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

This commit is contained in:
wzy
2024-10-31 15:38:27 +08:00
parent 590a63b558
commit 61b3b782c7
+21 -8
View File
@@ -31,6 +31,7 @@ def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.001, iterations=500, batch_size=16, initial_weights=None):
X = np.insert(X, 0, 1, axis=1) # 添加偏置项
if initial_weights is None:
weights = np.zeros(X.shape[1])
else:
@@ -68,7 +69,7 @@ def train_logreg(X, y, learning_rate=0.001, iterations=500, batch_size=16, initi
def predict_logreg(inX, weights):
inX = np.insert(inX, 0, 1) # 添加偏置项
z = np.dot(inX, weights)
h = sigmoid(z)
return 1 if h >= 0.5 else 0
@@ -116,15 +117,26 @@ def load_data(filepath):
data = [line.strip().split() for line in lines]
data = [list(map(lambda x: float(x) if x != '?' else np.nan, row)) for row in data]
# 处理缺失值,这里简单用平均值填充
for i in range(len(data[0])):
mean_val = np.nanmean([row[i] for row in data if not np.isnan(row[i])])
for row in data:
# 移除类别标签缺失的样本
data = [row for row in data if row[-1] != np.nan]
# 使用“0”填充缺失值
for row in data:
for i in range(len(row)):
if np.isnan(row[i]):
row[i] = mean_val
row[i] = 0.0
# 合并特征23的值2和3为0
for row in data:
if row[22] == 2 or row == 3: # 假设特征23是第23个元素
row[22] = 0
# 移除不需要的特征
# 假设特征从0开始编号,那么我们需要移除特征3和特征24~28
data = [row[:2] + row[3:23] + row[28:] for row in data]
# 分离特征和标签
X = [row[:-1] for row in data]
X = [row[:-1] for row in data] # 特征现在是从0到21,然后是23到27
y = [row[-1] for row in data]
return np.array(X), np.array(y)
@@ -140,6 +152,7 @@ def load_data(filepath):
"""
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
@@ -151,4 +164,4 @@ if __name__ == "__main__":
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")