更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 38s

This commit is contained in:
2024-10-31 18:17:48 +08:00
parent 656512a3d6
commit 242f28eb7e
+15 -23
View File
@@ -1,4 +1,3 @@
# function.py
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
@@ -8,36 +7,20 @@ from sklearn.model_selection import train_test_split
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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 = "202210423130"
name = "董秋"
# 这里写自己的代码实现
def train_logreg(X, y, learning_rate=0.01, iterations=1000,lambda_reg=0.01):
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零*。
Returns:
- numpy array: 训练得到的权重。
@@ -73,7 +56,7 @@ def predict_logreg(inX, weights):
prediction_prob = 1 / (1 + np.exp(-z))
return 1 if prediction_prob >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
data = []
labels = []
@@ -83,13 +66,23 @@ def load_data(filepath):
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
data.append(values[:-1]) # 特征
labels.append(values[-1]) # 标签
# 合并特征23的取值
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
labels.append(0) # 死亡
elif values[22] == 1:
labels.append(1) # 生存
else:
continue # 无效标签,丢弃
# 去掉特征3(索引2)和特征24~28(索引23-27)
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
except ValueError:
continue
return np.array(data), np.array(labels)
def preprocess_data(X):
# 特征标准化
scaler = StandardScaler()
@@ -107,8 +100,7 @@ if __name__ == "__main__":
X_test = preprocess_data(X_test)
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000,lambda_reg=0.01)
X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.01)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)