generated from LufsX/Challenge-SVM
This commit is contained in:
+19
-24
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user