首页 > 解决方案 > Numpy Broadcast_to((50000,), (50000,32,32,3)) 失败。为什么?

问题描述

我正在尝试将 1D numpy 数组广播到 4D numpy 数组,但出现错误:

operands could not be broadcast together with remapped shapes [original->remapped]: (50000,) and requested shape (50000,32,32,3)

这是我的代码:

from tensorflow.keras.datasets import cifar10

import numpy as np

(x_train, y_train), (x_test, y_test) = cifar10.load_data()

mask = (y_train == 0) | (y_train == 1)
y_train = np.ma.masked_array(y_train, mask = mask)
mask = np.broadcast_to(mask.reshape(-1), x_train.shape)
x_train = np.ma.masked_array(x_train, mask = mask) # Error happens here

# Same for the test set

我的目标是从数据中删除一堆类,只保留类 0 和 1。

我认为当尺寸丢失时允许广播,就像我的情况一样。谁能解释我为什么会收到错误?

我正在使用 Python 3.7.2。

标签: pythonpython-3.xnumpyarray-broadcasting

解决方案


为了使广播工作,您需要重新调整数组的形状,以便对齐大小为 50000 的尺寸。在您的示例中,掩码应替换为掩码 [:,None,None,None]。这样(50000,1,1,1)可以广播到(50000,32,32,3)。


推荐阅读