【问题标题】:Vectorize cosine similarity in matlab在matlab中向量化余弦相似度
【发布时间】:2017-09-27 13:37:40
【问题描述】:

我有一个 1000x1000x3 的 3d 矩阵。我想计算某个集合的每个 3d 向量与我可以从 3d 矩阵中垂直提取的每个 3d 向量之间的角度的余弦。然后我应该能够创建一个 1000x1000 矩阵,其向量的索引与原始数据具有最大余弦相似度(即最小角度)。

如何向量化这个计算或至少部分计算?目前我使用嵌套的 for 循环(大量的时间和开销)。

【问题讨论】:

标签: matlab matrix vectorization


【解决方案1】:

我找不到一个在三维空间上取范数的函数,但我认为这也可以。

a = rand(1000,1000,3)-.5; %dataset
na = sqrt(a(:,:,1).^2+a(:,:,2).^2+a(:,:,3).^2); %the norm of each vector
b = [1.2,1,3]; %vector to compare angle against
nb = norm(b); %the norm of the compare vector
b = repmat(b,[1000,1000]);
b = reshape(b,[1000,1000,3]); %1000x1000 copies of b
pl = a.*nb + na.*b; 
mn = a.*nb - na.*b;
npl = sqrt(pl(:,:,1).^2+pl(:,:,2).^2+pl(:,:,3).^2);  
nmn = sqrt(mn(:,:,1).^2+mn(:,:,2).^2+mn(:,:,3).^2);  
theta = 2 * atan(nmn./npl); %angle between [0 and pi] as expected

数学是对这个公式的改编:

theta = 2 * atan(norm(x*norm(y) - norm(x)*y) / norm(x * norm(y) + norm(x) * y))

【讨论】:

    猜你喜欢
    • 2016-03-08
    • 2020-08-12
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多