[英]Implement K-fold cross validation in MLPClassification Python
我正在學習如何使用 scikit-learn 開發反向傳播神經網絡。 我仍然對如何在我的神經網絡中實現 k 折交叉驗證感到困惑。 我希望你們能幫助我。 我的代碼如下:
import numpy as np
from sklearn.model_selection import KFold
from sklearn.neural_network import MLPClassifier
f = open("seeds_dataset.txt")
data = np.loadtxt(f)
X=data[:,0:]
y=data[:,-1]
kf = KFold(n_splits=10)
X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
clf.fit(X, y)
MLPClassifier(activation='relu', alpha=1e-05, batch_size='auto',
beta_1=0.9, beta_2=0.999, early_stopping=False,
epsilon=1e-08, hidden_layer_sizes=(5, 2), learning_rate='constant',
learning_rate_init=0.001, max_iter=200, momentum=0.9,
nesterovs_momentum=True, power_t=0.5, random_state=1, shuffle=True,
solver='lbfgs', tol=0.0001, validation_fraction=0.1, verbose=False,
warm_start=False)
不要將您的數據分成訓練和測試。 這由 KFold 交叉驗證自動處理。
from sklearn.model_selection import KFold
kf = KFold(n_splits=10)
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
for train_indices, test_indices in kf.split(X):
clf.fit(X[train_indices], y[train_indices])
print(clf.score(X[test_indices], y[test_indices]))
KFold 驗證將您的數據集划分為 n 個相等的公平部分。 然后將每個部分分成測試和訓練。 有了這個,您就可以相當准確地衡量模型的准確性,因為它是在小部分公平分布的數據上進行測試的。
感謝@COLDSPEED 的回答。
如果您想進行 n 折交叉驗證的預測,則 cross_val_predict() 是您要走的路。
# Scamble and subset data frame into train + validation(80%) and test(10%)
df = df.sample(frac=1).reset_index(drop=True)
train_index = 0.8
df_train = df[ : len(df) * train_index]
# convert dataframe to ndarray, since kf.split returns nparray as index
feature = df_train.iloc[:, 0: -1].values
target = df_train.iloc[:, -1].values
solver = MLPClassifier(activation='relu', solver='adam', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1, verbose=True)
y_pred = cross_val_predict(solver, feature, target, cv = 10)
基本上,選項 cv 表示您希望在培訓中進行多少次交叉驗證。 y_pred 與目標大小相同。
如果您正在尋找已經內置的方法來執行此操作,您可以查看cross_validate 。
from sklearn.model_selection import cross_validate
model = MLPClassifier()
cv_results = cross_validate(model, X, Y, cv=10,
return_train_score=False,
scoring=model.score)
print("Fit scores: {}".format(cv_results['test_score']))
我喜歡這種方法的一點是它可以讓您訪問 fit_time、score_time 和 test_score。 它還允許您提供您選擇的評分指標和交叉驗證生成器/迭代器(即 Kfold)。 另一個很好的資源是Cross Validation 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.