From c408fbace3edaec2c1a78d3eeb3127498a0846e7 Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Tue, 29 Oct 2024 07:48:23 +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 | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/function.py b/function.py index 409b1ac..b532259 100644 --- a/function.py +++ b/function.py @@ -21,12 +21,12 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423217" +name = "吴俊煯" # 这里写自己的代码实现 -def train_logreg(X, y, other_params="你自己设置一些其它参数"): +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ 对率回归训练函数。 @@ -38,7 +38,23 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"): Returns: - numpy array: 训练得到的权重。 """ - + m, n = X.shape + weights = np.zeros(n) + bias = 0 + + for _ in range(iterations): + for idx, x_i in enumerate(X): + linear_output = np.dot(x_i, weights) + bias + y_predicted = 1 / (1 + np.exp(-linear_output)) + + # 计算误差 + error = y[idx] - y_predicted + + # 更新权重和偏置 + weights += learning_rate * error * x_i + bias += learning_rate * error + + return weights def predict_logreg(inX, weights): """ @@ -51,7 +67,11 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - + linear_output = np.dot(inX, weights) + y_predicted = 1 / (1 + np.exp(-linear_output)) + + # 将输出转换为分类标签 + return 1 if y_predicted >= 0.5 else 0 # 这里也写自己的代码实现 def load_data(filepath): @@ -65,7 +85,14 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ - + data = np.loadtxt(filepath, delimiter=',') + X = data[:, :-1] + y = data[:, -1] + + # 将标签转换为0和1(假设原始标签为1和2) + y = np.where(y == 1, 0, 1) + + return X, y if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改