From b0c53f2d32d5e50bd378771ff40f8bba8e9c12c4 Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 31 Oct 2024 15:33:49 +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 | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index b5b9523..b6d9a7c 100644 --- a/function.py +++ b/function.py @@ -93,7 +93,7 @@ def predict_logreg(inX, weights, degree=2): def load_data(filepath): """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + 从文件中加载数据,并使用均值填充缺失值。 Args: - filepath (str): 数据文件路径。 @@ -107,10 +107,21 @@ def load_data(filepath): with open(filepath, 'r') as file: for line in file: line_data = line.strip().split() - if '?' not in line_data: # 忽略缺失值的行 - data.append([float(x) for x in line_data[:-1]]) - labels.append(int(float(line_data[-1]))) - return np.array(data), np.array(labels) + # 将缺失值替换为 np.nan + line_data = [float(x) if x != '?' else np.nan for x in line_data] + data.append(line_data[:-1]) + labels.append(int(line_data[-1])) + + data = np.array(data) + labels = np.array(labels) + + # 使用列均值填充缺失值 + col_mean = np.nanmean(data, axis=0) + # 找到所有缺失值,并用列均值替换 + indices = np.where(np.isnan(data)) + data[indices] = np.take(col_mean, indices[1]) + + return data, labels if __name__ == "__main__": # 测试数据加载和模型训练预测