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

This commit is contained in:
hao
2024-11-02 13:10:22 +08:00
parent ce1394eb5d
commit e001955acf
+12 -30
View File
@@ -1,29 +1,7 @@
import numpy as np
from sklearn.preprocessing import StandardScaler
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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 = "202210423228"
name = "黎世浩"
# 这里写自己的代码实现
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
"""
对率回归训练函数。
@@ -32,6 +10,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
- y (numpy array): 标签数据。
- learning_rate (float): 学习率,默认为0.01。
- iterations (int): 迭代次数,默认为1000。
- lambda_reg (float): L2正则化系数,默认为0.01。
Returns:
- numpy array: 训练得到的权重。
@@ -48,7 +27,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
# 计算梯度
gradient = x_i * (prediction - y_i)
# 更新权重
weights -= learning_rate * gradient
weights -= learning_rate * (gradient + lambda_reg * weights)
return weights
@@ -66,8 +45,6 @@ def predict_logreg(inX, weights):
prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0
import numpy as np
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -86,12 +63,12 @@ def load_data(filepath):
X = data[:, :-1]
y = data[:, -1]
# 将缺失值填充为0
X[np.isnan(X)] = 0
# 将缺失值填充为每列的平均值
for i in range(X.shape[1]):
X[:, i] = np.where(np.isnan(X[:, i]), np.nanmean(X[:, i]), X[:, i])
return X, y.astype(int)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
@@ -100,6 +77,11 @@ if __name__ == "__main__":
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)