Files
Experiment-LogReg/function.py
T
Dengddd d5a373a8f9
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s
更新 function.py
2024-10-30 10:52:26 +08:00

91 lines
2.4 KiB
Python

# function.py
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 = "202210423222"
name = "邓龙树"
import numpy as np
def load_data(filepath):
"""
从文件中加载数据。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 读取每一行作为字符串
with open(filepath, 'r') as file:
lines = file.readlines()
# 分割每一行并填充缺失的列
max_cols = 0
rows = []
for line in lines:
# 分割每一行
cols = line.strip().split(' ')
# 记录最大列数
max_cols = max(max_cols, len(cols))
rows.append(cols)
# 将所有行填充到相同的列数
for row in rows:
while len(row) < max_cols:
row.append('nan')
# 转换为numpy数组
data = np.array(rows, dtype=float)
# 用np.nan替换字符串'nan'
data[data == 'nan'] = np.nan
X = data[:, :-1] # 假设最后一列是标签
y = data[:, -1]
return X, y
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 = np.nan_to_num(X_train, nan=np.nanmean(X_train, axis=0))
X_test = np.nan_to_num(X_test, nan=np.nanmean(X_train, axis=0)) # 用训练集的均值替代测试集
# 确保标签为浮点型
y_train = y_train.astype(float)
y_test = y_test.astype(float)
# 训练对率回归模型
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]}")