Files
Experiment_2/function.py
T
hao cf6cb2c1a1
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 13s
更新 function.py
2024-11-02 13:19:45 +08:00

74 lines
2.2 KiB
Python

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 = "202210423228"
name = "黎世浩"
def load_data(filepath):
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?')
X = data[:, :-1]
y = data[:, -1]
# 将缺失值填充为每列的平均值
for i in range(X.shape[1]):
X[:, i] = np.where(np.isnan(X[:, i]), np.mean(X[:, i]), X[:, i])
return X, y.astype(int)
def scale_features(X):
mean = np.mean(X, axis=0)
std = np.std(X, axis=0)
std[std == 0] = 1
scaled_X = (X - mean) / std
return scaled_X
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
m, n = X.shape
weights = np.zeros(n)
for _ in range(iterations):
for i in range(m):
x_i = X[i]
y_i = y[i]
prediction = 1 / (1 + np.exp(-np.dot(x_i, weights)))
gradient = x_i * (prediction - y_i)
weights -= learning_rate * (gradient + lambda_reg * weights)
return weights
def predict_logreg(inX, weights):
prediction = 1 / (1 + np.exp(-np.dot(inX, weights)))
return 1 if prediction > 0.5 else 0
if __name__ == "__main__":
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
X_train_scaled = scale_features(X_train)
X_test_scaled = scale_features(X_test)
weights = train_logreg(X_train_scaled, y_train, learning_rate=0.01, iterations=1000)
# 测试模型
y_pred = [predict_logreg(x, weights) for x in X_test_scaled]
accuracy = np.mean(y_pred == y_test)
print(f"Accuracy: {accuracy}")