TransWikia.com

K-fold cross validation of scikit-learn with confusion matrix of Keras

Data Science Asked by PS Nayak on January 29, 2021

I intend to display confusion matrix using Keras while K-fold of scikit-learn. My code using Keras is:

import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense

seed = 7
numpy.random.seed(seed)

# load dataset
dataframe = pandas.read_csv("BolMov.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:24].astype(float)
Y = dataset[:,24]

model = Sequential()
model.add(Dense(16, activation='relu'))
model.add(Dense(7, activation='softmax')
model.compile('adam', 'categorical_crossentropy', metrics=['accuracy'])

y_cat = to_categorical(Y)
result = model.fit(X, y_cat, verbose=0, epochs=50)

plot_loss_accuracy(result)

y_pred = model.predict_classes(X, verbose=0)

print(classification_report(y, y_pred))
plot_confusion_matrix(model, X, y)

How should I use kfold in this code? Here the author is calling a function. What I believe is that if I do so in my code, the model.fit() will be executed twice – once for my Keras code and another time (internally) for the KerasClassifier(). I want that the model.fit() executes once only. Help from anyone is appreciated.

One Answer

KFold() is meant for cross-validation purpose where multiple models are created over the subsets of the entire dataset and discarded after the validation procedure is over. So the model.fit() should be called explicitly to create the model for purpose. Both the tasks can be easily done through the wrapper named KerasClassifier() by packaging all the details of the model design.

Answered by PS Nayak on January 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP