From 8da0fd0717abf3bbe058978de1aab6076c23b728 Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Sat, 2 Nov 2024 15:02:05 +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 | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/function.py b/function.py index 5588f71..6f1fc4e 100644 --- a/function.py +++ b/function.py @@ -28,14 +28,14 @@ name = "章程鸿" # 这里写自己的代码实现 import numpy as np import pandas as pd -from sklearn.preprocessing import StandardScaler, PolynomialFeatures +from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split, KFold def sigmoid(z): """Sigmoid 激活函数。""" return 1 / (1 + np.exp(-z)) -def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32): +def train_logreg(X, y, learning_rate=0.01, iterations=5000, lambda_reg=0.01, batch_size=32): """逻辑回归训练函数,随机初始化权重,并在每次迭代前打乱数据。""" m, n = X.shape weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值 @@ -61,7 +61,11 @@ def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batc weights -= learning_rate * gradient # 动态调整学习率 - learning_rate *= 0.99 # 每次迭代稍微减小学习率 + if i % 1000 == 0: # 每1000次迭代调整一次学习率 + learning_rate *= 0.9 # 每1000次迭代减小学习率 + + if i % 100 == 0: # 每100次迭代输出一次学习率 + print(f"Iteration {i}, Learning Rate: {learning_rate}") return weights @@ -81,7 +85,7 @@ def load_data(filepath): values = line.strip().replace('?', '0').split() try: values = [float(v) for v in values] - + # 合并特征23的取值 if values[22] == 2 or values[22] == 3: # 特征23(索引22) labels.append(0) # 死亡 @@ -89,7 +93,7 @@ def load_data(filepath): labels.append(1) # 生存 else: continue # 无效标签,丢弃 - + # 用0填充缺失值 values = [0 if v == 0 else v for v in values] # 直接用0填充 data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23 @@ -102,25 +106,20 @@ def load_data(filepath): return data, labels def preprocess_data(X): - """特征标准化并增加多项式特征。""" + """特征标准化。""" scaler = StandardScaler() - X_scaled = scaler.fit_transform(X) - - # 添加多项式特征 - poly = PolynomialFeatures(degree=2, include_bias=False) - X_poly = poly.fit_transform(X_scaled) - - return X_poly + return scaler.fit_transform(X) if __name__ == "__main__": - # 加载数据集 - X, y = load_data("./data/horse-colic.data") + # 加载训练集 + X_train, y_train = load_data("./data/horse-colic.data") + + # 加载测试集 + X_test, y_test = load_data("./data/horse-colic.test") # 归一化数据 - X = preprocess_data(X) - - # 使用 train_test_split 打乱并随机抽取数据 - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + X_train = preprocess_data(X_train) + X_test = preprocess_data(X_test) # K折交叉验证 k = 5 @@ -133,7 +132,7 @@ if __name__ == "__main__": # 训练逻辑回归模型,设置 batch size batch_size = 32 - weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=batch_size) + weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.01, iterations=5000, lambda_reg=0.01, batch_size=batch_size) # 验证模型 val_predictions = [predict_logreg(X_val_kf[i], weights) for i in range(len(X_val_kf))] @@ -144,7 +143,16 @@ if __name__ == "__main__": print(f"K折交叉验证得分: {accuracies}") print(f"平均准确率: {np.mean(accuracies)}") + # 在测试集上测试模型 + test_predictions = [predict_logreg(X_test[i], weights) for i in range(len(X_test))] + test_accuracy = np.mean(test_predictions == y_test) + print(f"测试集准确率: {test_accuracy}") + # 测试单个数据 y_pred = predict_logreg(X_test[11], weights) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + + + +