更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 13s

This commit is contained in:
2024-11-07 16:52:41 +08:00
parent 8b9ff6e020
commit 3677b2ab86
+27 -6
View File
@@ -56,9 +56,11 @@ def predict_logreg(inX, weights):
# 将概率转为标签
return 1 if prob >= 0.5 else 0
import numpy as np
def load_data(filepath):
"""
从文件中加载数据。
从文件中加载数据,处理缺失数据,并将 '?' 替换为列的均值。
Args:
- filepath (str): 数据文件路径。
@@ -69,19 +71,38 @@ def load_data(filepath):
"""
data = []
labels = []
# 读取数据
with open(filepath, 'r') as file:
for line in file:
line = line.strip().split()
if not line:
continue
# 将特征转换为浮点型
features = list(map(float, line[:-1]))
# 将标签提取出来
label = int(line[-1])
# 将特征转换为浮动数组
features = line[:-1] # 去除标签部分
# 用特征中的均值替换 '?',并转换为 float
features = [float(f) if f != '?' else None for f in features]
# 将数据和标签分别加入到列表
data.append(features)
labels.append(label)
return np.array(data), np.array(labels)
# 将列表转换为numpy数组
data = np.array(data)
labels = np.array(labels)
# 计算每列的均值,并用均值替换 None
col_means = np.nanmean(data, axis=0) # 计算每列的均值,忽略 NaN
# 将 None 替换为对应的列均值
for i in range(data.shape[1]):
data[:, i] = np.where(np.isnan(data[:, i]), col_means[i], data[:, i])
return data, labels
if __name__ == "__main__":
# 加载训练集