Grimlock
Grimlock

Reputation: 1091

How to transform test data according to model in CNN?

I'm new to Keras and I am learning to build Convolutional Neural Network models. I am using MNIST dataset.

(X_train, y_train), (X_test, y_test) = mnist.load_data()

After building and evaluating I am getting 99%+ accuracy.

model = NN_model() # Sequential model built with multiple Convolution and pooling layers

model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=200, verbose=2)

scores = model.evaluate(X_test, y_test, verbose=0)

Now, I want to check result manually by picking a random image, printing it using matplotlib and then predicting it using the learned model. For example, the X_test[39] data looks like this.

print(model.predict(X_test[39],verbose=2))

When I try to do this, it asks me to convert the pre-processed data into conv2d data, as the model is converting it. How do I apply this transformation on test data manually?

ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (1, 28, 28)

Upvotes: 2

Views: 521

Answers (2)

Dr. Snoopy
Dr. Snoopy

Reputation: 56387

The model is not converting anything, the network takes a batch of images which has shape (num_samples, channels, width, height). In this case you have a single sample so you should set num_samples to one by adding a new dimension:

sample = X_test[39]
model.predict(sample[np.newaxis, :, :, :])

Or you can also just reshape the sample array to (1, 1, 28, 28).

Upvotes: 5

Andrey Lukyanenko
Andrey Lukyanenko

Reputation: 3851

I suppose that you need to reshape data (maybe it is done within the model while training, can't say without the code). Try something like this:

print(model.predict(X_test[39].reshape(-1, 28, 28, 1),verbose=2))

Upvotes: 2

Related Questions