Stanford CS231n k-Nearest Neighbor (kNN) exercise2

その買うを、もっとハッピーに。|ハピタス
スポンサーリンク

np.linalg.normとは?

np.linalg.norm(a)で、array(a)のFrobenius normを返す。

import numpy as np
a = np.array(((1.1, 2.0), (3.3, 2.6)))
print(a)
print (np.linalg.norm(a))
[[1.1 2. ]
 [3.3 2.6]]
4.7812132351527685

Frobenius norm(フロベニウスノルム)とは、このサイトによると

matrix norm of an m×n matrix A defined as the square root of the sum of the absolute squares of its elements

となっているので、つまり、

np.sqrt(np.sum(np.square(X[i,:]-self.X_train[j,:])))

と同じということになり、以下のような公式が成立する。

np.linalg.norm(X[i]-self.X_train[j]) = np.sqrt(np.sum((X[i] - self.X_train[j]) ** 2))

np.linalg.normを使った方が計算が早い結果になったので、こっちを使うのがスマートな解法であると言える。

参考サイトhttps://stackoverflow.com/

スポンサーリンク
スポンサーリンク