sklearn余弦相似性:: AttributeError:'module'对象没有属性'metrics'

时间:2017-08-18 17:24:56

标签: python scikit-learn cosine-similarity

ur[5][8]=
[[0,3,4,0,0,0,5,0],
[4,5,0,0,0,0,3,0],
[0,4,0,3,0,0,1,4],
[2,0,5,0,0,0,3,0],
[0,0,0,5,0,0,0,4]]

0表示未评级的电影 我想用余弦相似度预测每个用户的未评级电影的评级,并且在计算相似度之后我拿起k个最相似的用户并根据那个预测

但如何使用skearn库或任何其他

中的内置函数计算余弦相似度
code:
similar=[[0] * 5 for i in range(5)]
print similar
for x in range(0,5):
    for y in range(0,5):
        similar[x][y] = sklearn.metrics.pairwise.cosine_similarity(ur[x],ur[y])

error :
runfile('C:/Users/Nitin/cf/first.py', wdir='C:/Users/Nitin/cf')
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Traceback (most recent call last):

  File "<ipython-input-18-e55296403aad>", line 1, in <module>
    runfile('C:/Users/Nitin/cf/first.py', wdir='C:/Users/Nitin/cf')

  File "C:\Users\Nitin\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "C:\Users\Nitin\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/Nitin/cf/first.py", line 23, in <module>
    similar[x][y] = sklearn.metrics.pairwise.cosine_similarity(ur[x],ur[y])

AttributeError: 'module' object has no attribute 'metrics'

cosine_similarity传递什么或如何正确执行此操作

1 个答案:

答案 0 :(得分:1)

您需要导入模块才能使用它。

from sklearn.metrics.pairwise import cosine_similarity

OR

import sklearn
# to use it like 
sklearn.metrics.pairwise.cosine_similarity(ur[x],ur[y])

然后使用它。

from sklearn.metrics.pairwise import cosine_similarity

ur = [[0,3,4,0,0,0,5,0],
[4,5,0,0,0,0,3,0],
[0,4,0,3,0,0,1,4],
[2,0,5,0,0,0,3,0],
[0,0,0,5,0,0,0,4]]

similar=[[0] * 5 for i in range(5)]
print(similar)
for x in range(0,5):
    for y in range(0,5):
        similar[x][y] = cosine_similarity(ur[x],ur[y])

similar

输出:

[[array([[ 1.]]),
  array([[ 0.6]]),
  array([[ 0.37097041]]),
  array([[ 0.80295507]]),
  array([[ 0.]])],