generated from LufsX/Experiment-LogReg
This commit is contained in:
+19
-5
@@ -27,7 +27,7 @@ name = "章程鸿"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
import numpy as np
|
||||
|
||||
from sklearn.model_selection import KFold
|
||||
def sigmoid(z):
|
||||
return 1 / (1 + np.exp(-z))
|
||||
|
||||
@@ -92,6 +92,21 @@ def load_data(filepath):
|
||||
X = data[:, :-1]
|
||||
y = data[:, -1]
|
||||
return X, y
|
||||
def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000):
|
||||
kf = KFold(n_splits=k)
|
||||
accuracies = []
|
||||
|
||||
for train_index, test_index in kf.split(X):
|
||||
X_train, X_test = X[train_index], X[test_index]
|
||||
y_train, y_test = y[train_index], y[test_index]
|
||||
|
||||
weights = train_logreg(X_train, y_train, learning_rate, iterations)
|
||||
predictions = [predict_logreg(x, weights) for x in X_test]
|
||||
|
||||
accuracy = np.mean(predictions == y_test)
|
||||
accuracies.append(accuracy)
|
||||
|
||||
return np.mean(accuracies)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
@@ -102,8 +117,7 @@ if __name__ == "__main__":
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 训练对率回归模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=10000)
|
||||
k = 5 # 设置折数
|
||||
accuracy = cross_validate(X, y, k=k, learning_rate=0.01, iterations=5000)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
print(f"{k}-折交叉验证的平均准确率: {accuracy:.2f}")
|
||||
|
||||
Reference in New Issue
Block a user