From 85c3ac6b710f61d2bfa5c9e06eafb66c10830fc8 Mon Sep 17 00:00:00 2001 From: Yijuehen <1906265724@qq.com> Date: Wed, 13 Nov 2024 18:31: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 | 43 +++++++++++++++++++------------------------ 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/function.py b/function.py index b279245..43c724b 100644 --- a/function.py +++ b/function.py @@ -5,35 +5,30 @@ id = "202210423230" name = "尹家立" def load_data(filepath): - data, labels = [], [] - with open(filepath, 'r') as f: - for line in f: - line = line.strip().split() - if len(line) >= 1 and line[-1].isdigit(): - # 将特征值中的缺失值(“?”)替换为0,并将其余项转换为浮点数 - line_data = [0 if x == '?' else float(x) for x in line[:-1]] - data.append(line_data) - # 保留标签原始的三分类标签 - labels.append(int(line[-1])) + """ + 从文件中加载数据,处理缺失值,并确保标签维持原始三分类标签。 - data = np.array(data) - labels = np.array(labels) + Args: + - filepath (str): 数据文件路径。 - # 检查特征数量 - num_features = data.shape[1] + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + # 读取数据,将 '?' 替换为 NaN + data = np.genfromtxt(filepath, delimiter=' ', dtype=float, missing_values='?', filling_values=np.nan) - # 特征选择:去掉特征3(索引2)和特征24~28(索引23~26),确保索引有效 - indices_to_delete = [2] # 特征3 - if num_features > 24: # 确保特征数量足够 - indices_to_delete += list(range(24, 27)) # 特征24到27(索引23到26) + # 用列均值填补缺失值 + nan_indices = np.isnan(data) + col_means = np.nanmean(data, axis=0) + data[nan_indices] = np.take(col_means, np.where(nan_indices)[1]) - # 删除指定特征列 - data = np.delete(data, indices_to_delete, axis=1) + # 分离特征和标签 + X = data[:, :-1] + y = data[:, -1] - # 保留三分类标签 - target_variable = labels # 不再合并任何标签,保持三分类 - - return data, target_variable + # 确保标签值保持三分类标签(例如,假设标签值分别为 1:存活,2:死亡,3:安乐死) + return X, y