From b32dc0220d74141e3db2647bc8703312d0695ce8 Mon Sep 17 00:00:00 2001 From: 202210423105 <3374617300@qq.com> Date: Sun, 3 Nov 2024 16:15:01 +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 | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/function.py b/function.py index 750a541..a0aff78 100644 --- a/function.py +++ b/function.py @@ -23,12 +23,12 @@ import numpy as np 姓名请直接**填写中文** 例如: name = "张三" """ -id = "202210423xxx" -name = "test_name" +id = "202210423105" +name = "魏明帅" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ 对率回归训练函数。 @@ -40,7 +40,19 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ - +m, n = X.shape + weights = np.zeros(n) + + for _ in range(iterations): + for i in range(m): + x_i = X[i] + y_i = y[i] + z = np.dot(x_i, weights) + h = 1 / (1 + np.exp(-z)) + error = y_i - h + weights += learning_rate * error * x_i + + return weights def predict_logreg(inX, weights): """ @@ -53,7 +65,9 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - +z = np.dot(inX, weights) + h = 1 / (1 + np.exp(-z)) + return 1 if h >= 0.5 else 0 # 这里也写自己的代码实现 def load_data(filepath): @@ -67,7 +81,17 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ - +with open(filepath, 'r') as f: + lines = f.readlines() + + X = [] + y = [] + for line in lines: + values = line.strip().split() + y.append(int(values[-1])) + X.append([float(x) for x in values[:-1]]) + + return np.array(X), np.array(y) if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改