Pacific-Design.com

    
Home Index

1. Machine Learning

2. 0 Cosine Similarity

Machine Learning / 0 Cosine Similarity /

Matlab - Cosine Similarity Computation

x = [1,0,0]
y = [1,0,1]

xy = x(1)*y(1) + x(2)*y(2) + x(3)*y(3) 
x1 = sqrt(x(1)*x(1) + x(2)*x(2) + x(3)*x(3) )
y1 = sqrt(y(1)*y(1) + y(2)*y(2) + y(3)*y(3) )

CosineSimilarity = xy/(x1*y1)

Result:

xy = 1 
x1 = 1 
y1 = 1.4142 
CosineSimilarity = 0.7071

x = [3,2,0,5,0,0,0,2,0,0]
y = [1,0,0,0,0,0,0,1,0,2]

xy = x(1)*y(1) + x(2)*y(2) + x(3)*y(3) + x(4)*y(4) + x(5)*y(5) + x(6)*y(6) + x(7)*y(7) + x(8)*y(8) + x(9)*y(9) + x(10)*y(10) 
x1 = sqrt(x(1)*x(1) + x(2)*x(2) + x(3)*x(3) + x(4)*x(4) + x(5)*x(5) + x(6)*x(6) + x(7)*x(7) + x(8)*x(8) + x(9)*x(9) + x(10)*x(10))
y1 = sqrt(y(1)*y(1) + y(2)*y(2) + y(3)*y(3) + y(4)*y(4) + y(5)*y(5) + y(6)*y(6) + y(7)*y(7) + y(8)*y(8) + y(9)*y(9) + y(10)*y(10))

CosineSimilarity = xy/(x1*y1)

Result:

xy = 5
x1 = 6.4807
y1 = 2.4495
CosineSimilarity = 0.3150