generated from LufsX/Experiment-LogReg
This commit is contained in:
+21
-3
@@ -1,7 +1,7 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.model_selection import train_test_split, KFold
|
||||
|
||||
id = "202210423130"
|
||||
name = "董秋"
|
||||
@@ -91,9 +91,27 @@ if __name__ == "__main__":
|
||||
# 使用 train_test_split 打乱并随机抽取数据
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
||||
|
||||
# K折交叉验证
|
||||
k = 5
|
||||
kf = KFold(n_splits=k, shuffle=True, random_state=42)
|
||||
accuracies = []
|
||||
|
||||
for train_index, val_index in kf.split(X_train):
|
||||
X_train_kf, X_val_kf = X_train[train_index], X_train[val_index]
|
||||
y_train_kf, y_val_kf = y_train[train_index], y_train[val_index]
|
||||
|
||||
# 训练逻辑回归模型,设置 batch size
|
||||
batch_size = 64
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.1, iterations=1000, lambda_reg=0.01, batch_size=batch_size)
|
||||
batch_size = 32
|
||||
weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.1, iterations=1000, lambda_reg=0.01, batch_size=batch_size)
|
||||
|
||||
# 验证模型
|
||||
val_predictions = [predict_logreg(X_val_kf[i], weights) for i in range(len(X_val_kf))]
|
||||
accuracy = np.mean(val_predictions == y_val_kf)
|
||||
accuracies.append(accuracy)
|
||||
|
||||
# 输出交叉验证的准确率和平均准确率
|
||||
print(f"K折交叉验证得分: {accuracies}")
|
||||
print(f"平均准确率: {np.mean(accuracies)}")
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
|
||||
Reference in New Issue
Block a user