generated from LufsX/Experiment-LogReg
107 lines
2.9 KiB
Python
107 lines
2.9 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):
|
|
"""
|
|
对率回归训练函数。
|
|
|
|
Args:
|
|
- X (numpy array): 特征数据。
|
|
- y (numpy array): 标签数据。
|
|
- learning_rate (float): 学习率,默认值为0.01。
|
|
- iterations (int): 迭代次数,默认值为1000。
|
|
|
|
Returns:
|
|
- weights (numpy array): 训练得到的权重。
|
|
"""
|
|
# 初始化权重
|
|
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]
|
|
|
|
# 主逻辑
|
|
if __name__ == "__main__":
|
|
# 加载数据
|
|
X, y = load_data('path_to_data_file.txt')
|
|
|
|
# 训练模型
|
|
weights = train_logreg(X, y)
|
|
|
|
# 加载测试数据并预测
|
|
X_test, y_test = load_data('path_to_test_data_file.txt')
|
|
predictions = predict_logreg(X_test, weights)
|
|
|
|
# 打印预测结果和实际结果
|
|
for i in range(min(10, len(y_test))): # 打印前10个结果或全部结果,取决于测试数据量
|
|
print(f"预测结果: {predictions[i]}, 实际结果: {y_test[i]}")
|