From 0b9bd58554129fad5624c011a12be94dc1cebf59 Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 31 Oct 2024 16:19:52 +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 | 40 ++++++++++------------------------------ 1 file changed, 10 insertions(+), 30 deletions(-) diff --git a/function.py b/function.py index 6e0e038..9dc71f9 100644 --- a/function.py +++ b/function.py @@ -19,49 +19,29 @@ id = "202210423213" name = "熊浩燃" # 对率回归训练函数 -def train_logreg(X, y, learning_rate=0.01, iterations=1000): - """ - 对率回归训练函数。 - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - learning_rate (float): 学习率,默认为0.01。 - - iterations (int): 迭代次数,默认为1000。 - Returns: - - numpy array: 训练得到的权重。 - """ - # 初始化权重 +def train_logreg(X, y, learning_rate=0.001, iterations=1000): + # 标准化特征数据 + X = (X - np.mean(X, axis=0)) / np.std(X, axis=0) + weights = np.zeros(X.shape[1]) - + for i in range(iterations): - # 预测值:通过对率回归模型得到 z = np.dot(X, weights) predictions = 1 / (1 + np.exp(-z)) - # 计算梯度并更新权重 + # 防止 log(0) 引发 NaN + predictions = np.clip(predictions, 1e-10, 1 - 1e-10) + gradient = np.dot(X.T, (predictions - y)) / y.size weights -= learning_rate * gradient - - # 可选:输出损失,帮助调试 + + # 输出损失帮助调试 if i % 100 == 0: loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) print(f"迭代 {i},损失: {loss}") return weights -# 对率回归预测函数 -def predict_logreg(inX, weights): - """ - 对率回归预测函数。 - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - Returns: - - int: 预测的分类标签。 - """ - probability = 1 / (1 + np.exp(-np.dot(inX, weights))) - return 1 if probability >= 0.5 else 0 - # 数据加载函数 def load_data(filepath): """