更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 31s

This commit is contained in:
2024-11-02 15:02:05 +08:00
parent 97a873a559
commit 8da0fd0717
+26 -18
View File
@@ -28,14 +28,14 @@ name = "章程鸿"
# 这里写自己的代码实现 # 这里写自己的代码实现
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from sklearn.preprocessing import StandardScaler, PolynomialFeatures from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, KFold from sklearn.model_selection import train_test_split, KFold
def sigmoid(z): def sigmoid(z):
"""Sigmoid 激活函数。""" """Sigmoid 激活函数。"""
return 1 / (1 + np.exp(-z)) 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 m, n = X.shape
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值 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 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 return weights
@@ -102,25 +106,20 @@ def load_data(filepath):
return data, labels return data, labels
def preprocess_data(X): def preprocess_data(X):
"""特征标准化并增加多项式特征。""" """特征标准化。"""
scaler = StandardScaler() scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) return scaler.fit_transform(X)
# 添加多项式特征
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X_scaled)
return X_poly
if __name__ == "__main__": 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) X_train = preprocess_data(X_train)
X_test = preprocess_data(X_test)
# 使用 train_test_split 打乱并随机抽取数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# K折交叉验证 # K折交叉验证
k = 5 k = 5
@@ -133,7 +132,7 @@ if __name__ == "__main__":
# 训练逻辑回归模型,设置 batch size # 训练逻辑回归模型,设置 batch size
batch_size = 32 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))] 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"K折交叉验证得分: {accuracies}")
print(f"平均准确率: {np.mean(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) y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")