tf.keras.Sequential().compile error

Hello guys,

I was trying to run classification model on fashion mnist dataset, following book " Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 3rd Edition" . Section 10. Introduction to Artificial Neural Networks with Keras.

There they ran the code:

model.compile(loss="sparse_categorical_crossentropy",
              optimizer="sgd",
              metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=30,
                    validation_data=(X_valid, y_valid))

it was running sucessfully.
I changed model.compile code to:

model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              optimizer=tf.keras.optimizers.SGD(),
              metrics=[tf.keras.metrics.Accuracy()])

on running fit method I am getting error:
ValueError: Shapes (None, 1) and (None, 10) are incompatible

What I am doing wrong here? both chatgpt and bard unable to give me the satisfactory answer. Kindly help. Thanks

Seems like a fault in your output layer somehow ? Can you provide the entire code ?
Other than that, your code seems without any errors.

Found the error, the line metrics=[tf.keras.metrics.Accuracy()] is wrong rather one should use metrics=tf.keras.metrics.sparse_categorical_accuracy. problem got resolved. Thanks.

You might want to check out the shape of your output layer in the model that you’re training. Since this is an MNIST fashion example, it has 10 labels, and from the shape mismatch it looks like your output layer only has 1 output.