python - 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。
解决方案
为了使广播工作,您需要重新调整数组的形状,以便对齐大小为 50000 的尺寸。在您的示例中,掩码应替换为掩码 [:,None,None,None]。这样(50000,1,1,1)可以广播到(50000,32,32,3)。
推荐阅读
- macos - 尝试在 Mac OS Catalina 上为 OpenCV for Python 3.6.5 安装 virtualenv 时出错
- azure - 密码重置流程 Azure AD B2C
- reactjs - 如何使用 Promise 创建受保护的路由
- python - 内核不断死亡 Jupyter,Anaconda。尝试使用神经核函数实现共指解析
- c# - web api 项目的默认路由
- plotly-dash - 在破折号的下拉菜单中更改文本输入的字体颜色
- bluetooth - 蓝牙查找设备
- angular - 尝试在角度中使用 x-www-form-urlencoded 的 post 方法时收到错误消息 400(错误请求)
- python - 如果我为每个脚本运行相同的解释器,为什么我的 python 脚本只能在 Jupyter Notebook 中运行,而不在 VS Code 中运行?
- angular - 如何部署“适用于 COVID-19 的 Verily Pathfinder 虚拟代理模板”