python-3.x Numpy argmin()查找最近的元组

rqcrx0a6  于 12个月前  发布在  Python
关注(0)|答案(2)|浏览(164)

我有一个元组数组,我需要从该数组中找到与给定元组(元素)接近的元组,即通过这两个元组中每个元素之间的绝对值差。元组数组如下:

array_of_tuples = [(0.0, 6.5, 1),
     (0.0, 6.5, 4.5),
     (0.0, 6.5, 8.0),
     (0.0, 13.5, 1),
     (0.0, 13.5, 4.5),
     (0.0, 13.5, 8.0),
     (0.0, 21.0, 1),
     (0.0, 21.0, 4.5),
     (0.0, 21.0, 8.0),
     (7.0, 6.5, 1),
     (7.0, 6.5, 4.5),
     (13.5, 21.0, 8.0)]

字符串
当查询元组为(13.1, 20.3, 8.4)
标签:np.argmin(np.abs(array_of_tuples - (13.1, 20.3, 8.4)))
给出了8,而如果我在没有np.argmin()的情况下打印结果,我可以清楚地看到它是数组中与给定元组差异最小的最后一个元素。

6ioyuze2

6ioyuze21#

您必须考虑所有坐标并将其聚合为单个数字(每行)。
计算平方和并得到(arg)min:

np.argmin(((array_of_tuples - (13.1, 20.3, 8.4))**2).sum(axis=1))

字符串
输出:11
argmin之前的中间体:

array([416.81, 377.26, 362.21, 272.61, 233.06, 218.01, 226.86, 187.31,
       172.26, 282.41, 242.86,   0.81])


正如@MadPhysicist所建议的,你也可以使用numpy.linalg.norm来计算每行的norm

np.argmin(np.linalg.norm(array_of_tuples-(13.1, 20.3, 8.4), axis=1))

oyjwcjzk

oyjwcjzk2#

它所做的是正确的。看到一步一步

import numpy as np
array_of_tuples = [(0.0, 6.5, 1),
     (0.0, 6.5, 4.5),
     (0.0, 6.5, 8.0),
     (0.0, 13.5, 1),
     (0.0, 13.5, 4.5),
     (0.0, 13.5, 8.0),
     (0.0, 21.0, 1),
     (0.0, 21.0, 4.5),
     (0.0, 21.0, 8.0),
     (7.0, 6.5, 1),
     (7.0, 6.5, 4.5),
    (13.5, 21.0, 8.0)]
array_of_tuples = np.array(array_of_tuples)

sub = array_of_tuples -  (13.1, 20.3, 8.4)
print(sub)

'''
output:
subtracted (13.1, 20.3, 8.4)
[[-13.1 -13.8  -7.4]
 [-13.1 -13.8  -3.9]
 [-13.1 -13.8  -0.4]
 [-13.1  -6.8  -7.4]
 [-13.1  -6.8  -3.9]
 [-13.1  -6.8  -0.4]
 [-13.1   0.7  -7.4]
 [-13.1   0.7  -3.9]
 [-13.1   0.7  -0.4]
 [ -6.1 -13.8  -7.4]
 [ -6.1 -13.8  -3.9]
 [  0.4   0.7  -0.4]]
 '''

ab = np.abs(sub)
print(ab)
'''
negatives are made into positives
output:
[[13.1 13.8  7.4]
 [13.1 13.8  3.9]
 [13.1 13.8  0.4]
 [13.1  6.8  7.4]
 [13.1  6.8  3.9]
 [13.1  6.8  0.4]
 [13.1  0.7  7.4]
 [13.1  0.7  3.9]
 [13.1  0.7  0.4]
 [ 6.1 13.8  7.4]
 [ 6.1 13.8  3.9]
 [ 0.4  0.7  0.4]]
 '''

n = np.argmin(ab)
print(n)

#output 8
#Because no axis given. 0.4 is the smallest number. its index is 8 if array is converted into single dimension

字符串
这里没有给出坐标轴,0.4是最小的数字,也是第一次出现的数字,如果把数组转换成一维的话,它的下标是8

相关问题