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