更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s

This commit is contained in:
2024-11-03 20:44:21 +08:00
parent e8e2071256
commit b9ed65b7db
+11 -5
View File
@@ -26,17 +26,23 @@ name = "陈垣豪"
def train_logreg(X, y, learning_rate=0.01, iterations=1000): def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""训练逻辑回归模型.""" """训练逻辑回归模型,使用随机梯度下降."""
n_samples, n_features = X.shape n_samples, n_features = X.shape
weights = np.zeros(n_features + 1) # 增加一位用于偏置 weights = np.zeros(n_features + 1) # 增加一位用于偏置
X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项 X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项
for _ in range(iterations): for _ in range(iterations):
linear_model = np.dot(X, weights) # 随机选择一个样本
# 直接使用线性模型的输出进行梯度更新 random_index = np.random.randint(n_samples)
dw = (1 / n_samples) * np.dot(X.T, (linear_model - y)) 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 weights -= learning_rate * dw
return weights return weights