在python中,給定一個大小為3*2的矩陣,如
A=[[x11,x12,x13],[x21,x22,x23]]和一個列向量b=[mu1;mu2>。如果我想計算A的每一列和向量b之間的歐幾里得距離。例如,對于第一列,距離'd1'是由
A=[[x11,x12,x13], [x21,x22,x23]]
b=[[mu1],[mu2]]
d1=(x11-mu1)^2 (x21-mu2)^2
#第二列
d2=(x12-mu1)^2 (x22-mu2)^2
# 以此類推。
因此,距離可以在一個矩陣中評分[d1,d2,d3],其大小為3*1:
我可以計算出更小的矩陣的距離。但如果矩陣A較大,如大小為100*2,如何獲得所有數量的距離(即大小為100*1的矩陣)?
uj5u.com熱心網友回復:
你可以使用逐點減法,然后對兩列進行平方和:
>>> np. sum((A-b)**2, 1)
正如@Gilad Green所指出的,如果b的形狀是(n, 1),那么將需要一個轉置:
無論是對b:
>>> np. sum((A-b.T)**2,1)
或者在A上(注意在軸=0上的求和)
>>> np。 sum((A.T-b)**2, 0)
>>> A = np.random.rand(3,2)
>>> b = np.random.rand(2)
>>> A - b
array([[0.21263611, 0.47988496],
[0.91061396, 0.93371001],
[0.66321026, 0.21926392]])
>>> (A - b)**2
array([[0.04521411, 0.23028957],
[0.82921779, 0.87181438],
[0.43984785, 0.04807667]])
>>> np.sum((A-b)**2,1)
array([0.27550369, 1.70103217, 0.48792451] )
uj5u.com熱心網友回復:
對于歐幾里得距離,你可以使用以下任何方法:
在[1]。import numpy as np
在[2]。A = np.random.rand(3, 2)
在[3]: b = np.random.rand(2)
在[4]。Ab = A - b
在[5]中。Ab.形狀
輸出[5]。(3, 2)
在[6]。A
輸出[6]。
array([[0.88888598, 0.71558933],
[0.42653942, 0.80202214],
[0.37195937, 0.24403248]])
在[7]: b
Out[7]: array([0.13348342, 0.91007169] )
在[8]。腹部
輸出[8]。
array([[ 0.75540256, -0.19448237],
[0.293056 , -0.10804955] 。
[0.23847595, -0.66603921]])
在[9]: np.sqrt(np.sum(Ab**2, axis=1)
Out[9]: array([0.78003617, 0.3123404 , 0.70744541] )
在[10]: np.linalg.norm(Ab, axis=1)
Out[10]: array([0.78003617, 0.3123404 , 0.70744541] )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/326849.html
標籤:
上一篇:Oracle資料庫日常管理
下一篇:在二維陣列中搜索多個元素?
