3

I'm trying to broadcast a 1D numpy array to a 4D numpy array but I get an error:

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

This is my code:

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

My goal is to cut out a bunch of classes out of the data and only keep the classes 0 and 1.

I thought that broadcasting was allowed when the dimensions were missing, like in my case. Can anyone explain why I'm getting the error?

I'm using Python 3.7.2.

Jupiter
  • 1,421
  • 2
  • 12
  • 31

1 Answers1

4

For broadcasting to work, you need to reshape the array such that the dimensions with size 50000 are aligned. In you example mask should be replaced by mask[:,None,None,None]. This way (50000,1,1,1) can be broadcasted to (50000,32,32,3).