Cosine similarity degree

Source: Internet
Author: User

Title Description: Give you two vectors of the same size a B, to find their cosine similarity; returns 2.0000 if the cosine is similar to a non-method (e.g. A = [0] B = [0]).

Example: Given a = [1, 2, 3], B = [2, 3, 4]. Returns 0.9926, given a = [0], B = [0]. Returns 2.0000


Python calculates this kind of data science is juchongruoqing, even without any third-party library, can be very concise code to complete the operation.

Calculating the cosine of two vectors is an important method to judge the similarity of two vectors in machine learning. In fact, in addition to the cosine, there are many other methods, they have advantages and disadvantages, the matter will certainly write a special summary of things, and now the main solution lintcode these topics.

The equation for the cosine value is as follows:


According to the formula, write out the code, for convenience, you can write a function to calculate the inner product of the vector, for the main function call:

Class solution: ""    @param the A:an integer array.    @param the B:an integer array.    @return: Cosine similarity.    "" " def cosinesimilarity (self, A, b):        T1 = Self.inner (A, b)        t2 = Self.inner (A, a)        T3 = Self.inner (b, b)        if T2 = = 0 or T3 = = 0:            return 2        return t1/(POW (t2, 0.5) * POW (T3, 0.5))    def inner (self, A, B):        count, i = 0, 0        n = len (A) while        i < n:            count + = (a[i] * b[i])            i + = 1        return count

In fact, Python has a very powerful third-party library of functions: NumPy. To solve the problem of scientific calculation is very convenient, how to use, and later have the opportunity to be specific.

Cosine similarity degree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.