generated from LufsX/Experiment-LogReg
This commit is contained in:
+14
-20
@@ -27,7 +27,7 @@ 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))
|
||||||
|
|
||||||
@@ -92,21 +92,20 @@ def load_data(filepath):
|
|||||||
X = data[:, :-1]
|
X = data[:, :-1]
|
||||||
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 standardize(X):
|
||||||
kf = KFold(n_splits=k)
|
"""
|
||||||
accuracies = []
|
标准化特征数据,使其均值为0,标准差为1。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- X (numpy array): 特征数据。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- numpy array: 标准化后的特征数据。
|
||||||
|
"""
|
||||||
|
mean = np.mean(X, axis=0)
|
||||||
|
std = np.std(X, axis=0)
|
||||||
|
return (X - mean) / std
|
||||||
|
|
||||||
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__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 加载训练集
|
||||||
@@ -115,11 +114,6 @@ 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 = 5 # 设置折数
|
|
||||||
cv_accuracy = cross_validate(X_train, y_train, k=k, learning_rate=0.01, iterations=1000)
|
|
||||||
print(f"{k}-折交叉验证的平均准确率: {cv_accuracy:.2f}")
|
|
||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
|
|||||||
Reference in New Issue
Block a user