Numpy Broadcast_to((50000,), (50000,32,32,3)) 失败。为什么?
Numpy Broadcast_to((50000,), (50000,32,32,3)) fails. Why?
我正在尝试将 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)。
我正在尝试将 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)。