2017-10-04 5 views
1

だから私は、相続人が望むように動作し、私のループのバージョンでnumpyのとイムトラブル を持つでこのコードをベクトル化しようとしています:ベクタライズnumpyのコード

Bは、私は今、3×3行列

for i in range(b.shape[0]): 
    for j in range(b.shape[0]): 
     Z[i,j] = np.sqrt(np.dot((b[i,:].T - b[j,:].T).T , b[i,:].T - b[j,:].T)) 

ですこのコードをベクトル化しようとしているので、double forループを使用する必要はありません。ここで私は今のところ動作しない得ている何を:あなたがforループどうなるのかを打破する場合

i = 0, j = 0 
np.sqrt(np.dot ((p[i,:].T - p[j:,:].T).T , p[i,:].T - p[j,:].T)) 

は、理想的には、これを実行する必要があります。

np.sqrt(np.dot ((p[0,:].T - p[0,:].T).T , p[0,:].T - p[0,:].T )) 
np.sqrt(np.dot ((p[0,:].T - p[1,:].T).T , p[0,:].T - p[1,:].T )) 
np.sqrt(np.dot ((p[1,:].T - p[0,:].T).T , p[1,:].T - p[0,:].T )) 
np.sqrt(np.dot ((p[1,:].T - p[1,:].T).T , p[1,:].T - p[1,:].T )) 

誰かが親切にいくつかの洞察力を提供できますか?私は組み込みの関数を使用せず、np.dotのようなものを使うことに固執したいと考えています。 Btwこれは、Eucledean距離行列を計算することです。

+0

) ' – Julien

+0

コードが何をしているかを知るのに役立ちます。 –

答えて

3

あなたとしてそれをベクトル化することができる:

b = np.asarray(b)      # in case you have a matrix, convert it to an array 
np.linalg.norm(b - b[:,None], axis=2) 

b - b[:,None]bの行単位の外側の減算を行い、そしてnp.sqrt(np.dot(...,...))np.linalg.normで計算することができます。


:[:I] -b [:J]は `Z [I、J] = np.linalg.norm(B用に簡略化することができるスタータ用

a = np.arange(9).reshape(3,3) 
b = np.matrix(a) 

Z = np.zeros_like(b, dtype=np.float32) 


for i in range(b.shape[0]): 
    for j in range(b.shape[0]): 
     Z[i,j] = np.sqrt(np.dot((b[i,:].T - b[j,:].T).T , b[i,:].T - b[j,:].T)) 

Z 
#array([[ 0.  , 5.19615221, 10.39230442], 
#  [ 5.19615221, 0.  , 5.19615221], 
#  [ 10.39230442, 5.19615221, 0.  ]], dtype=float32) 

b = np.asarray(b) 
np.linalg.norm(b - b[:,None], axis=2) 
#array([[ 0.  , 5.19615242, 10.39230485], 
#  [ 5.19615242, 0.  , 5.19615242], 
#  [ 10.39230485, 5.19615242, 0.  ]])