Skip to main content
 首页 » 编程设计

python之凯拉斯图像数据生成器 : problem with data and label shape

2025年05月04日12zdz8207

我想使用 Keras 生成更多图像,您可以在 here 中看到, 使用此代码(几乎与 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 (images tensor) and y (labels) should have the same length. Found: x.shape = (60, 60, 1), y.shape = (12464,)

这可能有助于进一步检查:

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

ValueError: Input to .fit() should have rank 4. Got array with shape: (12464, 60, 60)

请您参考如下方法:

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

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