Reputation: 531
I tried the following code, but I encountered the above error. I saw some similar questions but I didn't get a proper solution. Please help me!
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
mnist=tf.keras.datasets.mnist #download the dataset
(xtrain, ytrain),(xtest, ytest)=mnist.load_data() #split the dataset in test and train
xtrain=tf.keras.utils.normalize(xtrain, axis=1)
xtest=tf.keras.utils.normalize(xtest, axis=1)
model=tf.keras.models.Sequential() # start building the model
model.add(tf.keras.layers.Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Flatten()) # converting matrix to vector
model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) # adding a layer with 10 nodes(as only 10 outputs are possible) and softmax activaation function
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # specifiying hyperparameters
model.fit(xtrain,ytrain,epochs=5,) # load the model
model.save('Ashwatdhama') # save the model with a unique name
myModel=tf.keras.models.load_model('Ashwatdhama') # make an object of the model
prediction=myModel.predict((xtest)) # run the model object
for i in range(10):
print(np.argmax(prediction[i]))
plt.imshow(xtest[i]) # make visuals of mnist dataset
plt.show() #output
Upvotes: 1
Views: 490
Reputation: 22021
your network expect images in black and white (1 channel), so you have to modify your data accordingly to this. this is possible simply adding dimensionality to your images before fitting
xtrain = xtrain[...,None] # (batch_dim, 28, 28, 1)
xtest = xtest[...,None] # (batch_dim, 28, 28, 1)
Upvotes: 1