From 03c98cf1b4a64f0745fa4b4dcf7c62a9e90c8d7f Mon Sep 17 00:00:00 2001 From: mogu-king <1547976000@qq.com> Date: Sun, 3 Nov 2024 04:10:05 +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 | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/function.py b/function.py index 6b87d42..7dc9248 100644 --- a/function.py +++ b/function.py @@ -29,12 +29,25 @@ def load_data(filepath): - X (numpy array): 特征数据 - y (numpy array): 标签数据 """ - data = np.loadtxt(filepath, delimiter=",") + # 读取数据,指定缺失值符号为 '?' + data = np.genfromtxt(filepath, delimiter=",", dtype=str) + + # 将 '?' 替换为 np.nan 并转换为浮点数 + data[data == '?'] = np.nan + data = data.astype(float) + + # 对每一列的缺失值使用列的均值填充 + col_means = np.nanmean(data, axis=0) + inds = np.where(np.isnan(data)) + data[inds] = np.take(col_means, inds[1]) + + # 分离特征和标签 X = data[:, :-1] y = data[:, -1] return X, y + # 这里实现对率回归训练函数 def train_logreg(X, y, learning_rate=0.01, num_iterations=1000, regularization_strength=0.01): """