资讯专栏INFORMATION COLUMN

[LintCode] Cosine Similarity

Betta / 2874人阅读

Problem

Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the cosine of the angle between them. The cosine of 0° is 1, and it is less than 1 for any other angle.
See wiki: Cosine Similarity
Here is the formula:

Given two vectors A and B with the same size, calculate the cosine similarity.
Return 2.0000 if cosine similarity is invalid (for example A = [0] and B = [0]).

Example

Given A = [1, 2, 3], B = [2, 3 ,4].
Return 0.9926.
Given A = [0], B = [0].
Return 2.0000

Solution
class Solution {
    public double cosineSimilarity(int[] A, int[] B) {
        // write your code here
        if (A.length == 0 || B.length == 0 || A.length != B.length) {
            return 2;
        }
        int aa = 0, bb = 0, ab = 0;
        for (int i = 0; i < A.length; i++) {
            aa += A[i]* A[i];
            bb += B[i]* B[i];
            ab += A[i]* B[i];
        }
        if (aa == 0 || bb == 0) return 2;
        return ab / (Math.sqrt(aa) * Math.sqrt(bb));
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65440.html

相关文章

  • Collaborative Filtering

    Memory basedget user-item matrix and calculate cosine similarity between $u_k, u_a$$$sim^{cos}(u_k,u_a)=frac{u_kcdot u_a}{||u_k|| ||u_a||}$$calculate in python, each row of train_data_matrix represent...

    oogh 评论0 收藏0
  • [LeetCode/LintCode] Sentence Similarity

    Problem Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, great acting skills a...

    dreamtecher 评论0 收藏0
  • 基于 Postgres 实现一个推荐系统

    摘要:机器学习派是后起之秀,而相似度派则是泰山北斗,以致撑起来推荐系统的半壁江山。纯来做推荐基本不靠谱,所以我们来试一下基于和相似度来实现一个推荐系统。 对于内容类网站或者APP,搜索和推荐已经是标配。搜索相对容易,使用Elasticsearch简单配置一下就可以做出一个性能还不错效果也还可以的搜索引擎,然而,推荐系统的话,没有专门的团队实践起来还挺困难的。 网上推荐系统相关的理论非常多,但...

    wean 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<