Files
Experiment23/function.py
T
ywq157 6745f2983e
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 14s
更新 function.py
2024-11-12 20:08:44 +08:00

77 lines
2.0 KiB
Python

# function.py
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
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423113"
name = "杨文强"
# 这里写自己的代码实现
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
m, n = X.shape
weights = np.zeros(n)
for i in range(iterations):
for j in range(m):
z = np.dot(X[j], weights)
h = sigmoid(z)
error = y[j] - h
weights += learning_rate * error * X[j]
return weights
def predict_logreg(inX, weights):
z = np.dot(inX, weights)
h = sigmoid(z)
if h > 0.5:
return 1
else:
return 0
# 这里也写自己的代码实现
def load_data(filepath):
data = np.loadtxt(filepath, delimiter=' ')
X = data[:, :-1]
y = data[:, -1]
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")