首页 > 解决方案 > Keras ImageDataGenerator:数据和标签形状的问题

问题描述

我想使用 Keras 生成更多图像,如您在此处看到的,使用此代码(几乎与source>Random Rotations相同):

# Random Rotations
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
from matplotlib import pyplot
from keras import backend as K
datagen = ImageDataGenerator(rotation_range=90)
# fit parameters from data
datagen.fit(cats["images"])

print(np.asarray(cats["label"]).shape)  #output=(12464,)
print(np.asarray(cats["images"]).shape) #output=(12464, 60, 60, 1)

# configure batch size and retrieve one batch of images
for X_batch, y_batch in datagen.flow(cats["images"], cats["label"], batch_size=9):
    # create a grid of 3x3 images
    for i in range(0, 9):
        pyplot.subplot(330 + 1 + i)
        pyplot.imshow(X_batch[i].reshape(28, 28), cmap=pyplot.get_cmap('gray'))
    # show the plot
    pyplot.show()
    break

但我收到以下错误:

ValueError:(x图像张量)和y(标签)应该具有相同的长度。找到:x.shape = (60, 60, 1), y.shape = (12464,)

这可能有助于进一步检查: 在此处输入图像描述

我想图书馆应该有问题,就好像我将图像的形状更改为 60x60 而不是 60x60x1 我会得到:

ValueError: 输入.fit()应该有 4 级。得到的数组形状为: (12464, 60, 60)

标签: pythontensorflowimage-processingkeras

解决方案


cats['images']和很可能cats['labels']是 Python 列表。首先使用将它们转换为数组np.array,然后将它们传递给flow方法:

cats['images'] = np.array(cats['images'])
cats['labels'] = np.array(cats['labels'])

推荐阅读