6

私は集合知プログラミングの次のコードで遊んでいます。これは、2人の映画評論家の間のクリディアン距離を計算した本の関数です。

この関数は、辞書内のランキングの差を合計しますが、n次元のユークリッド距離には、その合計の平方根も含まれます。

AFAIKは同じ関数を使用して全員をランク付けしているので、平方根であるかどうかは関係ありませんが、特別な理由があるのではないかと思いました。


from math import sqrt 
# Returns a distance-based similarity score for person1 and person2 
def sim_distance(prefs,person1,person2): 
  # Get the list of shared_items 
  si={} 
  for item in prefs[person1]: 
    if item in prefs[person2]: 
       si[item]=1 
  # if they have no ratings in common, return 0 
  if len(si)==0: return 0 
  # Add up the squares of all the differences 
  sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) 
                      for item in prefs[person1] if item in prefs[person2]]) 
  return 1/(1+sum_of_squares) 
4

4 に答える 4

12

平方根が使用されない理由は、計算コストが高いためです。平方根は単調(つまり、順序を保持)であるため、距離の順序だけに関心がある場合は、平方根は不要です(前述のように、計算コストが非常に高くなります)。

于 2009-11-10T17:33:53.730 に答える
3

そのとおりです。定量的に正しい結果を得るには平方根が必要ですが、ソートのために他の人との相対距離だけを気にする場合は、平方根を取る必要はありません。

于 2009-11-10T17:32:46.087 に答える
2

デカルト距離を計算するには、最初に距離の2乗を計算し、次にその平方根を計算する必要があります。しかし、平方根の計算には計算コストがかかります。本当に興味があるのが距離の比較だけである場合は、距離の2乗を比較するのにも同様に機能し、はるかに高速です。

For every two real numbers A and B, where A and B are >= zero, it's always true that A-squared and B-squared have the same relationship as A and B:

  • if A < B, then A-squared < B-squared.
  • if A == B, then A-squared == B-squared.
  • if A > B, then A-squared > B-squared.

Since distances are always >= 0 this relationship means comparing distance-squared gives you the same answer as comparing distance.

于 2009-11-11T15:21:04.867 に答える
1

相互比較のためだけに、平方根は必要ありません。ユークリッド距離の2乗が得られます...これは距離でもあります(数学的には、http://en.wikipedia.org/wiki/Metric_%28mathematics%29を参照してください)。

于 2009-11-10T17:32:39.817 に答える