generated from LufsX/Experiment-LogReg
This commit is contained in:
+11
-5
@@ -26,17 +26,23 @@ name = "陈垣豪"
|
||||
|
||||
|
||||
|
||||
|
||||
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):
|
||||
linear_model = np.dot(X, weights)
|
||||
# 直接使用线性模型的输出进行梯度更新
|
||||
dw = (1 / n_samples) * np.dot(X.T, (linear_model - y))
|
||||
# 随机选择一个样本
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user