简体   繁体   中英

ValueError: Input 0 of layer sequential_6 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 28, 28]

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM