From 27ca4c74202f4591446d0164f44436b320125caf Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 31 Oct 2024 15:53:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 136 +++++++++++++++++++--------------------------------- 1 file changed, 49 insertions(+), 87 deletions(-) diff --git a/function.py b/function.py index 8e957e0..a328c53 100644 --- a/function.py +++ b/function.py @@ -1,133 +1,95 @@ import numpy as np from sklearn.linear_model import LogisticRegression -from sklearn.metrics import accuracy_score +from sklearn.impute import SimpleImputer -id = "202210423213" -name = "熊浩燃" +""" +实验说明: +- 自行编写实现数据加载与预测病马死亡的对率回归算法。 + +注意事项: +- 在 function.py 中实现对率回归算法。 +- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 +- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。 + +测评环境: +- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz +- OS: Ubuntu 22.04.4 LTS +- Python: 3.10.12 +- numpy: 2.1.1 +""" + +id = "202210423xxx" # 请填写学号 +name = "test_name" # 请填写姓名 -def sigmoid(z): - """计算Sigmoid函数值""" - return 1 / (1 + np.exp(-z)) - - -def train_logreg(X, y, learning_rate=0.01, iterations=1000, initial_weights=None): +def train_logreg(X, y, max_iter=1000, C=1.0): """ - 对率回归训练函数,支持暴力搜索超参数。 + 对率回归训练函数,使用sklearn的LogisticRegression。 Args: - X (numpy array): 特征数据。 - y (numpy array): 标签数据。 - - learning_rate (float): 学习率,默认为0.01。 - - iterations (int): 梯度下降迭代次数,默认为1000。 - - initial_weights (numpy array): 预设初始权重,可选。 + - max_iter (int): 最大迭代次数。 + - C (float): 正则化强度。 Returns: - - numpy array: 训练得到的权重。 + - sklearn LogisticRegression: 训练好的模型。 """ - # 初始化权重 - weights = initial_weights if initial_weights is not None else np.zeros(X.shape[1]) - - # 梯度下降 - for i in range(iterations): - predictions = sigmoid(np.dot(X, weights)) - errors = y - predictions - weights += learning_rate * np.dot(X.T, errors) - - return weights + # 使用sklearn的LogisticRegression模型 + model = LogisticRegression(max_iter=max_iter, C=C) + model.fit(X, y) + return model -def predict_logreg(inX, weights): +def predict_logreg(inX, model): """ 对率回归预测函数。 Args: - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 + - model (LogisticRegression): 训练得到的LogisticRegression模型。 Returns: - int: 预测的分类标签。 """ - probability = sigmoid(np.dot(inX, weights)) - return 1 if probability >= 0.5 else 0 + return int(model.predict(inX.reshape(1, -1))[0]) def load_data(filepath): """ - 从文件中加载数据并填充缺失值。确保每列的缺失值被正确填充为该列的均值。 + 从文件中加载数据并填充缺失值。 Args: - filepath (str): 数据文件路径。 Returns: - - np.array: 特征数据。 + - np.array: 填充缺失值后的特征数据。 - np.array: 标签数据。 """ - # 加载数据,处理缺失值(使用 nan 表示缺失数据) - data = np.genfromtxt(filepath, delimiter=",", dtype=float, missing_values="?", filling_values=np.nan) + # 加载数据 + data = np.loadtxt(filepath, delimiter=",", dtype=float) - # 特征和标签分离 - X = data[:, :-1] - y = data[:, -1] + # 分割特征和标签 + X = data[:, :-1] # 特征 + y = data[:, -1] # 标签 - # 对每列特征数据进行缺失值填充 - col_means = np.nanmean(X, axis=0) - inds = np.where(np.isnan(X)) - X[inds] = np.take(col_means, inds[1]) + # 填充缺失值,使用列的平均值 + imputer = SimpleImputer(strategy="mean") + X = imputer.fit_transform(X) return X, y -def brute_force_search(X_train, y_train, X_val, y_val, learning_rates, iterations_list): - """ - 通过暴力搜索选择最佳的学习率和迭代次数。 - - Args: - - X_train, y_train: 训练集特征和标签。 - - X_val, y_val: 验证集特征和标签。 - - learning_rates (list of floats): 学习率列表。 - - iterations_list (list of ints): 迭代次数列表。 - - Returns: - - tuple: 最佳学习率,最佳迭代次数,最佳权重。 - """ - best_acc = 0 - best_params = (0, 0) - best_weights = None - - for lr in learning_rates: - for iters in iterations_list: - weights = train_logreg(X_train, y_train, learning_rate=lr, iterations=iters) - y_pred = [predict_logreg(x, weights) for x in X_val] - acc = accuracy_score(y_val, y_pred) - - if acc > best_acc: - best_acc = acc - best_params = (lr, iters) - best_weights = weights - - print(f"最佳学习率: {best_params[0]}, 最佳迭代次数: {best_params[1]}, 验证集准确率: {best_acc}") - return best_params[0], best_params[1], best_weights - - if __name__ == "__main__": - # 加载训练集和测试集 + # 加载训练集 X_train, y_train = load_data("./data/horse-colic.data") + + # 加载测试集 X_test, y_test = load_data("./data/horse-colic.test") - # 使用暴力搜索找到最佳的超参数组合 - learning_rates = [0.001, 0.01, 0.1] - iterations_list = [500, 1000, 1500] - best_lr, best_iters, best_weights = brute_force_search(X_train, y_train, X_test, y_test, learning_rates, iterations_list) + # 训练对率回归模型 + model = train_logreg(X_train, y_train, max_iter=1000, C=1.0) - # 使用 sklearn 进行对比 - sklearn_model = LogisticRegression(max_iter=best_iters, solver='lbfgs') - sklearn_model.fit(X_train, y_train) - y_pred_sklearn = sklearn_model.predict(X_test) - sklearn_acc = accuracy_score(y_test, y_pred_sklearn) - print(f"Sklearn Logistic Regression 准确率: {sklearn_acc}") - - # 测试对率回归预测 - y_pred_custom = [predict_logreg(x, best_weights) for x in X_test] - custom_acc = accuracy_score(y_test, y_pred_custom) - print(f"自实现 Logistic Regression 准确率: {custom_acc}") + # 测试单个数据 + y_pred = predict_logreg(X_test[11], model) + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")