From 7d4f661ff059e5fb28a4f88d001bb7a7fc01fe6f Mon Sep 17 00:00:00 2001 From: dong <2938690875@qq.com> Date: Thu, 31 Oct 2024 16:36:14 +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 | 33 ++++++++------------------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/function.py b/function.py index 48dac4a..fb0fb6d 100644 --- a/function.py +++ b/function.py @@ -42,20 +42,16 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000): """ m, n = X.shape weights = np.zeros(n) - + for _ in range(iterations): - # 计算预测值 z = np.dot(X, weights) predictions = 1 / (1 + np.exp(-z)) - - # 计算损失的梯度 gradient = np.dot(X.T, (predictions - y)) / m - - # 更新权重 weights -= learning_rate * gradient - + return weights + def predict_logreg(inX, weights): """ 对率回归预测函数。 @@ -67,40 +63,27 @@ def predict_logreg(inX, weights): Returns: - int: 预测的分类标签。 """ - z = np.dot(inX, weights) + z = np.dot(inX, weights) prediction_prob = 1 / (1 + np.exp(-z)) - return 1 if prediction_prob >= 0.5 else 0 # 这里也写自己的代码实现 def load_data(filepath): data = [] labels = [] - + with open(filepath, 'r') as f: for line in f: values = line.strip().replace('?', '0').split() try: values = [float(v) for v in values] - data.append(values[:-1]) - labels.append(values[-1]) + data.append(values[:-1]) # 特征 + labels.append(values[-1]) # 标签 except ValueError: continue - + return np.array(data), np.array(labels) -def preprocess_data(filepath): - # 加载数据 - X, y = load_data(filepath) - - # 特征缩放 - scaler = StandardScaler() - X_scaled = scaler.fit_transform(X) - - # 拆分数据集 - X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42) - - return X_train, X_test, y_train, y_test if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改