Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Created December 20, 2012 11:52
Show Gist options
  • Save petitviolet/4344871 to your computer and use it in GitHub Desktop.
Save petitviolet/4344871 to your computer and use it in GitHub Desktop.
2つの疎行列(1*N)のユークリッド距離を求める関数
# -*- encoding: utf-8 -*-
import scipy.spatial.distance as dis
import scipy.sparse as sp
import numpy as np, scipy.io as io
import math
def sparse_distance(v1, v2):
"""1*Nのベクトル間のユークリッド距離を求める
args:
v1, v2 : 1 * N の(疎)行列
"""
if not sp.issparse(v1) or not sp.issparse(v2):
if v1.size != v2.size:
raise ValueError
return dis.euclidean(v1, v2)
indexes1 = v1.rows.item()[:]
indexes2 = v2.rows.item()[:]
if len(indexes1) != len(indexes2):
raise ValueError
indexes = indexes1 + indexes2 # 2つのベクトルの疎でない所のindex
euc_dis = 0.0
for index in indexes:
_dis = v1[0, index] - v2[0, index]
euc_dis += _dis ** 2
return math.sqrt(euc_dis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment