generated from LufsX/Experiment-LogReg
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 46s
127 lines
3.7 KiB
Python
127 lines
3.7 KiB
Python
import os
|
|
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 = "202210423215"
|
|
name = "章程鸿"
|
|
|
|
|
|
# 这里写自己的代码实现
|
|
import numpy as np
|
|
from sklearn.model_selection import KFold
|
|
def sigmoid(z):
|
|
return 1 / (1 + np.exp(-z))
|
|
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|
"""
|
|
对率回归训练函数。
|
|
|
|
Args:
|
|
- X (numpy array): 特征数据。
|
|
- y (numpy array): 标签数据。
|
|
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
|
|
|
Returns:
|
|
- numpy array: 训练得到的权重。
|
|
"""
|
|
m, n = X.shape
|
|
weights = np.zeros(n)
|
|
bias = 0
|
|
for _ in range(iterations):
|
|
z = np.dot(X, weights) + bias
|
|
h = sigmoid(z)
|
|
dw = (1/m) * np.dot(X.T, (h - y))
|
|
db = (1/m) * np.sum(h - y)
|
|
weights -= learning_rate * dw
|
|
bias -= learning_rate * db
|
|
return weights
|
|
|
|
def predict_logreg(inX, weights):
|
|
"""
|
|
对率回归预测函数。
|
|
|
|
Args:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- weights (numpy array): 训练得到的权重。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
z = np.dot(inX, weights)
|
|
h = sigmoid(z)
|
|
return 1 if h >= 0.5 else 0
|
|
|
|
# 这里也写自己的代码实现
|
|
def load_data(filepath):
|
|
"""
|
|
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
|
|
|
Args:
|
|
- directory (str): 数据文件路径。
|
|
|
|
Returns:
|
|
- np.array: 特征数据。
|
|
- np.array: 标签数据。
|
|
"""
|
|
data = []
|
|
with open(filepath, 'r') as file:
|
|
for line in file:
|
|
# 清理无效数据
|
|
cleaned_line = line.strip().replace('?', '0') # 将问号替换为0
|
|
data.append([float(x) for x in cleaned_line.split()]) # 转换为浮点数
|
|
data = np.array(data)
|
|
X = data[:, :-1]
|
|
y = data[:, -1]
|
|
return X, y
|
|
def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000):
|
|
kf = KFold(n_splits=k)
|
|
accuracies = []
|
|
|
|
for train_index, test_index in kf.split(X):
|
|
X_train, X_test = X[train_index], X[test_index]
|
|
y_train, y_test = y[train_index], y[test_index]
|
|
|
|
weights = train_logreg(X_train, y_train, learning_rate, iterations)
|
|
predictions = [predict_logreg(x, weights) for x in X_test]
|
|
|
|
accuracy = np.mean(predictions == y_test)
|
|
accuracies.append(accuracy)
|
|
|
|
return np.mean(accuracies)
|
|
|
|
if __name__ == "__main__":
|
|
# 加载训练集
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
|
|
# 加载测试集
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
|
|
# 进行 K 折交叉验证
|
|
k = 5 # 设置折数
|
|
cv_accuracy = cross_validate(X_train, y_train, k=k, learning_rate=0.01, iterations=1000)
|
|
print(f"{k}-折交叉验证的平均准确率: {cv_accuracy:.2f}")
|
|
|
|
# 测试单个数据
|
|
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]}")
|