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

This commit is contained in:
2024-10-31 16:02:06 +08:00
parent 2c88287c22
commit 1682939bdb
+12 -9
View File
@@ -1,31 +1,35 @@
import numpy as np
id = "202210423213" # 请填写学号
name = "熊浩燃" # 请填写姓名
def sigmoid(z):
"""计算Sigmoid函数值"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def train_logreg(X, y, learning_rate=0.01, iterations=5000, reg_lambda=0.1):
"""
对率回归训练函数。
对率回归训练函数,带正则化项。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率,默认为0.01。
- iterations (int): 梯度下降迭代次数,默认为1000。
- iterations (int): 梯度下降迭代次数,默认为5000。
- reg_lambda (float): L2正则化系数,默认为0.1。
Returns:
- numpy array: 训练得到的权重。
"""
# 数据标准化
X = (X - X.mean(axis=0)) / X.std(axis=0)
# 初始化权重
weights = 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)
# 更新权重,带L2正则化
weights += learning_rate * (np.dot(X.T, errors) - reg_lambda * weights)
return weights
@@ -54,7 +58,6 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.genfromtxt(filepath, delimiter=" ", dtype=float, missing_values="?", filling_values=np.nan)
# 使用列均值填充缺失值
@@ -74,7 +77,7 @@ if __name__ == "__main__":
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, reg_lambda=0.1)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)