NameError:使用word2vec计算相似度时未定义名称“点”

2024-06-08 05:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用此函数使用word2vec计算相似性 我用了keras和tensorflow

def cosine_distance (model, word,target_list , num) :
    cosine_dict ={}
    word_list = []
    a = model[word]
    for item in target_list :
        if item != word :
            b = model [item]
            cos_sim = dot(a, b)/(norm(a)*norm(b))
            cosine_dict[item] = cos_sim
    dist_sort=sorted(cosine_dict.items(), key=lambda dist: dist[1],reverse = True) ## in Descedning order 
    for item in dist_sort:
        word_list.append((item[0], item[1]))
    return word_list[0:num]

# only get the unique Maker_Model
Maker_Model = list(df.Maker_Model.unique()) 

# Show the most similar Mercedes-Benz SLK-Class by cosine distance 
cosine_distance (model,'Mercedes-Benz SLK-Class',Maker_Model,5)

并收到此错误:

NameError                                 Traceback (most recent call last)
<ipython-input-29-584408bf6259> in <module>
     17 
     18 # Show the most similar Mercedes-Benz SLK-Class by cosine distance
---> 19 cosine_distance (model,'Mercedes-Benz SLK-Class',Maker_Model,5)

<ipython-input-29-584408bf6259> in cosine_distance(model, word, target_list, num)
      6         if item != word :
      7             b = model [item]
----> 8             cos_sim = dot(a, b)/(norm(a)*norm(b))
      9             cosine_dict[item] = cos_sim
     10     dist_sort=sorted(cosine_dict.items(), key=lambda dist: dist[1],reverse = True) ## in Descedning order

NameError: name 'dot' is not defined

我尝试更新tensorflow和keras,正如网站上的一个答案所建议的那样,但无法修复。我该如何解决这个问题? 请帮帮我


Tags: innormmodeldistsimcositemdict
1条回答
网友
1楼 · 发布于 2024-06-08 05:43:22

基本上,dot不被认为是一种方法

要解决此问题,您需要执行以下操作之一:

  1. 指定您尝试使用的模块的dot方法。像这样:
import numpy as np
...
np.dot(a, b)/(norm(a)*norm(b))
  1. 定义一个自定义的dot方法
def dot(x, y):
   ...
  1. 导入要使用的dot方法

这与第一个选项类似,只是您不需要在dot方法调用前面加上模块名,因为您要导入的是方法,而不是模块

from numpy import dot

这里,我使用numpy作为示例库,但它可以是包含dot方法的任何库:

相关问题 更多 >

    热门问题