I'm observing some odd behaviour using numpy broadcasting. The problem is illustrated below, where running the first piece of code produces an error:
A = np.ones((10))
B = np.ones((10, 4))
C = np.ones((10))
np.asarray([A, B, C])
ValueError: could not broadcast input array from shape (10,4) into shape (10)
If I instead expand the dimensions of B, using B = np.expand_dims(B, axis=0), it will successfully create the array, but it now has (not surprisingly) the wrong dimensions:
array([array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
array([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]]),
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])], dtype=float32)
Why does it fail to broadcast the first example, and how can I end up with an array like below (notice only double brackets around the second array)? Any feedback is much appreciated.
array([array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]),
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])], dtype=object)
Including, say, None prevents the broadcasting, so this workaround is an option:
np.asarray([A, B, C, None])[:-1]
Here the outcome:
array([array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]]),
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])], dtype=object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With