Search code examples
kerasconvolutionmnist

How to make prediction from a trained model of mnist using keras?


I have following a tutorial of using mnist with keras.I have trained the model and got a pretty good accuracy.Now how can i make a new prediction out of it by giving a new input. Here's the code

import numpy as np
from keras.layers import MaxPool2D,Conv2D,Dense,Flatten,Dropout
from keras.models import Sequential
from keras.utils import np_utils
from keras.layers import activations
from keras.datasets import mnist

np.random.seed(1)

(x_train,y_train),(x_test,y_test)=mnist.load_data()

x_train = x_train.reshape(x_train.shape[0],  28,28,1).astype('float32')
x_test = x_test.reshape(x_test.shape[0],  28, 28,1).astype('float32')

x_train=x_train.astype('float32')
x_tset=x_test.astype('float32')

x_train=x_train/255
x_test=x_test/255

y_train=np_utils.to_categorical(y_train,10)
y_test=np_utils.to_categorical(y_test,10)

model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)))
model.add(MaxPool2D(pool_size= (2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(32,(3,3), activation='relu',input_shape=(28,28,1)))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(units=128,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=10,activation='softmax'))

model.compile(optimizer='adam',loss='binary_crossentropy',metrics= ['accuracy'])

model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=10, batch_size=200, verbose=2)

model.evaluate(x_test,y_test,verbose=0)

model.save('hand_written.h5')

Thanks in Advance!!


Solution

  • This line of code in the tutorial is to take a new sample to evaluate your model:model.evaluate(x_test,y_test,verbose=0)What you need to do is give evaluate(x_test,y_test,verbose=0) the new input in this form. If you want to see how the prediction works, write this:
    prediction = model.evaluate(x_test,y_test,verbose=0) print('prediction:',prediction)