generated from LufsX/Experiment-LogReg
This commit is contained in:
+23
-13
@@ -67,27 +67,37 @@ def predict_logreg(X, weights):
|
||||
return np.where(prediction_prob >= 0.5, 1, 0)
|
||||
|
||||
def load_data(filepath):
|
||||
data, labels = [], []
|
||||
"""加载数据并处理缺失值。"""
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f.readlines():
|
||||
line = line.strip().split()
|
||||
if len(line) >= 1 and line[-1].isdigit():
|
||||
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
|
||||
data.append(line_data)
|
||||
labels.append(int(line[-1]))
|
||||
for line in f:
|
||||
values = line.strip().replace('?', '0').split()
|
||||
try:
|
||||
values = [float(v) for v in values]
|
||||
|
||||
# 合并特征23的取值
|
||||
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
|
||||
labels.append(0) # 死亡
|
||||
elif values[22] == 1:
|
||||
labels.append(1) # 生存
|
||||
else:
|
||||
continue # 无效标签,丢弃
|
||||
|
||||
# 用0填充缺失值
|
||||
values = [0 if v == 0 else v for v in values] # 直接用0填充
|
||||
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
data = np.array(data)
|
||||
labels = np.array(labels)
|
||||
|
||||
target_variable = labels
|
||||
target_variable[(target_variable == 2) | (target_variable == 3)] = 0
|
||||
|
||||
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
|
||||
|
||||
scaler = StandardScaler()
|
||||
data = scaler.fit_transform(data)
|
||||
|
||||
return data, target_variable
|
||||
return data, labels
|
||||
|
||||
def accuracy(X, y, weights):
|
||||
"""计算模型准确率。"""
|
||||
|
||||
Reference in New Issue
Block a user