generated from LufsX/Experiment-LogReg
82 lines
2.6 KiB
Python
82 lines
2.6 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 = "202210423204"
|
|
name = "陈垣豪"
|
|
|
|
|
|
def load_data(filepath):
|
|
"""加载数据并处理缺失值."""
|
|
data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan)
|
|
nan_columns = np.isnan(data)
|
|
mean_values = np.nanmean(data, axis=0)
|
|
data[nan_columns] = np.take(mean_values, np.where(nan_columns)[1])
|
|
X = data[:, :-1]
|
|
y = data[:, -1]
|
|
return X, y
|
|
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|
"""训练逻辑回归模型,使用随机梯度下降."""
|
|
n_samples, n_features = X.shape
|
|
weights = np.zeros(n_features + 1) # 增加一位用于偏置
|
|
X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项
|
|
|
|
for _ in range(iterations):
|
|
random_index = np.random.randint(n_samples)
|
|
X_i = X[random_index]
|
|
y_i = y[random_index]
|
|
|
|
linear_model = np.dot(X_i, weights)
|
|
dw = (linear_model - y_i) * X_i
|
|
weights -= learning_rate * dw
|
|
|
|
return weights
|
|
|
|
def predict_logreg(inX, weights):
|
|
"""使用线性模型预测结果."""
|
|
inX = np.append(inX, 1) # 增加偏置项
|
|
linear_model = np.dot(inX, weights)
|
|
return 1.0 if linear_model >= 0 else 2.0
|
|
|
|
if __name__ == "__main__":
|
|
# 示例:加载数据并训练模型
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)
|
|
|
|
# 测试单个数据
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
y_pred = predict_logreg(X_test[11], weights)
|
|
|
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
|
|
|
|
# 训练逻辑回归模型
|
|
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)
|
|
|
|
# 测试单个数据
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
X_test = scaler.transform(X_test) # 同样标准化测试集
|
|
y_pred = predict_logreg(X_test[11], weights)
|
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
|