From 8f57fdf0cc5639ae78f7066642b1d475449ca00d Mon Sep 17 00:00:00 2001 From: YimingTang Date: Thu, 24 Oct 2024 17:28:36 +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, 19 insertions(+), 3 deletions(-) diff --git a/function.py b/function.py index 409b1ac..b176385 100644 --- a/function.py +++ b/function.py @@ -21,8 +21,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423218" +name = "唐一鸣" # 这里写自己的代码实现 @@ -38,6 +38,17 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ + m, n = X.shape # 样本数和特征数 + weights = np.zeros(n) # 初始化权重 + for _ in range(iterations): + # 计算当前模型的预测值 + z = np.dot(X, weights) + h = sigmoid(z) + # 计算损失函数的梯度 + gradient = np.dot(X.T, (h - y)) / m + # 更新权重 + weights -= learning_rate * gradient + return weights def predict_logreg(inX, weights): @@ -51,7 +62,8 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - + probability = sigmoid(np.dot(inX, weights)) + return 1 if probability >= 0.5 else 0 # 这里也写自己的代码实现 def load_data(filepath): @@ -65,6 +77,10 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ + data = np.loadtxt(filepath, delimiter=' ', dtype=float) + X = data[:, :-1] # 特征数据 + y = data[:, -1] # 标签数据 + return X, y if __name__ == "__main__":