问题
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 generator using Keras as follows;
iter=datagen.flow(X_train,y_train,batch_size=32)
which works fine.
Then I train the model using;
model.fit_generator(iter,steps_per_epoch=len(X_train)/32,epochs=1)
Here it gives the following error;
ValueError: Error when checking input: expected dense_9_input to have 2 dimensions, but got array with shape (32, 28, 28, 1)
I tried but failed to find the mistake. Also I searched here but there was no answer:
expected dense_218_input to have 2 dimensions, but got array with shape (512, 28, 28, 1)
BTW this is the summary of my model
Please help me.
Update:
model=Sequential()
model.add(Dense(256,activation='relu',kernel_initializer='he_normal',input_shape=(28,28,1)))
model.add(Flatten())
model.add(Dense(10,activation='softmax',kernel_initializer='he_normal'))
回答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
来源:https://stackoverflow.com/questions/61454294/keras-fit-generator-gives-a-dimension-mismatch-error