Euclidean Distance (similarity)


Bir kümedeki elementlerin benzerliğini ölçen, benzerlik puanı üreten avantajı ve dezavantajı duruma göre değişen algoritmalar bulunmaktadır.

Collaborative Intelligence kitabında Euclidean Distance hesaplaması ile film eleştirmenleri arasındaki benzerlik hesaplanmıştır.

Senaryoda, kişiler çeşitli filmlere puan vermişlerdir ve bu puanlar üzerinden bir kişinin diğer insanlarla arasındaki benzerlik hesaplanmıştır.Birkaç ekleme dışında kodların tamamını kitaptaki gibi aktarıyorum.

from math import sqrt


def sim_euclidan_distance(prefs, person1, person2):
  si={}
  for item in prefs[person1]:
    if item in prefs[person2]:
      si[item]=1

  if len(si)==0: return 0

  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+sqrt(sum_of_squares))

critics={
'Mustafa': {
"The Matrix": 5,
"The Godfather": 5,
"Se7en": 3,
"Babel": 2,
"Troy": 4,
"Legends of the Fall": 1,
"The Thing": 2,
"Leon": 3
},
'Ali': {
"The Matrix": 5,
"The Godfather": 5,
"Se7en": 3,
"Babel": 2,
"Troy": 4,
"Legends of the Fall": 1,
"The Thing": 1,
"Leon": 2
},
'Jodie': {
"The Matrix": 2,
"The Godfather": 3,
"Se7en": 5,
"Babel": 4,
"Troy": 2,
"Legends of the Fall": 5,
"The Thing": 1,
"Leon": 5
},
'John': {
"The Matrix": 4,
"The Godfather": 5,
"Se7en": 4,
"Babel": 1,
"Troy": 4,
"Legends of the Fall": 1,
"The Thing": 5,
"Leon": 2
},
'Neval': {
"The Matrix": 3,
"The Godfather": 5,
"Se7en": 5,
"Babel": 1,
"Troy": 1,
"Legends of the Fall": 5,
"The Thing": 1,
"Leon": 5
},
}

def sim_for_person(prefs, person):
for person2 in prefs:
sim=sim_euclidan_distance(prefs, person, person2);
print person+" & "+person2
print sim

sim_for_person(critics, 'Mustafa')


Bu kodu recommendations.py olarak kaydedip çalıştırırsanız "Mustafa" ile diğer kişiler arasındaki film zevklerinin yakınlık değerini görebilirsiniz. 1 birebir aynı, 0 ise hiçbir şekilde benzemiyor demektir.

Burada filmler üzerinden hesaplama yapılıyor fakat film yerine etiket, müzik veya başka bir birim de kullanabilirdik. Bu yöntemi kullanabilmek için tek gereken birimleri sayısal olarak yazabiliyor olmamız gerekir.

Euclidean hesaplaması aslında hipotenüs hesaplmasıdır. x, y düzlemindeki iki nokta, bir üçgen hipotenüsünün iki ucu olarak kabul edilir ve hipotenüsü yani iki nokta arasındaki mesafeyi ölçen
sqrt(power(nokta1, 2)+power(nokta2, 2)) formül uygulanır.

Euclidean Distance ile ilgili olan bağlantıları aşağıda listeledim:

http://www.cut-the-knot.org/pythagoras/DistanceFormula.shtml

http://en.wikipedia.org/wiki/Euclidean_distance

http://www.econ.upf.edu/~michael/stanford/maeb4.pdf

Comments

Popular posts from this blog

Migrating from PHP to Python

Memory organization and cache management

(DRAFT) Scaling a django project using celery and elasticsearch