parsa
parsa

Reputation: 370

Error when checking input: expected conv2d_27_input to have 4 dimensions, but got array with shape (55000, 28, 28)

hi i'm trying to use cnn on fashion mnist data there are 5200 images 28*28 in grayscale so i used a 2D cnn here is my code:

fashion_mnist=keras.datasets.fashion_mnist
(xtrain,ytrain),(xtest,ytest)=fashion_mnist.load_data()
xvalid,xtrain=xtrain[:5000]/255.0,xtrain[5000:]/255.0
yvalid,ytrain=ytrain[:5000],ytrain[5000:]

defaultcon=partial(keras.layers.Conv2D,kernel_size=3,activation='relu',padding="SAME")

model=keras.models.Sequential([
                           defaultcon(filters=64,kernel_size=7,input_shape=[28,28,1]),
                           keras.layers.MaxPooling2D(pool_size=2),
                           defaultcon(filters=128),
                           defaultcon(filters=128),
                           keras.layers.MaxPooling2D(pool_size=2),
                           defaultcon(filters=256),
                           defaultcon(filters=256),
                           keras.layers.MaxPooling2D(pool_size=2),
                           keras.layers.Flatten(),
                           keras.layers.Dense(units=128,activation='relu'),
                           keras.layers.Dropout(0.5),
                           keras.layers.Dense(units=64,activation='relu'),
                           keras.layers.Dropout(0.5),
                           keras.layers.Dense(units=10,activation='softmax'),

])
model.compile(optimizer='sgd',loss="sparse_categorical_crossentropy", metrics=["accuracy"])
history=model.fit(xtrain,ytrain,epochs=30,validation_data=(xvalid,yvalid))

but i get Error when checking input: expected conv2d_27_input to have 4 dimensions, but got array with shape (55000, 28, 28) how expected to get 4D ?

Upvotes: 0

Views: 70

Answers (1)

alift
alift

Reputation: 1928

In the input line :

defaultcon(filters=64,kernel_size=7,input_shape=[28,28,1])

you mistakenly defined the shape (28,28,1) which is not correct. And for a task with m samples, model will expect the data with the dimension of (m,28,28,1) which is a 4D.

Apparently your inputs are in the shape of (m,28,28) where m is the number of samples. So you can solve your problem by changing the line I mentioned above with this one:

defaultcon(filters=64,kernel_size=7,input_shape=(28,28))

and hopefully, you will be all set.

Upvotes: 1

Related Questions