Working with Fashion mnist data

I ran the code below

import tensorflow as tf

data = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = data.load_data()
training_images = training_images.astype('float32') / 255.0
test_images = test_images.astype('float32') / 255.0
training_images = training_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
# model.evaluate(test_images, test_labels)

But got this error:
ValueError: Shapes (32,) and (32, 28, 10) are incompatible
What Iā€™m I missing?

Hi @Clem_Clem, Before passing the input to the dense layer, you have to flatten your input data because the dense layer accepts 1d input.

model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(28, 28)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

Also you are not converting the labels to the categorical change the loss function to SparseCategoricalCrossentropy while compiling the model.

model.compile(optimizer='adam', loss='SparseCategoricalCrossentropy', metrics=['accuracy'])

Please refer to this gist for working code example. Thank You.

1 Like