首页 > 解决方案 > 使用三个通道重塑张量时 Numpy 数组尺寸不匹配

问题描述

我正在OmniglotKeras 数据集(一个图像数据集)上构建一个连体网络。当我尝试重塑数据集时,问题就出现了,说如下:

cannot reshape array of size 212562000 into shape (19280,105,105,3)

但是,当我检查数据集的形状时,它是

train_images.shape
(19280, 105, 105)

我对从哪里212562000得到的感到困惑。下面是使用到失败的代码。

 ' Load Omniglot dataset ' 
# load the training data
(ds_train, ds_test), ds_info = tfds.load(name='Omniglot', split=['train', 'test'], with_info=True)


# Convert labels to numpy arrays for manipulation
train_labels = np.array([[glyph["alphabet"].numpy() for glyph in ds_train]])    


# Convert images to numpy arrays for manipulation
train_images = np.array([glyph["image"].numpy()[:, :, 0] for glyph in ds_train])    


# Re-shape images for input layer
train_images = train_images.reshape(train_images.shape[0], train_images.shape[1], train_images.shape[2], 3)

标签: pythontensorflowkeras

解决方案


张量一个形状(19280, 105, 105)通常意味着您有 19280 个样本,这些样本是大小为 105 x 105 的灰度图像(可以看作是 的形状(19280, 105, 105, 1)),而 RGB 图像的张量具有形状(19280, 105, 105, 3)

问题是您正试图将灰度(或单通道)图像的张量重塑为彩色图像的张量。您不能这样做,因为形状不兼容,因此会出现错误。形状张量(19280, 105, 105)具有19280 x 105 x 105 = 212562000元素,您不能将其重塑为(19280, 105, 105, 3)具有19280 x 105 x 105 x 3 = 637686000元素的大小张量。

问题可能出在从数据集中提取 Numpy 数组的第三步中:

train_images = np.array([glyph["image"].numpy()[:, :, 0] for glyph in ds_train])

图像可能是彩色的,并且您在第三维中采用索引 0,因此您只采用第一个颜色维度(红色维度)。尝试移除[:, :, 0]以获得 3 个颜色通道。

3如果图像是灰度图像,请在重塑操作中替换为,1因为灰度图像只有 1 个通道。


推荐阅读