From a03737a8c170bd6962c825d935b0a886912a0c46 Mon Sep 17 00:00:00 2001 From: 43606070 <43606070@qq.com> Date: Tue, 29 Oct 2024 19:10:45 +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 | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/function.py b/function.py index 8fb3b7c..1433793 100644 --- a/function.py +++ b/function.py @@ -40,43 +40,43 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000): - iterations (int): 迭代次数, 默认值为1000。 Returns: - - numpy array: 训练得到的权重。 - - float: 训练得到的偏置。 + - numpy array: 训练得到的权重和偏置(合并为一个数组)。 """ n_samples, n_features = X.shape - weights = np.zeros(n_features) - bias = 0 + weights = np.zeros(n_features + 1) # 增加一位用于偏置 + + # 增加一列1表示偏置 + X = np.c_[X, np.ones((n_samples, 1))] # 梯度下降法 for i in range(iterations): - linear_model = np.dot(X, weights) + bias + linear_model = np.dot(X, weights) y_pred = sigmoid(linear_model) # 计算梯度 dw = (1 / n_samples) * np.dot(X.T, (y_pred - y)) - db = (1 / n_samples) * np.sum(y_pred - y) - # 更新权重和偏置 + # 更新权重 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): 训练得到的偏置。 + - weights (numpy array): 训练得到的权重和偏置。 Returns: - int: 预测的分类标签 (0 或 1)。 """ - linear_model = np.dot(inX, weights) + bias + # 增加偏置项 + inX = np.append(inX, 1) + linear_model = np.dot(inX, weights) y_pred = sigmoid(linear_model) return 1 if y_pred >= 0.5 else 0 @@ -115,10 +115,11 @@ if __name__ == "__main__": X_test, y_test = load_data("./data/horse-colic.test") # 训练对率回归模型 - weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) + weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000) # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights, bias) + y_pred = predict_logreg(X_test[11], weights) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") +