generated from LufsX/Experiment-LogReg
This commit is contained in:
+21
-12
@@ -63,27 +63,36 @@ def predict_logreg(inX, weights):
|
|||||||
return 1 if h > 0.5 else 0
|
return 1 if h > 0.5 else 0
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
|
"""加载数据并处理缺失值。"""
|
||||||
data, labels = [], []
|
data, labels = [], []
|
||||||
|
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f:
|
||||||
for line in f.readlines():
|
for line in f:
|
||||||
line = line.strip().split()
|
values = line.strip().replace('?', '0').split()
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
try:
|
||||||
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
|
values = [float(v) for v in values]
|
||||||
data.append(line_data)
|
|
||||||
labels.append(int(line[-1]))
|
# 合并特征23的取值
|
||||||
|
if values[22] in [2, 3]: # 特征23索引(22)
|
||||||
|
labels.append(0) # 死亡
|
||||||
|
elif values[22] == 1:
|
||||||
|
labels.append(1) # 生存
|
||||||
|
else:
|
||||||
|
continue # 无效标签,丢弃
|
||||||
|
|
||||||
|
# 用0填充缺失值并提取特征
|
||||||
|
data.append([0 if v == 0 else v for v in values[:2] + values[3:23]]) # 保留特征1, 2 和特征4-23
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
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()
|
scaler = StandardScaler()
|
||||||
data = scaler.fit_transform(data)
|
data = scaler.fit_transform(data)
|
||||||
|
|
||||||
return data, target_variable
|
return data, labels
|
||||||
|
|
||||||
def accuracy(X, y, weights):
|
def accuracy(X, y, weights):
|
||||||
predictions = [predict_logreg(x, weights) for x in X]
|
predictions = [predict_logreg(x, weights) for x in X]
|
||||||
|
|||||||
Reference in New Issue
Block a user