From 3fd4017913cfa9e91cbff683abf2fdeeae21a82e Mon Sep 17 00:00:00 2001 From: heart20003 <1789588961@qq.com> Date: Sun, 3 Nov 2024 21:19:53 +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 | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/function.py b/function.py index 45f6edf..d0d7130 100644 --- a/function.py +++ b/function.py @@ -1,5 +1,8 @@ # function.py import numpy as np +from sklearn.linear_model import LogisticRegression +from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import train_test_split """ 实验说明: @@ -25,6 +28,9 @@ id = "202210423204" name = "陈垣豪" + + + def load_data(filepath): """加载数据并处理缺失值.""" data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan) @@ -35,41 +41,32 @@ def load_data(filepath): y = data[:, -1] return X, y -def train_logreg(X, y, learning_rate=0.01, iterations=1000): - """训练逻辑回归模型,使用随机梯度下降.""" - n_samples, n_features = X.shape - weights = np.zeros(n_features + 1) # 增加一位用于偏置 - X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项 +def train_logreg(X, y): + """训练逻辑回归模型,使用scikit-learn.""" + scaler = StandardScaler() + X_scaled = scaler.fit_transform(X) # 标准化特征 + model = LogisticRegression() + model.fit(X_scaled, y) + return model, scaler - for _ in range(iterations): - random_index = np.random.randint(n_samples) - X_i = X[random_index] - y_i = y[random_index] - - linear_model = np.dot(X_i, weights) - dw = (linear_model - y_i) * X_i - weights -= learning_rate * dw - - return weights - -def predict_logreg(inX, weights): - """使用线性模型预测结果.""" - inX = np.append(inX, 1) # 增加偏置项 - linear_model = np.dot(inX, weights) - return 1.0 if linear_model >= 0 else 2.0 +def predict_logreg(model, scaler, inX): + """使用训练好的模型预测结果.""" + inX_scaled = scaler.transform(inX.reshape(1, -1)) # 标准化输入数据 + return model.predict(inX_scaled)[0] if __name__ == "__main__": # 示例:加载数据并训练模型 X_train, y_train = load_data("./data/horse-colic.data") - weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000) + model, scaler = train_logreg(X_train, y_train) # 测试单个数据 X_test, y_test = load_data("./data/horse-colic.test") - y_pred = predict_logreg(X_test[11], weights) + y_pred = predict_logreg(model, scaler, X_test[11]) print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + # 训练逻辑回归模型 weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)