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

This commit is contained in:
2024-11-03 16:43:20 +08:00
parent a1b1d7bfe6
commit 8c704c9124
+15 -6
View File
@@ -5,9 +5,7 @@ name = "魏明帅"
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
m, n = X.shape
# 添加偏置项
X = np.c_[np.ones((m, 1)), X]
weights = np.zeros(n + 1)
weights = np.zeros(n)
for _ in range(iterations):
for i in range(m):
@@ -31,20 +29,31 @@ def load_data(filepath):
with open(filepath, 'r') as f:
for line in f:
values = line.strip().split()
# 跳过包含 '?' 的行
if '?' in values:
continue
# 将标签和特征转换为浮点数
y.append(float(values[-1]))
X.append([float(x) for x in values[:-1]])
# 特征缩放
X_array = np.array(X)
X_scaled = (X_array - np.mean(X_array, axis=0)) / np.std(X_array, axis=0)
return X_scaled, np.array(y).reshape(-1, 1)
y_array = np.array(y).reshape(-1, 1)
# 特征缩放,处理标准差为零的特征
stds = np.std(X_array, axis=0)
means = np.mean(X_array, axis=0)
X_scaled = (X_array - means) / np.where(stds == 0, 1, stds)
return X_scaled, y_array
if __name__ == "__main__":
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 添加偏置项
X_train = np.c_[np.ones((X_train.shape[0], 1)), X_train]
X_test = np.c_[np.ones((X_test.shape[0], 1)), X_test]
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")