From 9000e29c5e5d44659356e5de9a9523201e239ef2 Mon Sep 17 00:00:00 2001 From: Frae19 <515745323@qq.com> Date: Tue, 5 Nov 2024 15:11:17 +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 | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/function.py b/function.py index 73f3559..3ea581e 100644 --- a/function.py +++ b/function.py @@ -28,16 +28,9 @@ name = "Tanjunfeng" # 这里写自己的代码实现 +import numpy as np + def sigmoid(z): - """ - Compute the sigmoid of z. - - Args: - - z (numpy array): Input array. - - Returns: - - numpy array: Sigmoid of input. - """ return 1 / (1 + np.exp(-z)) def train_logreg(X, y, learning_rate=0.01, iterations=1000): @@ -51,7 +44,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000): - iterations (int): 迭代次数,默认为 1000。 Returns: - - Tuple[numpy array, float]: 训练得到的权重和偏置。 + - numpy array: 训练得到的权重。 """ m, n = X.shape weights = np.zeros(n) @@ -65,23 +58,23 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000): weights -= learning_rate * dw bias -= learning_rate * db - return weights, bias + return weights -def predict_logreg(inX, weights, bias): +def predict_logreg(inX, weights): """ 对率回归预测函数。 Args: - inX (numpy array): 输入待分类的样本。 - weights (numpy array): 训练得到的权重。 - - bias (float): 训练得到的偏置。 Returns: - int: 预测的分类标签。 """ - z = np.dot(inX, weights) + bias + z = np.dot(inX, weights) h = sigmoid(z) - return 1 if h >= 0.5 else 0 + # 调整分类阈值 + return 1 if h > 0.6 else 0 def load_data(filepath): """ @@ -119,14 +112,14 @@ if __name__ == "__main__": X_test, y_test = load_data("./data/horse-colic.test") # 训练对率回归模型 - weights, bias = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000) + weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000) # 测试单个数据 correct_count = 0 total_count = len(y_test) for i in range(total_count): - y_pred = predict_logreg(X_test[i], weights, bias) + y_pred = predict_logreg(X_test[i], weights) if y_pred == y_test[i]: correct_count += 1 accuracy = correct_count / total_count - print(f"测试准确率: {accuracy:.2f}") + print(f"准确率: {accuracy}") \ No newline at end of file