Q:

How do I calculate the cosine similarity of two vectors?

How do I find the cosine similarity between vectors?
I need to find the similarity to measure the relatedness between two lines of text.
For example, I have two sentences like:

system for user interface
user interface machine

… and their respective vectors after tF-idf, followed by normalisation using LSI, for example
[1,0.5] and [0.5,1].
How do I measure the smiliarity between these vectors?

A:

If you want to avoid relying on third-party libraries for such a simple task, here is a plain Java implementation:
public static double cosineSimilarity(double[] vectorA, double[] vectorB) {
    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    for (int i = 0; i < vectorA.length; i++) {
        dotProduct += vectorA[i] * vectorB[i];
        normA += Math.pow(vectorA[i], 2);
        normB += Math.pow(vectorB[i], 2);
    }   
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}

Note that the function assumes that the two vectors have the same length. You may want to explictly check it for safety.

A:

Have a look at: http://en.wikipedia.org/wiki/Cosine_similarity.
If you have vectors A and B.
The similarity is defined as:
cosine(theta) = A . B / ||A|| ||B||

For a vector A = (a1, a2), ||A|| is defined as sqrt(a1^2 + a2^2)

For vector A = (a1, a2) and B = (b1, b2), A . B is defined as a1 b1 + a2 b2;

So for vector A = (a1, a2) and B = (b1, b2), the cosine similarity is given as:

  (a1 b1 + a2 b2) / sqrt(a1^2 + a2^2) sqrt(b1^2 + b2^2)

Example:
A = (1, 0.5), B = (0.5, 1)

cosine(theta) = (0.5 + 0.5) / sqrt(5/4) sqrt(5/4) = 4/5

A:

public class CosineSimilarity extends AbstractSimilarity {

  @Override
  protected double computeSimilarity(Matrix sourceDoc, Matrix targetDoc) {
    double dotProduct = sourceDoc.arrayTimes(targetDoc).norm1();
    double eucledianDist = sourceDoc.normF() * targetDoc.normF();
    return dotProduct / eucledianDist;
  }
}

I did some tf-idf stuff recently for my Information Retrieval unit at University.
I used this Cosine Similarity method which uses Jama: Java Matrix Package.
For the full source code see IR Math with Java : Similarity Measures, really good resource that covers a good few different similarity measurements. 

