generated from LufsX/Experiment-LogReg
90 lines
3.2 KiB
Python
90 lines
3.2 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 = "202210423217"
|
|
name = "吴俊煯"
|
|
|
|
|
|
# 这里写自己的代码实现
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.0):
|
|
m, n = X.shape
|
|
weights = np.zeros(n)
|
|
bias = 0
|
|
m = len(X) # 重新赋值m,以确保它表示样本数量(在添加正则化时可能需要)
|
|
|
|
for _ in range(iterations):
|
|
linear_output = np.dot(X, weights) + bias # 向量化操作
|
|
y_predicted = 1 / (1 + np.exp(-linear_output))
|
|
error = y - y_predicted
|
|
|
|
# 更新权重和偏置,添加正则化项
|
|
weights += learning_rate * (error * X.T - regularization * weights) / m
|
|
bias += learning_rate * np.sum(error) / m
|
|
|
|
return weights, bias
|
|
|
|
def predict_logreg(inX, weights):
|
|
linear_output = np.dot(inX, weights) + bias
|
|
y_predicted = 1 if linear_output >= 0 else 0 # 简化判断条件,因为逻辑回归输出已经通过sigmoid函数处理
|
|
return y_predicted
|
|
|
|
# 这里也写自己的代码实现
|
|
def load_data(filepath):
|
|
data = []
|
|
with open(filepath, 'r') as file:
|
|
for line in file:
|
|
parts = [part.strip() for part in line.split()]
|
|
features = [float(part) if part != '?' else 0 for part in parts[:-1]]
|
|
label = int(parts[-1]) - 1 # 假设标签是{1, 2},转换为{0, 1}
|
|
data.append(features + [label])
|
|
data_array = np.array(data)
|
|
X = data_array[:, :-1]
|
|
y = data_array[:, -1]
|
|
return X, y
|
|
|
|
def evaluate_model(X, y, weights, bias):
|
|
predictions = [predict_logreg(x, weights, bias) for x in X]
|
|
accuracy = np.mean(predictions == y)
|
|
return accuracy
|
|
|
|
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_mean = np.mean(X_train, axis=0)
|
|
X_train_std = np.std(X_train, axis=0)
|
|
X_train = (X_train - X_train_mean) / X_train_std
|
|
X_test = (X_test - X_train_mean) / X_train_std # 使用训练集的标准差来标准化测试集
|
|
|
|
# 训练逻辑回归模型
|
|
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, regularization=0.1)
|
|
|
|
# 评估模型性能
|
|
accuracy = evaluate_model(X_test, y_test, weights, bias)
|
|
print(f"测试集准确率: {accuracy:.2f}")
|
|
|
|
# 测试单个数据(可选)
|
|
y_pred = predict_logreg(X_test[11], weights, bias)
|
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|