我正在嘗試使用scipy.spatial.distance
來實現euclidean distance
,這是我以前正常編寫的。歐幾里德距離錯誤:不受支持的操作數類型
from math import sqrt
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane': 4.5, 'You, Me and Dupree': 1.0, 'Superman Returns': 4.0}}
def sim_distance(preference, person1, person2):
si = {}
for item in preference[person1]:
if item in preference[person2]:
si[item] = 1
if len(si) == 0: return 0
sum_of_scores = sum([pow(preference[person1][item] - preference[person2][item], 2)
for item in preference[person1] if item in preference[person2]])
return 1/(1 + sum_of_scores)
a = sim_distance(critics, 'Lisa Rose','Mick LaSalle')
print(a) #0.333
當前實現完美的作品,但使用scipy
模塊嘗試時,我不能夠理解應該爲此提供什麼類型的輸入。這是我的嘗試。
from scipy.spatial.distance import euclidean
a = euclidean(critics['Lisa Rose'], critics['Mick LaSalle'])
print(a)
回溯
Traceback (most recent call last):
File "C:/Users/Ajay/PycharmProjects/SO/new.py", line 22, in <module>
a = euclidean(critics['Lisa Rose'], critics['Mick LaSalle'])
File "C:\Python33\lib\site-packages\scipy\spatial\distance.py", line 224, in euclidean
dist = norm(u - v)
TypeError: unsupported operand type(s) for -: 'dict' and 'dict'
當提到的euclidean
實施,似乎輸入應給出tuples
,但我無法理解如何處理這一點。
def euclidean(u, v):
"""
Computes the Euclidean distance between two 1-D arrays.
The Euclidean distance between 1-D arrays `u` and `v`, is defined as
.. math::
{||u-v||}_2
Parameters
----------
u : (N,) array_like
Input array.
v : (N,) array_like
Input array.
Returns
-------
euclidean : double
The Euclidean distance between vectors `u` and `v`.
"""
u = _validate_vector(u)
v = _validate_vector(v)
dist = norm(u - v)
return dist
請賜教。
什麼是最好的情況下,找到距離呢? – ajkumar25
你是什麼意思?這取決於你如何定義距離。 – ysakamoto
@sakamoto謝謝。 – ajkumar25