I have the following numpy arrays:
arr_1 = [[1,2],[3,4],[5,6]] # 3 X 2
arr_2 = [[0.5,0.6],[0.7,0.8],[0.9,1.0],[1.1,1.2],[1.3,1.4]] # 5 X 2
arr_1
is clearly a 3 X 2
array, whereas arr_2
is a 5 X 2
array.
Now without looping, I want to element-wise multiply arr_1 and arr_2 so that I apply a sliding window technique (window size 3) to arr_2.
Example:
Multiplication 1: np.multiply(arr_1,arr_2[:3,:])
Multiplication 2: np.multiply(arr_1,arr_2[1:4,:])
Multiplication 3: np.multiply(arr_1,arr_2[2:5,:])
I want to do this in some sort of a matrix multiplication form to make it faster than my current solution which is of the form:
for i in (2):
np.multiply(arr_1,arr_2[i:i+3,:])
So if the number of rows in arr_2 are large (of the order of tens of thousands), this solution doesn't really scale very well.
Any help would be much appreciated.
This is a nice case to test the speed of
as_strided
and Divakar's broadcasting.Create Numpy array without enumerating array for more of a comparison of these methods.
We can use
NumPy broadcasting
to create those sliding windowed indices in a vectorized manner. Then, we can simply index intoarr_2
with those to create a3D
array and perform element-wise multiplication with2D
arrayarr_1
, which in turn will bring onbroadcasting
again.So, we would have a vectorized implementation like so -
Runtime test and verify results -