python - 使用三个通道重塑张量时 Numpy 数组尺寸不匹配
问题描述
我正在Omniglot
Keras 数据集(一个图像数据集)上构建一个连体网络。当我尝试重塑数据集时,问题就出现了,说如下:
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)
解决方案
张量一个形状(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 个通道。
推荐阅读
- flutter - 颤振通知图标在Android中没有改变
- electron - 通过requirejs导入电子
- google-apps-script - 有没有办法在 Google 表格中创建脚本来打印 2 份活动工作表?
- python - Python 如何从打印结果中删除前导回车?
- javascript - JavaScript 前导零数字填充
- reactjs - 在两个组件之间使用 Cookie
- android - 科尔多瓦上的导航栏颜色没有改变
- firebase - 未捕获的错误:预期类型为“FutureOr”的值
',但得到了“MemoryInfo”类型之一 - php - 如何创建两个 laravel 项目(在同一台服务器上),共享除资源(视图)文件夹之外的所有文件
- flutter - Flutter - Listview 超出容器边界半径