generated from LufsX/Experiment-LogReg
This commit is contained in:
+8
-7
@@ -10,15 +10,16 @@ def sigmoid(z):
|
||||
"""
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
对率回归训练函数,加入了 L2 正则化。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认值为 0.01。
|
||||
- iterations (int): 梯度下降迭代次数,默认值为 1000。
|
||||
- lambda_reg (float): 正则化强度,默认值为 0.1。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
@@ -34,13 +35,13 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
# 计算误差
|
||||
error = predictions - y
|
||||
|
||||
# 更新权重
|
||||
gradient = np.dot(X.T, error) / len(y)
|
||||
# 计算梯度,并加入正则化项
|
||||
gradient = np.dot(X.T, error) / len(y) + lambda_reg * weights / len(y)
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
# 每 100 次迭代输出一次损失
|
||||
if i % 100 == 0:
|
||||
loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
|
||||
loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) + (lambda_reg / (2 * len(y))) * np.sum(weights**2)
|
||||
print(f"Iteration {i}, Loss: {loss:.4f}")
|
||||
|
||||
return weights
|
||||
@@ -101,8 +102,8 @@ if __name__ == "__main__":
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 训练对率回归模型,增加迭代次数为 5000 次
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000)
|
||||
# 训练对率回归模型,加入正则化并增加迭代次数为 5000 次
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, lambda_reg=0.1)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
|
||||
Reference in New Issue
Block a user