Files
Experiment-LogReg/function.py
T
Dengddd 9b0d573f0c
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s
更新 function.py
2024-10-31 14:35:31 +08:00

108 lines
3.1 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 = "邓龙树"
# user_code.py
import numpy as np
def sigmoid(z):
"""计算sigmoid函数"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""对率回归训练函数。"""
weights = np.zeros(X.shape[1])
for _ in range(iterations):
z = np.dot(X, weights)
predictions = sigmoid(z)
gradient = np.dot(X.T, (predictions - y)) / y.size
weights -= learning_rate * gradient
return weights
def predict_logreg(X, weights):
"""使用训练好的权重预测标签"""
z = np.dot(X, weights)
predictions = sigmoid(z)
return np.where(predictions >= 0.5, 1, 0)
def load_data(filepath):
"""从文件中加载数据,处理不规则列数问题"""
with open(filepath, 'r') as file:
lines = file.readlines()
max_columns = 0
data = []
for line in lines:
parts = line.strip().split()
max_columns = max(max_columns, len(parts))
data.append(parts)
# 填充缺失的列
for i in range(len(data)):
if len(data[i]) < max_columns:
data[i].extend(['nan'] * (max_columns - len(data[i])))
# 转换成numpy数组,处理缺失值
data_array = np.array(data, dtype=float)
data_array[np.isnan(data_array)] = np.nanmean(data_array, axis=0)
return data_array[:, :-1], data_array[:, -1]
def preprocess_data(X, y):
"""数据预处理,合并特征23的值,并删除特征3和特征24~28。"""
# 合并特征23的值:将2(死亡)和3(安乐死)合并为0(死亡)
y = np.where(y == 2, 0, y) # 将值2替换为0
y = np.where(y == 3, 0, y) # 将值3替换为0
# 删除特征3和特征24~28(假设特征索引从0开始)
X = np.delete(X, [2] + list(range(23, 28)), axis=1)
return X, y
if __name__ == "__main__":
# 加载数据
X, y = load_data("./data/horse-colic.data")
# 数据预处理
X, y = preprocess_data(X, y)
# 训练模型
weights = train_logreg(X, y)
# 加载测试数据并进行预处理
X_test, y_test = load_data("./data/horse-colic.test")
X_test, y_test = preprocess_data(X_test, y_test)
# 预测
predictions = predict_logreg(X_test, weights)
# 打印预测结果和实际结果
for i in range(min(10, len(y_test))):
print(f"预测结果: {predictions[i]}, 实际结果: {y_test[i]}")