Numpy のブロードキャスト メカニズムは、行列間のペアごとの距離を効率的に計算します。

numpy を使用すると、2 つの 2 次元配列間の距離を簡単に計算できます。2 次元配列間の距離は次のように定義されます。X の次元は (a,c)、Y の次元は (b,c)、Z は X から Y までの距離配列であり、次元は (a 、b)。Z[0,0] は X[0] から Y[0] までの距離です。Z(m,n) は X[m] から Y[n] までの距離です。

例: m 2 の行列と n * 2 の行列の m 2 と n*2の各行間のユークリッド距離を計算します。

#computer the distance between text point x and train point x_train
import numpy as np
X = np.random.random((3,2))
X_train = np.random.random((5,2))
print('X:')
print(X)
print('X_train:')
print(X_train)
 
dist = np.zeros((X.shape[0],X_train.shape[0]))
print('--------------------')
#way 1:use two loops ,使用两层循环
for i in range(X.shape[0]):
    for j in range(X_train.shape[0]):
        dist[i,j] = np.sum((X[i,:]-X_train[j,:])**2)
print('way 1 result:')
print(dist)
 
#way 2:use one loops ,使用一层循环
for i in range(X.shape[0]):
    dist[i,:] = np.sum((X_train-X[i,:])**2,axis=1)
print('--------------------')
print('way 2 result:')
print(dist)
 
#way 3:use no loops,不使用循环
dist = np.reshape(np.sum(X**2,axis=1),(X.shape[0],1))+ np.sum(X_train**2,axis=1)-2*X.dot(X_train.T)
print('--------------------')
print('way 3 result:')
print(dist)

おすすめ

転載: blog.csdn.net/ZauberC/article/details/129325182