generated from LufsX/Experiment-LogReg
122 lines
3.5 KiB
Python
122 lines
3.5 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 = []
|
|
for row in data:
|
|
cleaned_row = []
|
|
for value in row:
|
|
if value == '?': # 替换无法转换的值
|
|
cleaned_row.append(np.nan)
|
|
else:
|
|
cleaned_row.append(float(value)) # 转换为float
|
|
data_array.append(cleaned_row)
|
|
|
|
data_array = np.array(data_array)
|
|
|
|
# 处理缺失值
|
|
col_mean = np.nanmean(data_array, axis=0)
|
|
for i in range(data_array.shape[1]):
|
|
data_array[np.isnan(data_array[:, i]), i] = col_mean[i]
|
|
|
|
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]}")
|