Keras fit_generator给出尺寸不匹配错误 [英] Keras fit_generator gives a dimension mismatch error

查看:302
本文介绍了Keras fit_generator给出尺寸不匹配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究MNIST数据集,其中X_train = (42000,28,28,1)是训练集. y_train = (42000,10)是相应的标签集.现在,我使用Keras从图像生成器创建一个迭代器,如下所示;

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)

效果很好.

然后我使用训练模型;

Then I train the model using;

model.fit_generator(iter,steps_per_epoch=len(X_train)/32,epochs=1)

此处显示以下错误;

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:

预计density_218_input具有2维,但数组的形状为(512,28,28,1)

顺便说一下,这是我的模型摘要

BTW this is the summary of my model

请帮助我.

更新:

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'))

推荐答案

形状不匹配是根本原因.输入形状与ImageDataGenetor的预期不匹配.请检查以下示例中的mnist数据.我用过Tensorflow 2.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) 

完整代码为此处

这篇关于Keras fit_generator给出尺寸不匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆