Keras中的ImageDataGenerator形状问题

时间:2019-03-14 10:48:41

标签: python keras

datagen = ImageDataGenerator(
            featurewise_center=False,  # set input mean to 0 over the dataset
            samplewise_center=False,  # set each sample mean to 0
            featurewise_std_normalization=False,  # divide inputs by std of the dataset
            samplewise_std_normalization=False,  # divide each input by its std
            zca_whitening=False,  # apply ZCA whitening
            rotation_range=15,  # randomly rotate images in the range (degrees, 0 to 180)
            width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
            height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
            horizontal_flip=True,  # randomly flip images
            vertical_flip=False)  # randomly flip images
        # (std, mean, and principal components if ZCA whitening is applied).
        # datagen.fit(x_train)


        print(x_train.shape)

        def data_generator(generator, x, y1, y2, batch_size):
            genX = generator.flow(x, seed=7, batch_size=batch_size)
            genY1 = generator.flow(y1, seed=7, batch_size=batch_size)
            genY2 = generator.flow(y2, seed=7, batch_size=batch_size)
            while(True):
                Xi = genX.next()
                Yi1 = genY1.next()
                Yi2 = genY2.next()
                yield Xi, [Yi1, Yi2]

这就是我调用model.fit_generator的方式

model.fit_generator(data_generator(datagen, x_train, y_train, y_aux_train, params['batch_size']),
                            epochs=params['epochs'], steps_per_epoch=150,
                            validation_data=data_generator(datagen, x_test, y_test, y_aux_test, params['batch_size']), 
                            validation_steps=100, callbacks=[reduce_lr, tensorboard],verbose=2)

这是我得到的错误-

  

ValueError:('NumpyArrayIterator中的输入数据应具有等级4。   您传递了一个带有形状的数组',(5630,4))

2 个答案:

答案 0 :(得分:0)

您的xy1y2是什么? ImageDataGenerator的输入数据必须具有4个维度(批,通道,高度,宽度)。您的数据完全不同,这就是为什么会出现错误。

更新:

根据docs

flow(x, y=None, batch_size=32, shuffle=True, sample_weight=None, seed=None, save_to_dir=None, save_prefix='', save_format='png', subset=None)
  

x:输入数据。 Numpy数组,等级4或元组。如果是元组,则第一个   元素应包含图片,第二个元素应包含另一个numpy   数组或numpy数组的列表,这些列表将传递给输出而无需   任何修改。可用于馈送模型的其他数据   以及图像。

genY1 = generator.flow(y1, seed=7, batch_size=batch_size)中,将您的标签(如我所见,形状为(4,))作为要素传递,ImageDataGenerator希望它们具有4个尺寸。

您不应通过这样的标签。尝试像这样:

datagen.flow((x_train, [y_train, y_aux_train]), batch_size=params['batch_size'])

或者:

datagen.flow(x=x_train, y=[y_train, y_aux_train], batch_size=params['batch_size'])

答案 1 :(得分:0)

我不知道您输入的形状...但是由于错误,我可以告诉您以下内容... 是的,参数x的输入值必须为4级... 我将举例说明。从Keras下载的MNIST数据集以形状为60000(用于测试)的NumPy ndarray的形式出现(28,28),如果将其传递给ImageDataGenerator作为参数“ x”的输入,则会得到相同的错误。您可以通过调整数组大小来解决此问题。

<your image ndarray>.reshape(<your image ndarray>.shape[0],28,28,1)

注意:上一行的最后一个值,即灰度图像的1和RGB图像的3,分别是图像中的颜色通道数。

因此,我建议您调整ndarray的大小,使其具有四个维度。