nympyで距離を計算する
numpyのインストール
pipで普通に入る
pip install numpy
ベクトルの距離を計算するサンプル
サンプルコード
5つのベクトルデータpoint1~point4とindataの距離を測定して出力する
#sample.py import numpy class Excercise: point0 = [0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0] point1 = [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0] point2 = [0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1] point3 = [0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0] point4 = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0] points = [point0, point1, point2, point3, point4] @classmethod def eg1(cls): indata = [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] distances = {} for i, p in enumerate(cls.points): dis = numpy.linalg.norm( numpy.array(p) - numpy.array(indata) ) distances[i] = dis return distances if __name__ == '__main__': ans = Excercise.eg1() print ans
結果
point4とindataの距離が一番近いことが分かる
$ python sample.py {0: 3.6055512754639891, 1: 3.1622776601683795, 2: 3.4641016151377544, 3: 3.3166247903553998, 4: 3.0}