如何在Python中为具有不同形状的两个数组计算余弦距离? [英] How is the cosine distance calculated for two arrays with different shapes in Python?

查看:42
本文介绍了如何在Python中为具有不同形状的两个数组计算余弦距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

array1 = numpy.array([ 7.26741212e-01, -9.80825232e-17])
array2 = numpy.array([-3.82390578e-01, -1.48157964e-17],
       [-3.82390578e-01,  7.87310307e-01],
       [ 7.26741212e-01, -9.80825232e-17],
       [ 7.26741212e-01, -9.80825232e-17],
       [-3.82390578e-01, -2.06286905e-01],
       [ 7.26741212e-01, -9.80825232e-17],
       [-2.16887107e-01,  6.84509305e-17],
       [-3.82390578e-01, -5.81023402e-01],
       [-2.16887107e-01,  6.84509305e-17],
       [-2.16887107e-01,  6.84509305e-17])

如何获取列表中array2到array1的每一行的余弦距离?

How do I get the cosine distance of each row in array2 to array1 in a list?

推荐答案

import numpy as np


def cosine_similarity(x, y):
    return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))
    
a = np.array([7.26741212e-01, -9.80825232e-17])
b = np.array(([-3.82390578e-01, -1.48157964e-17],
                     [-3.82390578e-01,  7.87310307e-01],
                     [7.26741212e-01, -9.80825232e-17],
                     [7.26741212e-01, -9.80825232e-17],
                     [-3.82390578e-01, -2.06286905e-01],
                     [7.26741212e-01, -9.80825232e-17],
                     [-2.16887107e-01,  6.84509305e-17],
                     [-3.82390578e-01, -5.81023402e-01],
                     [-2.16887107e-01,  6.84509305e-17],
                     [-2.16887107e-01,  6.84509305e-17]))


output = [cosine_similarity(a, y) for y in b]

这篇关于如何在Python中为具有不同形状的两个数组计算余弦距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆