Alexander Waters
Alexander Waters

Reputation: 73

Keras Shape 'ValueError'

I'm quite new to TensorFlow and currently using the fasion_mnist data set from Keras. when trying to get the model to fit my data its throwing a value error of the following: ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28]

The reason I am confused is because the images are 28x28 and black and white. The amount of images I have in my training set is 6000. Where does the 32 come from and why isn't my shape right?

my code in full:

import tensorflow as tf

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
print(x_train)

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28,28,1)),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.fit(x_train,y_train, epochs=10)

test_loss, test_acc = model.evaluate(x_test, y_test)

Upvotes: 2

Views: 340

Answers (1)

Luke B
Luke B

Reputation: 1204

You need to reshape x_train and x_test to have the right shape.

x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(60000, 28, 28, 1)

Your shape goes from (60000, 28, 28) to (60000, 28, 28, 1).

You can take a look at this blog from tensorflow. There's a colab notebook linked in it. It does what you are trying to do.

Upvotes: 4

Related Questions