From b966900456e5edbf79f353df203ea6081768bee5 Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 31 Oct 2024 15:12:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/function.py b/function.py index 10d11f6..0007b5b 100644 --- a/function.py +++ b/function.py @@ -50,15 +50,18 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, lambd weights = np.zeros(n) for _ in range(iterations): + # 确保 batch_size 不超过 m + effective_batch_size = min(batch_size, m) + # 随机选择一个小批量 - indices = np.random.choice(m, batch_size, replace=False) + indices = np.random.choice(m, effective_batch_size, replace=False) X_batch = X[indices] y_batch = y[indices] # 计算预测和梯度 z = np.dot(X_batch, weights) h = sigmoid(z) - gradient = np.dot(X_batch.T, (h - y_batch)) / batch_size + lambda_ * weights + gradient = np.dot(X_batch.T, (h - y_batch)) / effective_batch_size + lambda_ * weights weights -= learning_rate * gradient return weights