generated from LufsX/Experiment-LogReg
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 1m13s
94 lines
2.5 KiB
Python
94 lines
2.5 KiB
Python
import numpy as np
|
|
|
|
"""
|
|
实验说明:
|
|
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
|
"""
|
|
|
|
# 填写学号和姓名
|
|
id = "202210423213" # 请替换为实际学号
|
|
name = "熊浩燃" # 请替换为实际姓名
|
|
|
|
def sigmoid(z):
|
|
"""计算Sigmoid函数值"""
|
|
return 1 / (1 + np.exp(-z))
|
|
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=5000, reg_lambda=0.1):
|
|
"""
|
|
对率回归训练函数,带正则化项。
|
|
|
|
Args:
|
|
- X (numpy array): 特征数据。
|
|
- y (numpy array): 标签数据。
|
|
- learning_rate (float): 学习率,默认为0.01。
|
|
- iterations (int): 梯度下降迭代次数,默认为5000。
|
|
- reg_lambda (float): L2正则化系数,默认为0.1。
|
|
|
|
Returns:
|
|
- numpy array: 训练得到的权重。
|
|
"""
|
|
# 数据标准化
|
|
X = (X - X.mean(axis=0)) / X.std(axis=0)
|
|
|
|
# 初始化权重
|
|
weights = np.zeros(X.shape[1])
|
|
|
|
# 批量梯度下降
|
|
for i in range(iterations):
|
|
predictions = sigmoid(np.dot(X, weights))
|
|
errors = y - predictions
|
|
# 更新权重,带L2正则化
|
|
weights += learning_rate * (np.dot(X.T, errors) - reg_lambda * weights)
|
|
|
|
return weights
|
|
|
|
def predict_logreg(inX, weights):
|
|
"""
|
|
对率回归预测函数。
|
|
|
|
Args:
|
|
- inX (numpy array): 输入待分类的样本。
|
|
- weights (numpy array): 训练得到的权重。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
probability = sigmoid(np.dot(inX, weights))
|
|
return 1 if probability >= 0.5 else 0
|
|
|
|
def load_data(filepath):
|
|
"""
|
|
从文件中加载数据,并填充缺失值。
|
|
|
|
Args:
|
|
- filepath (str): 数据文件路径。
|
|
|
|
Returns:
|
|
- np.array: 特征数据。
|
|
- np.array: 标签数据。
|
|
"""
|
|
data = np.genfromtxt(filepath, delimiter=" ", dtype=float, missing_values="?", filling_values=np.nan)
|
|
|
|
# 使用列均值填充缺失值
|
|
col_means = np.nanmean(data, axis=0)
|
|
indices = np.where(np.isnan(data))
|
|
data[indices] = np.take(col_means, indices[1])
|
|
|
|
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")
|
|
|
|
# 训练对率回归模型
|
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, reg_lambda=0.1)
|
|
|
|
# 测试单个数据
|
|
y_pred = predict_logreg(X_test[11], weights)
|
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|