前提・実現したいこと
Kerasを用いてMNIST10種分類問題を行っており、出てきた結果に対してK交差検証を行いたいのですが、cross_val_score
でエラーが発生してしまいます。
発生している問題・エラーメッセージ
File "C:/Users/user/PycharmProjects/MNIST/MNISTlkfoldxval.py", line 111, in <module> scores = cross_val_score(hist, X_train, Y_train, cv=kf) File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\model_selection\_validation.py", line 384, in cross_val_score scorer = check_scoring(estimator, scoring=scoring) File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\metrics\scorer.py", line 270, in check_scoring 6000/6000 [==============================] - 0s 51us/step - loss: 0.4041 - accuracy: 0.8767 - val_loss: 0.3896 - val_accuracy: 0.8945 "'fit' method, %r was passed" % estimator) TypeError: estimator should be an estimator implementing 'fit' method, <keras.callbacks.callbacks.History object at 0x000001BBCF15FEB8> was passed
該当のソースコード
python
1mnist = datasets.fetch_mldata('MNIST original', data_home='.') 2 3n = len(mnist.data) 4N = 10000 # MNISTの一部を使う 5N_train = 8000 6N_validation = 2000 7indices = np.random.permutation(range(n))[:N] # ランダムにN枚を選択 8 9X = mnist.data[indices] 10X = X / 255.0 11X = X - X.mean(axis=1).reshape(len(X), 1) 12y = mnist.target[indices] 13Y = np.eye(10)[y.astype(int)] 14 15X_train, X_test, Y_train, Y_test = \ 16 train_test_split(X, Y, train_size=N_train) 17X_train, X_validation, Y_train, Y_validation = \ 18 train_test_split(X_train, Y_train, test_size=N_validation) 19 20#モデル設定 21 22n_in = len(X[0]) # 784 23n_hidden = 200 24n_out = len(Y[0]) # 10 25p_keep = 0.5 26activation = 'relu' 27 28model = Sequential() 29model.add(Dense(n_hidden, input_dim=n_in)) 30model.add(Activation(activation)) 31model.add(Dropout(p_keep)) 32 33model.add(Dense(n_hidden)) 34model.add(Activation(activation)) 35model.add(Dropout(p_keep)) 36 37model.add(Dense(n_out)) 38model.add(Activation('softmax')) 39 40model.compile(loss='categorical_crossentropy', 41 optimizer=SGD(lr=0.01, momentum=0.9), 42 metrics=['accuracy']) 43 44#モデル学習 45batch_size = 200 46hist_acc_t = hist_acc_v = hist_loss_t = hist_loss_v = [] 47max_epochs = 10 48ep_learn_interval = 50 49 50project_name = 'MNIST' + activation + str(max_epochs) 51modellog = project_name + 'models' 52os.makedirs(modellog, exist_ok=True) 53 54model_checkpoint = ModelCheckpoint( 55 filepath=os.path.join(modellog, 'model_{epoch:02d}-{loss:.2f}-{acc:.2f}-{val_loss:.2f}-{val_acc:.2f}.hdf5'), 56 monitor='val_loss', 57 verbose=1, period=50) 58 59hist = model.fit(X_train, Y_train, batch_size=batch_size, 60 epochs = max_epochs, 61 validation_data = (X_validation, Y_validation), 62 callbacks=[model_checkpoint]) 63 64hist_acc_t = hist_acc_t + hist.history['accuracy'] 65hist_acc_v = hist_acc_v + hist.history['val_accuracy'] 66hist_loss_t = hist_loss_t + hist.history['loss'] 67hist_loss_v = hist_loss_v + hist.history['val_loss'] 68 69kf = KFold(n_splits=5, shuffle=True, random_state=42) 70scores = cross_val_score(hist, X_train, Y_train, cv=kf) 71 72#学習の進み具合を可視化 73# 各分割におけるスコア 74print('Cross-Validation scores: {}'.format(scores)) 75# スコアの平均値 76import numpy as np 77print('Average score: {}'.format(np.mean(scores)))
試したこと
ウェブ上をいろいろ参考にしましたが、cross_val_scoreの使われ方がコードによって違うのでどれを適用したらいいのかわからず困っております。よろしければお力をお貸しください。
補足情報(FW/ツールのバージョンなど)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/10/09 07:05
2019/10/09 07:30
2019/10/09 07:33
退会済みユーザー
2019/10/14 04:25