generated from LufsX/Experiment-LogReg
This commit is contained in:
+12
-7
@@ -27,7 +27,6 @@ name = "章程鸿"
|
|||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.model_selection import KFold
|
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1 / (1 + np.exp(-z))
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
@@ -93,12 +92,19 @@ def load_data(filepath):
|
|||||||
y = data[:, -1]
|
y = data[:, -1]
|
||||||
return X, y
|
return X, y
|
||||||
def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000):
|
def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000):
|
||||||
kf = KFold(n_splits=k)
|
m = len(y)
|
||||||
|
fold_size = m // k
|
||||||
|
indices = np.arange(m)
|
||||||
|
np.random.shuffle(indices) # 打乱索引
|
||||||
|
|
||||||
accuracies = []
|
accuracies = []
|
||||||
|
|
||||||
for train_index, test_index in kf.split(X):
|
for i in range(k):
|
||||||
X_train, X_test = X[train_index], X[test_index]
|
test_indices = indices[i * fold_size: (i + 1) * fold_size]
|
||||||
y_train, y_test = y[train_index], y[test_index]
|
train_indices = np.concatenate((indices[:i * fold_size], indices[(i + 1) * fold_size:]))
|
||||||
|
|
||||||
|
X_train, X_test = X[train_indices], X[test_indices]
|
||||||
|
y_train, y_test = y[train_indices], y[test_indices]
|
||||||
|
|
||||||
weights = train_logreg(X_train, y_train, learning_rate, iterations)
|
weights = train_logreg(X_train, y_train, learning_rate, iterations)
|
||||||
predictions = [predict_logreg(x, weights) for x in X_test]
|
predictions = [predict_logreg(x, weights) for x in X_test]
|
||||||
@@ -107,7 +113,6 @@ def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000):
|
|||||||
accuracies.append(accuracy)
|
accuracies.append(accuracy)
|
||||||
|
|
||||||
return np.mean(accuracies)
|
return np.mean(accuracies)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
@@ -115,7 +120,7 @@ if __name__ == "__main__":
|
|||||||
# 加载测试集
|
# 加载测试集
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 进行 K 折交叉验证
|
# 进行 K 折交叉验证
|
||||||
k = 5 # 设置折数
|
k = 5 # 设置折数
|
||||||
cv_accuracy = cross_validate(X_train, y_train, k=k, learning_rate=0.01, iterations=1000)
|
cv_accuracy = cross_validate(X_train, y_train, k=k, learning_rate=0.01, iterations=1000)
|
||||||
print(f"{k}-折交叉验证的平均准确率: {cv_accuracy:.2f}")
|
print(f"{k}-折交叉验证的平均准确率: {cv_accuracy:.2f}")
|
||||||
|
|||||||
Reference in New Issue
Block a user