当使用三个通道重塑张量时,Numpy阵列尺寸不匹配

2024-04-26 00:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在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)

Tags: 数据testinfonumpyconvertfordsload
1条回答
网友
1楼 · 发布于 2024-04-26 00:09:05

张量一个形状(19280, 105, 105)通常意味着您有19280个样本,它们是大小为105×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,因为灰度图像只有一个通道

相关问题 更多 >