generated from LufsX/Experiment-LogReg
This commit is contained in:
+9
-5
@@ -25,6 +25,8 @@ id = "202210423204"
|
||||
name = "陈垣豪"
|
||||
|
||||
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""训练逻辑回归模型,使用随机梯度下降."""
|
||||
@@ -33,15 +35,11 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
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
|
||||
|
||||
@@ -67,10 +65,16 @@ if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
|
||||
# 训练逻辑回归模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||
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]}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user