Suppose I have the following 2 arrays:
import numpy as np
a=np.asarray([[1,2,4],
[3,1,2]])
b=np.asarray([[2,1,1],
[3,2,3],
[4,1,2],
[2,2,1],])
For every row a_row in a, I would like to get the sum of squared difference between a_row and every row in b. The resulted array would be a 2 by 4 array. The expected result would be the following:
array([[ 11., 5., 14., 10.],
[ 2., 2., 1., 3.]])
I've already implemented a solution using loop:
c=np.zeros((2,4))
for e in range(a.shape[0]):
c[e,:] = np.sum(np.square(b-a[e,:]),axis=1)
print c
What I need is a fully vectorized solution, i.e. no loop is required.
Step 1: Import numpy. Step 2: Define two numpy arrays. Step 3: Find the set difference between these arrays using the setdiff1d() function. Step 4: Print the output.
To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.
To return True if all entries of two arrays are equal, use the ma. allequal() method in Python Numpy. Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.
square(arr, out = None, ufunc 'square') : This mathematical function helps user to calculate square value of each element in the array. Parameters : arr : [array_like] Input array or object whose elements, we need to square.
Here is a Numpythonic approach, simply by reshaping the b
in order to be able to directly subtract the a
from it:
>>> np.square(b[:,None] - a).sum(axis=2).T
array([[11, 5, 14, 10],
[ 2, 2, 1, 3]])
If you have access to scipy, then you could do:
import scipy
from scipy.spatial.distance import cdist
import numpy as np
a=np.asarray([[1,2,4],
[3,1,2]])
b=np.asarray([[2,1,1],
[3,2,3],
[4,1,2],
[2,2,1],])
x = cdist(a,b)**2
# print x
# array([[ 11., 5., 14., 10.],
# [ 2., 2., 1., 3.]])
This uses the cdist function which is vectorized and fast. You can possibly get a bit more speed using numba or cython, but it depends on the size of your arrays in practice.
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