How to calculate the Cosine similarity between two tensors?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Cosine similarity measures how aligned two vectors are, independent of their magnitude. For tensors, the calculation depends on what you mean by “between two tensors”: you may want a single similarity score for the entire tensors, or one score per row, channel, token, or batch element.
The math is the same in every case. Compute the dot product along the dimension of interest and divide by the product of the corresponding norms.
The Formula
For two non-zero vectors a and b, cosine similarity is:
cos(a, b) = dot(a, b) / (||a|| * ||b||)
The result is:
- '
1if the vectors point in the same direction.' - '
0if they are orthogonal.' - '
-1if they point in opposite directions.'
If your inputs are higher-rank tensors, first decide which axis represents the vector dimension.
Whole-Tensor Similarity
If you want one score for the entire tensors, flatten both tensors into one-dimensional vectors first.
This returns 1.0 because y is a scalar multiple of x, so they point in the same direction after flattening.
Row-Wise or Batch-Wise Similarity
In machine-learning code, you often have tensors shaped like batch_size x embedding_dim. In that case you usually want one cosine similarity value per row, not one score for the entire matrix.
PyTorch provides this directly.
Here dim=1 means each row is treated as a vector and the output contains one similarity score per row.
That “choose the dimension” step is the part people most often get wrong. The formula is easy; selecting the correct axis is the real design decision.
Manual Computation With Stability Protection
When implementing the formula yourself, protect against zero vectors to avoid division by zero.
Using a small eps is common in neural-network code because real data can include all-zero embeddings or masked values.
Interpreting the Result
Cosine similarity ignores scale. That is useful for embeddings, text vectors, and normalized feature spaces where direction matters more than raw magnitude.
It is less useful when vector length itself carries important information. Two tensors can have cosine similarity 1 even if one is ten times larger than the other.
Also remember that if you flatten structured tensors, you are discarding spatial or channel semantics. For an image tensor, a single whole-tensor score may be mathematically valid but conceptually meaningless depending on the task.
Common Pitfalls
A common mistake is comparing tensors of incompatible shapes and assuming broadcasting produced the intended result. Always confirm that the compared dimension matches your conceptual vector dimension.
Another issue is forgetting to handle zero vectors. The raw formula divides by the norm, so all-zero inputs must be handled explicitly or stabilized with an epsilon.
Developers also often flatten tensors too early. If the data is batched, flattening everything together destroys the per-example structure and produces one aggregate score instead of a score per sample.
Finally, do not confuse cosine similarity with Euclidean distance. They answer different questions and often produce different rankings.
Summary
- Cosine similarity is the normalized dot product of two vectors.
- For whole-tensor similarity, flatten both tensors first.
- For batched data, compute along the feature dimension rather than flattening everything.
- Use framework helpers such as
F.cosine_similaritywhen available. - Protect against zero vectors and choose the comparison axis deliberately.

