From f2b293e4ad216ab6d1af7bacff349c7ffe9d33e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=87=9A=E7=87=8A?= Date: Sun, 3 Nov 2024 17:12:57 +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 85939e5..83481da 100644 --- a/function.py +++ b/function.py @@ -6,8 +6,10 @@ from sklearn.impute import SimpleImputer id = "202210423107" name = "刘燚燊" +import pandas as pd + def load_data(filepath): - """ + """ 从文件中加载数据,处理缺失值和标签。 Args: @@ -17,20 +19,15 @@ def load_data(filepath): - np.array: 特征数据。 - np.array: 标签数据。 """ - with open(filepath, 'r') as f: - data = [line.strip().split() for line in f.readlines()] + # 使用pandas读取数据 + data = pd.read_csv(filepath, header=None, na_values='?') - # 将数据中缺失值用0填充 - data = [[0 if value == '?' else float(value) for value in line] for line in data] - data = np.array(data) + # 填充缺失值 + data.fillna(data.mean(), inplace=True) # 分离特征和标签 - X = data[:, :-1] - y = data[:, -1] - - # 使用均值填充缺失值 - imputer = SimpleImputer(strategy='mean') - X = imputer.fit_transform(X) + X = data.iloc[:, :-1].values + y = data.iloc[:, -1].values # 过滤掉没有类别标签的数据 valid_indices = np.isfinite(y) @@ -40,6 +37,7 @@ def load_data(filepath): return X, y + def train_logreg(X, y, learning_rate=0.01, iterations=1000, reg_param=0.01): # 初始化权重 weights = np.zeros(X.shape[1])