From 7c4caae057debe4da3b840b92a9f4c5471f70968 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=9D=A8=E6=B4=8B?= <2445091977@qq.com> Date: Sat, 2 Nov 2024 20:53:45 +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 | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/function.py b/function.py index 74b40ae..5a7aa8b 100644 --- a/function.py +++ b/function.py @@ -64,22 +64,15 @@ def load_data(filepath): - X (np.array): 特征数据。 - y (np.array): 标签数据。 """ - # 使用np.genfromtxt加载数据,并且忽略文件中不能转换为float的行 - with open(filepath, 'r') as file: - lines = file.readlines() - - data = [] - for line in lines: - split_line = line.strip().split(',') - # 将非数值数据转换为0 - split_line = [float(x) if x != '?' else 0 for x in split_line] - data.append(split_line) - - data = np.array(data) - if data.ndim == 1: - data = data.reshape(1, -1) + # 使用空格分隔符加载数据 + data = np.loadtxt(filepath, delimiter=' ') + # 将问号 '?' 替换为 NaN + data = np.where(data == '?', np.nan, data) + # 将 NaN 替换为 0 + data = np.where(np.isnan(data), 0, data) + # 分割特征和标签 X = data[:, :-1] - y = data[:, -1].reshape(-1, 1) # 确保y是二维的 + y = data[:, -1] return X, y