python给出了ZERODIVISIONERROR,有人能修复这个错误吗

ni65a41a  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(144)
from math import sqrt
S1 = [1,0,0,0,1,0,0,2]
S3 = [0,1,1,2,0,1,2,0]
sum = 0
sums1 = 0
sums3 = 0

for i, j in zip(S1,S3):
   sums1 += i*i
   sums3 += j*j
   sum += i*j

   cosine_similarity = sum / ((sqrt(sums1)) * (sqrt(sums3)))
   print (cosine_similarity)

请问我怎样才能从代码中删除这个错误。我想找到向量的余弦相似性。

izkcnapc

izkcnapc1#

错误是由于最后两行的缩进级别(如 j1-lee 的注解中所述):

# ...
   sum += i*j

# deindentation
cosine_similarity = sum / ((sqrt(sums1)) * (sqrt(sums3)))
print (cosine_similarity)

这里是通过将 * 余弦相似性 * 的定义分解成更小运算的另一实现:

def scalar_product(a, b):
    return sum(a_i*b_i for a_i, b_i in zip(a, b))

def norm(a):
    return sum(a_i**2 for a_i in a )**.5

def cosine_similarity(a, b):
    return scalar_product(a, b) / (norm(a)*norm(b))

S1 = [1,0,0,0,1,0,0,2]
S3 = [0,1,1,2,0,1,2,0]

cs = cosine_similarity(S1, S3)
print(cs)
# 0.0   # orthogonality
cs = cosine_similarity(S1, S1)
print(cs)
# 1.0...# parallelity
ttygqcqt

ttygqcqt2#

我认为您只需要删除代码末尾的额外括号,如下所示:

cosine_similarity = sum / (sqrt(sums1)) * (sqrt(sums3))
print (cosine_similarity)

相关问题