如何使用两个矩阵计算余弦相似度 [英] How to compute cosine similarity using two matrices

查看:1896
本文介绍了如何使用两个矩阵计算余弦相似度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵,A(尺寸M x N)和B(N x P).实际上,它们是向量的集合-A中的行向量,B中的列向量.我想获得每对ab的余弦相似度得分,其中a是矩阵A的向量(行) b是来自矩阵B的向量(列).

I have two matrices, A (dimensions M x N) and B (N x P). In fact, they are collections of vectors - row vectors in A, column vectors in B. I want to get cosine similarity scores for every pair a and b, where a is a vector (row) from matrix A and b is a vector (column) from matrix B.

我首先将矩阵相乘,得到矩阵C(尺寸M x P).

I have started by multiplying the matrices, which results in matrix C (dimensions M x P).

C = A * B

C = A*B

但是,要获得余弦相似度得分,我需要将每个值C(i,j)除以两个相应向量的范数.您能否建议在Matlab中最简单的方法?

However, to obtain cosine similarity scores, I need to divide each value C(i,j) by the norm of the two corresponding vectors. Could you suggest the easiest way to do this in Matlab?

推荐答案

最简单的解决方案是首先使用沿所需维度的逐元素乘法和求和来计算范数:

The simplest solution would be computing the norms first using element-wise multiplication and summation along the desired dimensions:

normA = sqrt(sum(A .^ 2, 2));
normB = sqrt(sum(B .^ 2, 1));

normAnormB现在分别是列向量和行向量.要将A * B中的相应元素除以normAnormB,请使用 bsxfun 像这样:

normA and normB are now a column vector and row vector, respectively. To divide corresponding elements in A * B by normA and normB, use bsxfun like so:

C = bsxfun(@rdivide, bsxfun(@rdivide, A * B, normA), normB);

这篇关于如何使用两个矩阵计算余弦相似度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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