如何在MATLAB中计算两个频率向量之间的余弦相似度? [英] How to calculate cosine similarity between two frequency vectors in MATLAB?

查看:178
本文介绍了如何在MATLAB中计算两个频率向量之间的余弦相似度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在MATLAB中找到两个频率向量之间的余弦相似度.

示例向量:

  a = [2,3,4,4,6,1]b = [1,3,2,4,6,3] 

如何在MATLAB中测量这些向量之间的余弦相似度?

解决方案

快速查看

每个点代表10个随机生成的向量的计算时间的几何平均值.

I need to find the cosine similarity between two frequency vectors in MATLAB.

Example vectors:

a = [2,3,4,4,6,1]
b = [1,3,2,4,6,3]

How do I measure the cosine similarity between these vectors in MATLAB?

解决方案

Take a quick look at the mathematical definition of Cosine similarity.

From the definition, you just need the dot product of the vectors divided by the product of the Euclidean norms of those vectors.

% MATLAB 2018b
a = [2,3,4,4,6,1]; 
b = [1,3,2,4,6,3];

cosSim = sum(a.*b)/sqrt(sum(a.^2)*sum(b.^2));            % 0.9436

Alternatively, you could use

cosSim = (a(:).'*b(:))/sqrt(sum(a.^2)*sum(b.^2));        % 0.9436

which gives the same result.


After reading this correct answer, to avoid sending you to another castle I've added another approach using MATLAB's built-in linear algebra functions, dot() and norm().

cosSim = dot(a,b)/(norm(a)*norm(b));                     % 0.9436

See also the tag-wiki for .


Performance by Approach:

  1. sum(a.*b)/sqrt(sum(a.^2)*sum(b.^2))
  2. (a(:).'*b(:))/sqrt(sum(a.^2)*sum(b.^2))
  3. dot(a,b)/(norm(a)*norm(b))

Each point represents the geometric mean of the computation times for 10 randomly generated vectors.

这篇关于如何在MATLAB中计算两个频率向量之间的余弦相似度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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