generated from LufsX/Experiment-LogReg
This commit is contained in:
+20
-27
@@ -5,35 +5,28 @@ id = "202210423223"
|
||||
name = "李顺潮"
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,处理缺失值和数据类型。
|
||||
"""从文件中加载数据,处理不规则的字段数量和缺失值"""
|
||||
data = []
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
fields = line.strip().split()
|
||||
# 处理不规则的字段数量,这里选择忽略多余的字段
|
||||
if len(fields) > 28:
|
||||
fields = fields[:28]
|
||||
# 替换 '?' 为 NaN
|
||||
fields = [np.nan if x == '?' else x for x in fields]
|
||||
data.append(fields)
|
||||
|
||||
Args:
|
||||
filepath (str): 数据文件路径。
|
||||
# 使用 pandas 创建 DataFrame
|
||||
df = pd.DataFrame(data)
|
||||
# 删除包含 NaN 的行
|
||||
df.dropna(inplace=True)
|
||||
# 转换为数值类型
|
||||
df = df.astype(float)
|
||||
|
||||
Returns:
|
||||
tuple: 特征数据 (np.array) 和标签数据 (np.array)。 返回None如果加载失败。
|
||||
"""
|
||||
try:
|
||||
# 使用正则表达式作为分隔符,更灵活地处理多个空格
|
||||
data = pd.read_csv(filepath, header=None, delim_whitespace=True)
|
||||
|
||||
# 替换问号为 NaN
|
||||
data.replace('?', np.nan, inplace=True)
|
||||
|
||||
# 填充数值型缺失值,这里使用中位数填充
|
||||
numeric_cols = data.select_dtypes(include=np.number).columns
|
||||
for col in numeric_cols:
|
||||
data[col].fillna(data[col].median(), inplace=True)
|
||||
|
||||
# 删除包含非数值型缺失值的列 (如果存在)
|
||||
data.dropna(inplace=True)
|
||||
|
||||
|
||||
# 假设最后一列是标签,其余是特征
|
||||
X = data.iloc[:, :-1].values.astype(float)
|
||||
y = data.iloc[:, -1].values.astype(float)
|
||||
return X, y
|
||||
X = df.iloc[:, :-1].values
|
||||
y = df.iloc[:, -1].values
|
||||
return X, y
|
||||
except pd.errors.ParserError as e:
|
||||
print(f"数据加载错误: {e}")
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user