Files
Experiment-LogReg/function.py
T
lzh 28749fc571
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 27s
444
2024-11-02 21:41:11 +08:00

67 lines
2.1 KiB
Python

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearchCV
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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 = "202210423221"
name = "廖子豪"
def load_data(filepath):
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
labels = data[:, -1].astype(int)
features = data[:, :-1]
# 将标签转换为二分类问题
labels = np.where((labels == 2) | (labels == 3), 1, 0)
# 数据标准化
scaler = StandardScaler()
features = scaler.fit_transform(features)
return features, labels
def train_logreg(X, y, random_state=42):
# 使用 GridSearchCV 进行参数调优
param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'penalty': ['l1', 'l2']}
model = LogisticRegression(solver='liblinear', random_state=random_state)
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X, y)
return grid_search.best_estimator_
def predict_logreg(inX, model):
return int(model.predict([inX])[0])
# 示例使用
if __name__ == "__main__":
# 加载训练数据和测试数据
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 训练模型
model = train_logreg(X_train, y_train, random_state=42)
# 进行预测
y_pred = [predict_logreg(x, model) for x in X_test]
# 计算准确率
accuracy = np.mean(y_pred == y_test)
print(f"Test Accuracy: {accuracy:.2f}")