Files
Experiment-LogReg/function.py
T
lzh c73871005a
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 22s
4544444
2024-11-02 21:33:01 +08:00

69 lines
2.1 KiB
Python

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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):
# 使用 numpy 的 genfromtxt 函数加载数据,自动处理缺失值
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)
# 删除不相关特征(如果需要)
# features = np.delete(features, [2] + list(range(23, 28)), axis=1)
# 数据标准化
scaler = StandardScaler()
features = scaler.fit_transform(features)
return features, labels
def train_logreg(X, y, random_state=42):
# 创建逻辑回归模型,使用liblinear求解器
model = LogisticRegression(solver='liblinear', random_state=random_state)
model.fit(X, y)
return model
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}")