From 74963892ae8e2344b58c88264d07bb8b938bbd29 Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Tue, 29 Oct 2024 09:22:31 +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 | 87 +++++++++++++++++++++++++++++------------------------ 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/function.py b/function.py index 1b8489d..4c3e626 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ # function.py import numpy as np - +from sklearn.preprocessing import StandardScaler +from sklearn.metrics import accuracy_score """ 实验说明: - 自行编写实现数据加载与预测病马死亡的对率回归算法。 @@ -26,64 +27,70 @@ name = "吴俊煯" # 这里写自己的代码实现 -def train_logreg(X, y, learning_rate=0.1, iterations=100): +def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1): m, n = X.shape weights = np.zeros(n) bias = 0 for _ in range(iterations): - for idx, x_i in enumerate(X): - linear_output = np.dot(x_i, weights) + bias - y_predicted = 1 / (1 + np.exp(-linear_output)) - - # 计算误差 - error = y[idx] - y_predicted - - # 更新权重和偏置 - weights += learning_rate * error * x_i - bias += learning_rate * error + linear_output = np.dot(X, weights) + bias + y_predicted = 1 / (1 + np.exp(-linear_output)) + + # 计算梯度(包括正则化项) + dw = (1 / m) * np.dot(X.T, (y_predicted - y)) + (lambda_reg / m) * weights + db = (1 / m) * np.sum(y_predicted - y) + + # 更新权重和偏置 + weights -= learning_rate * dw + bias -= learning_rate * db - return weights + return weights, bias -def predict_logreg(inX, weights): - linear_output = np.dot(inX, weights) - y_predicted = 1 / (1 + np.exp(-linear_output)) - - # 将输出转换为分类标签 - return 1 if y_predicted >= 0.5 else 0 +def predict_logreg(inX, weights, bias): + linear_output = np.dot(inX, weights) + bias + y_predicted = 1 if linear_output >= 0 else 0 # 简化阈值判断,因为已经通过sigmoid函数输出 + # 注意:这里为了与原始代码保持一致,使用了0.5作为阈值,但实际上由于sigmoid输出范围在(0,1),可以直接比较linear_output和0 + # return 1 if y_predicted >= 0.5 else 0 # 等价于上面的判断,但多余计算了sigmoid + return y_predicted # 这里也写自己的代码实现 def load_data(filepath): data = [] with open(filepath, 'r') as file: for line in file: - # 分割行,并去除任何可能的空白字符 - parts = [part.strip() for part in line.split()] - # 将缺失值'?'替换为0(或者你可以选择其他适当的处理方式) - features = [float(part) if part != '?' else 1 for part in parts[:-1]] - # 将标签从2转换为1(如果原始标签是1和2的话) - label = int(parts[-1]) - 1 # 假设原始标签是1和2,转换为0和1 + parts = line.strip().split() + # 将缺失值'?'替换为np.nan,然后使用0填充(或选择其他适当的填充策略) + features = [float(part) if part != '?' else np.nan for part in parts[:-1]] + # 填充NaN值(这里选择0,但也可以考虑使用均值、中位数等) + features = np.nan_to_num(features, nan=0.0) + # 将标签从2转换为1(如果原始标签是1和2的话),这里假设标签已经是0和1 + label = int(parts[-1]) # 假设标签已经是0和1,无需转换 data.append(features + [label]) - - # 将数据转换为numpy数组 + data_array = np.array(data) + X = data_array[:, :-1] + y = data_array[:, -1] - # 分离特征和标签 - X = data_array[:, :-1] # 所有行,除了最后一列 - y = data_array[:, -1] # 所有行的最后一列 + # 特征缩放(标准化) + scaler = StandardScaler() + X_scaled = scaler.fit_transform(X) - return X, y + return X_scaled, y if __name__ == "__main__": - # 加载训练集 + # 加载训练集和测试集 X_train, y_train = load_data("./data/horse-colic.data") - - # 加载测试集 X_test, y_test = load_data("./data/horse-colic.test") - + # 训练对率回归模型 - weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) - - # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") \ No newline at end of file + weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.1) + + # 测试模型并评估性能 + y_pred = [predict_logreg(x, weights, bias) for x in X_test] + accuracy = accuracy_score(y_test, y_pred) + print(f"模型准确率: {accuracy}") + + # 打印单个测试样本的预测结果和实际结果(示例) + # 注意:索引11可能需要根据实际测试集调整,这里仅作为示例 + sample_index = 11 # 假设要测试的样本索引是11(注意:索引可能需要根据实际数据调整) + print(f"预测结果: {y_pred[sample_index]}, 实际结果: {y_test[sample_index]}") \ No newline at end of file