Question

I am trying to train a Sequential model using simple flow_from_directory() but i am getting this error , I have tried using lesser layers but the error dose not go away.

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Flatten



train_directory = 'D:\D_data\Rock_Paper_Scissors\Train'
training_datgagen = ImageDataGenerator(rescale = 1./255)
training_generator = training_datgagen.flow_from_directory(
train_directory,
target_size = (28,28),
class_mode = 'categorical')

validation_directory = 'D:\D_data\Rock_Paper_Scissors\Test'
validation_datagen = ImageDataGenerator(rescale= 1./255)
validation_generator = validation_datagen.flow_from_directory(
validation_directory,
target_size = (28,28),
class_mode = 'categorical'
)

model = Sequential()

model.add(Dense(128, input_shape = (784,)))
model.add(Dense(64, activation = 'relu'))
model.add(Dense(16, activation = 'relu'))
model.add(Dense(3, activation = 'softmax'))

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

model.fit_generator(training_generator,epochs=10)

Here is the error:

File "C:\Users\Ankit\.spyder-py3\temp.py", line 31, in <module>
    model.fit_generator(training_generator,epochs=10)

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training.py", line 1732, in fit_generator
    initial_epoch=initial_epoch)

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training_generator.py", line 220, in fit_generator
    reset_metrics=False)

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training.py", line 1508, in train_on_batch
    class_weight=class_weight)

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training.py", line 579, in _standardize_user_data
    exception_prefix='input')

  File "C:\Users\Ankit\anaconda3\lib\site-packages\keras\engine\training_utils.py", line 135, in standardize_input_data
    'with shape ' + str(data_shape))

  ValueError: Error when checking input: expected dense_56_input to have 2 dimensions, but got array with shape (32, 28, 28, 3)
Was it helpful?

Solution

The error occurs due to mismatch in the input shape. In the model you have specified it as input_shape = (784,) but the actual images that the model is getting as input are of different size. Just put the input shape as input_shape = (32, 32, 3) and you are good to go. Take a look here for more details on how to specify the input_shape.

Also, you'll have to use convolutional layers to process images or you can use a flatten layer before using dense layers!

Licensed under: CC-BY-SA with attribution
Not affiliated with datascience.stackexchange
scroll top