上传文件至 /
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 10s

This commit is contained in:
2024-11-03 14:53:59 +08:00
parent 6fc047bbd9
commit 2d347b73b1
+26 -6
View File
@@ -1,12 +1,26 @@
import numpy as np
"""实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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 = "202210423104"
name = "张钦诚"
# 对率回归实现
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization_strength=0.01):
"""对率回归训练函数。
Args:
@@ -14,6 +28,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
- y (numpy array): 标签数据。
- learning_rate (float): 学习率。
- iterations (int): 训练次数。
- regularization_strength (float): L2正则化强度。
Returns:
- numpy array: 训练得到的权重。
@@ -23,7 +38,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
for _ in range(iterations):
predictions = 1 / (1 + np.exp(-np.dot(X, weights)))
errors = y - predictions
gradient = np.dot(X.T, errors) / m
gradient = np.dot(X.T, errors) / m - regularization_strength * weights / m
weights += learning_rate * gradient
return weights
@@ -74,8 +89,13 @@ 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=2000, regularization_strength=0.1)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
# 测试数据集
correct_predictions = 0
for i in range(len(X_test)):
y_pred = predict_logreg(X_test[i], weights)
if y_pred == y_test[i]:
correct_predictions += 1
accuracy = correct_predictions / len(X_test)
print(f"测试出的正确率: {accuracy * 100:.2f}%")