Skip to content Skip to sidebar Skip to footer

Keras Fit_generator Gives A Dimension Mismatch Error

I am working on MNIST dataset, in which X_train = (42000,28,28,1) is the training set. y_train = (42000,10) is the corresponding label set. Now I create an iterator from the image

Solution 1:

Shape mismatch was the root-cause. Input shape was not matching with what ImageDataGenetor expects. Please check the following example with mnist data. I have used Tensorflow 2.1.

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = tf.expand_dims(x_train,axis=-1)
x_test = tf.expand_dims(x_test,axis=-1)

datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2)

iter=datagen.flow(x_train,y_train,batch_size=32)

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28,1)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

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

#model.fit_generator(iter,steps_per_epoch=len(X_train)/32,epochs=1) # deprecated in TF2.1
model.fit_generator(iter,steps_per_epoch=len(iter),epochs=1)
model.evaluate(x_test, y_test) 

Full code is here

Post a Comment for "Keras Fit_generator Gives A Dimension Mismatch Error"