Consider the following exercise in Numpy array broadcasting.
import numpy as np
v = np.array([[1.0, 2.0]]).T # column array
A2 = np.random.randn(2,10) # 2D array
A3 = np.random.randn(2,10,10) # 3D
v * A2 # works great
# causes error:
v * A3 # error
I know the Numpy rules for broadcasting, and I'm familiar with bsxfun
functionality in Matlab. I understand why attempting to broadcast a (2,1) array into a (2,N,N) array fails, and that I have to reshape the (2,1) array into a (2,1,1) array before this broadcasting goes through.
My question is: is there any way to tell Python to automatically pad the dimensionality of an array when it attempts to broadcast, without me having to specifically tell it the necessary dimension?
I don't want to explicitly couple the (2,1) vector with the multidimensional array it's going to be broadcast against---otherwise I could do something stupid and absurdly ugly like mult_v_A = lambda v,A: v.reshape([v.size] + [1]*(A.ndim-1)) * A
. I don't know ahead of time if the "A" array will be 2D or 3D or N-D.
Matlab's bsxfun
broadcasting functionality implicitly pads the dimensions as needed, so I'm hoping there's something I could do in Python.
v
and then you had a 2-by-2-by-10ndarray
. Do you want to reshapev
to have shape(2,1,1)
or shape(1,2,1)
? If you just pad the dimensions, it could be ambiguous to the user. Forcing an explicit reshape is a better general procedure, and leave it to the user to write a special function to perform the reshaping automatically if the user has a fixed convention. But it's not good to make a globalnumpy
dimension-padder that forces a convention upon you. It would be too easy to misuse. – elynumpy.apply_along_axis
andnumpy.tensordot
in particular seem more than sufficient for this kind of thing, while still leaving the nice property that the programmer must make some explicit reference to the way that ambiguous dimension changes should occur for broadcasting. – elyapply_along_axis
to totally destroy performance by de-vectorizing the array operation. Also, broadcasting is much more useful than just multiplication viatensordot
. – Ahmed Fasih