Smallest square difference between numpy array elements

I just started to learn a little numpy because of High - performance least squares calculation is different from all possible combinations (n ​​lists) :

I started calculations right now and could use some help.

I have a numpy array object that looks like this:

>>> items array([[ 246, 1143, 1491, ..., 1167, 325, 1158], [ 246, 1143, 1491, ..., 1167, 519, 1158], [ 246, 1143, 1491, ..., 1167, 507, 1158], ..., [1491, 1143, 246, ..., 1167, 325, 1158], [1491, 1143, 246, ..., 1167, 519, 1158], [1491, 1143, 246, ..., 1167, 507, 1158]]) 

I would like to get the array number with the smallest square difference among all its members, the numpythonic version:

 for num,item in enumerate(items): #Calculate for each list of items for n in range(len(item)): for i in range(n, len(item)): dist += (item[n]-item[i])**2 #Key formula if dist>min_dist: #This is a shortcut break else: continue break if min_dist is None or dist < min_dist: min_dist = dist best = num #We get the number of the combination we want 

I would be grateful for any tips.

+4
source share
2 answers

Initialize the NxM array:

 >>> import numpy as np >>> items = np.random.random_sample((10,3)) 

Calculate the sum of squares between all the elements of each of the N M -dimensional vectors and save the results in the list:

 >>> sq = [(np.subtract.outer(item,item) ** 2).sum() for item in items] 

Find the index of the vector with the least sum of squares between all its elements:

 >>> best_index = np.argmin(sq) 

Or, to avoid an intermediate list:

 best = np.inf best_index = None for i,item in enumerate(items): ls = (np.subtract.outer(item,item) ** 2).sum() if ls < best: best = ls best_index = i 
+1
source
 import numpy as np [(lambda(x):np.square(np.dot(x,-1*x)))(x) for x in items] 
0
source

All Articles