From 1308465b8855c517fcb63f983f083e33358fc823 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=9D=A8=E6=B4=8B?= <2445091977@qq.com> Date: Sat, 2 Nov 2024 21:08:35 +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 | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/function.py b/function.py index 6e2ab41..f189af5 100644 --- a/function.py +++ b/function.py @@ -14,21 +14,17 @@ def sigmoid(z): return 1 / (1 + np.exp(-z)) -def train_logreg(X, y, numIter=1000, learning_rate=0.06, batch_size=128, lambda_reg=0.01): +def train_logreg(X, y, numIter=1000, learning_rate=0.01, lambda_reg=0.01): m, n = X.shape weights = np.zeros(n) for j in range(numIter): - dataIndex = np.random.permutation(m) - for i in range(0, m, batch_size): - end = min(i + batch_size, m) - batch_X = X[dataIndex[i:end]] - batch_y = y[dataIndex[i:end]] - z = np.dot(batch_X, weights) - h = 1 / (1 + np.exp(-z)) - error = batch_y - h - gradient = np.dot(batch_X.T, error) / len(batch_y) - reg_term = 2 * lambda_reg * weights - gradient -= reg_term / len(batch_y) + for i in range(m): + z = np.dot(X[i], weights) + h = sigmoid(z) + error = y[i] - h + gradient = X[i] * error + reg_term = lambda_reg * weights + gradient += reg_term weights += learning_rate * gradient return weights @@ -45,7 +41,7 @@ def predict_logreg(inX, weights): - int: 预测的分类标签。 """ z = np.dot(inX, weights) - prob = 1 / (1 + np.exp(-z)) + prob = sigmoid(z) return 1 if prob >= 0.5 else 0