From a6391a8f9d9160480d577df17e2e6cda063baa23 Mon Sep 17 00:00:00 2001 From: dong <2938690875@qq.com> Date: Sun, 3 Nov 2024 14:33:16 +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 | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/function.py b/function.py index 9aa30b2..1eaa52d 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,6 @@ import numpy as np import os -from sklearn.preprocessing import StandardScaler # 导入标准化库 +from sklearn.preprocessing import StandardScaler # 学号和姓名 id = "202210423130" @@ -46,7 +46,7 @@ def predict_logreg(inX, weights): h = sigmoid(z) return 1 if h >= 0.5 else 0 -def load_data(filepath): +def load_data(filepath, remove_indices=None): """从文件中加载数据。""" if not os.path.exists(filepath): raise FileNotFoundError(f"文件 {filepath} 不存在!") @@ -66,14 +66,9 @@ def load_data(filepath): data = np.array(data) labels = np.array(labels) - num_features = data.shape[1] - indices_to_remove = [2] # 去掉特征3(索引2) - - # 剔除特征 24-28(索引 23-27) - if num_features > 23: - indices_to_remove.extend(range(23, min(28, num_features))) - - data = np.delete(data, indices_to_remove, axis=1) + if remove_indices is not None: + data = np.delete(data, remove_indices, axis=1) + target_variable = np.where((labels == 2) | (labels == 3), 0, 1) print(f"数据加载成功,数据形状: {data.shape}, 标签形状: {target_variable.shape}") @@ -104,9 +99,12 @@ def k_fold_cross_validation(X, y, k=5, learning_rate=0.001, iterations=10000, ba return np.mean(accuracies) if __name__ == "__main__": + # 定义要剔除的特征索引 + indices_to_remove = [2] + list(range(23, 28)) # 去掉特征3和24到28的特征 + # 加载训练集 try: - X_train, y_train = load_data("./data/horse-colic.data") + X_train, y_train = load_data("./data/horse-colic.data", remove_indices=indices_to_remove) except FileNotFoundError as e: print(e) exit() @@ -121,7 +119,7 @@ if __name__ == "__main__": # 加载测试集 try: - X_test, y_test = load_data("./data/horse-colic.test") + X_test, y_test = load_data("./data/horse-colic.test", remove_indices=indices_to_remove) except FileNotFoundError as e: print(e) exit()