0

我有一组来自 tensorflow 基本图像分类指南的名为 train_images 和 train_labels 的集合:

https://www.tensorflow.org/tutorials/keras/classification

我加载数据集:

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

这两个列表的形状分别是: (60000, 28, 28) (60000,)

之后我想使用 ImageDataGenerator 水平翻转一些图像,但是当我用我的火车列表拟合模型时,它返回我的错误,说 x 应该是一个秩为 4 的数组

我已经尝试过

train_images = (np.expand_dims(train_images,0))

所以形状变成(1,60000,28,28)(我必须这样做才能让模型检查单个图像)但它不适用于模型

这是代码的其余部分:

aug = ImageDataGenerator(rotation_range=20, horizontal_flip=True)

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

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

BS=32
EPOCHS=10
H = model.fit_generator(
    aug.flow(train_images, train_labels, batch_size=BS),
    validation_data=(test_images, test_labels),
    steps_per_epoch=len(train_images) // BS,
    epochs=EPOCHS)

这是生成的错误:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-65-e49da92bcb89> in <module>()
      5 #train_images.shape
      6 H = model.fit_generator(
----> 7         aug.flow(train_images, train_labels, batch_size=BS),
      8         validation_data=(test_images, test_labels),
      9         steps_per_epoch=len(train_images) // BS,

1 frames
/usr/local/lib/python3.6/dist-packages/keras_preprocessing/image/numpy_array_iterator.py in __init__(self, x, y, image_data_generator, batch_size, shuffle, sample_weight, seed, data_format, save_to_dir, save_prefix, save_format, subset, dtype)

    115             raise ValueError('Input data in `NumpyArrayIterator` '
    116                              'should have rank 4. You passed an array '
--> 117                              'with shape', self.x.shape)
    118         channels_axis = 3 if data_format == 'channels_last' else 1
    119         if self.x.shape[channels_axis] not in {1, 3, 4}:

ValueError: ('Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (60000, 28, 28))

实际上 train_images 是 (N° of images, width, height) 它等待的第 4 轴是什么?如何执行此操作?

4

2 回答 2

1

您应该将图像转换为 4D 张量。现在您有了 NHW 格式(批量尺寸、高度、宽度)。该错误表明您应该具有 NHWC 格式 - 批次、高度、宽度、通道。所以你需要做

train_images = (np.expand_dims(train_images, axis=3))

这将添加一个通道维度(大小为 1),生成的形状将是 (60000,28,28,1),它应该可以解决您的问题。

于 2019-10-25T10:24:30.240 回答
0

通道应该是 4D 张量的最后一个维度。因此,不要train_images = (np.expand_dims(train_images,0))尝试使用train_images = (np.expand_dims(train_images, -1)). 希望它会有所帮助。

于 2019-10-25T10:37:15.753 回答