Inferensys

Glossary

Cosine Distance

A proximity measure used in LIME for text data that calculates the similarity between two documents based on the angle between their TF-IDF vector representations, ignoring differences in document length.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
PROXIMITY MEASURE

What is Cosine Distance?

A metric used in LIME for text data to quantify the similarity between two documents by measuring the angle between their TF-IDF vector representations, effectively ignoring differences in document length.

Cosine Distance is defined as 1 - cosine similarity, where cosine similarity measures the cosine of the angle between two non-zero vectors in a multi-dimensional space. In the context of Local Interpretable Model-agnostic Explanations (LIME) for text, it quantifies how semantically similar a perturbed document is to the original instance being explained, with a score of 0 indicating identical orientation and 1 indicating complete orthogonality.

This metric is preferred over Euclidean distance for text because it normalizes for document length, ensuring that a short document and a long document with the same word distribution are considered identical. The TF-IDF vector representations of the original and perturbed texts are compared, and the resulting distance is fed into an exponential kernel to assign higher weight to perturbed samples that are closer to the original instance during surrogate model training.

Orientation-Based Similarity

Key Properties of Cosine Distance

Cosine distance measures the angular difference between two vectors, making it ideal for high-dimensional text data where document length should be ignored in favor of directional alignment.

01

Scale Invariance

Cosine distance is magnitude-agnostic, meaning it ignores the absolute length of vectors and focuses solely on their orientation. This property is critical in text analysis, where a short document and a long document discussing the same topic should be considered similar. Two vectors pointing in the same direction will have a cosine distance of 0, regardless of whether one has a magnitude of 10 and the other 1,000. This is achieved by the inherent normalization in the dot product formula: cos(θ) = (A · B) / (||A|| × ||B||).

02

Bounded Range [-1, 1]

The output of the cosine similarity function is strictly confined to the interval [-1, 1], which is then often converted to a distance metric bounded in [0, 2]. A similarity score of 1 indicates perfectly identical orientation (0° angle), 0 indicates orthogonality (90° angle, no correlation), and -1 indicates diametrically opposed vectors (180° angle). This bounded nature makes thresholds highly interpretable: a cosine similarity above 0.8 reliably indicates strong directional alignment, simplifying the definition of 'local' in LIME's neighborhood generation.

03

Sparse Vector Efficiency

Cosine distance is computationally efficient for sparse, high-dimensional data like TF-IDF vectors. The calculation only needs to consider non-zero dimensions shared between two vectors. For a TF-IDF matrix where most terms are absent from any given document, the dot product computation collapses from O(n) to O(min(nnz(A), nnz(B))), where nnz is the number of non-zero entries. This sparsity exploitation is essential for LIME's perturbation sampling, which must rapidly compute thousands of distances between the original text instance and its masked variations.

04

Euclidean vs. Cosine Geometry

In high-dimensional spaces, Euclidean distance suffers from the 'curse of dimensionality,' where contrast between near and far points diminishes. Cosine distance remains robust because it measures angular separation on the unit hypersphere rather than absolute spatial distance. For text data, two documents with identical word distributions but different lengths will have a large Euclidean distance but a cosine distance of zero. This makes cosine the default choice for LIME's exponential kernel weighting, ensuring that perturbed samples are weighted by their semantic orientation relative to the original instance.

05

Kernel Weighting in LIME

LIME uses an exponential kernel on cosine distance to assign weights to perturbed samples: weight = exp(-distance² / kernel_width²). When cosine distance is small (high similarity), the weight approaches 1.0, giving maximum influence to samples that are semantically close to the original instance. As the distance increases toward 1 (orthogonal vectors), the weight decays rapidly, enforcing strict locality. The kernel width hyperparameter controls this decay rate, directly balancing the bias-variance trade-off of the local surrogate model.

06

Non-Negative Feature Spaces

Cosine distance is particularly well-suited for non-negative feature spaces like TF-IDF or bag-of-words representations, where all vector components are ≥ 0. In this constrained positive orthant, the cosine similarity is bounded between 0 and 1, eliminating the possibility of negative correlations. This simplifies interpretation: a similarity of 0 means the documents share no terms, while 1 means identical term distributions. This property ensures that LIME's neighborhood sampling in text domains always produces meaningful, positively correlated distance measurements.

DISTANCE METRIC COMPARISON

Cosine Distance vs. Euclidean Distance

Comparison of proximity measures used in LIME for quantifying similarity between perturbed samples and the original instance, with implications for local neighborhood weighting.

FeatureCosine DistanceEuclidean DistanceManhattan Distance

Fundamental Principle

Measures the cosine of the angle between two vectors; magnitude-invariant

Measures the straight-line length between two points in vector space

Measures the sum of absolute differences along each dimension

Range

[0, 2] for non-negative vectors

[0, ∞)

[0, ∞)

Sensitivity to Magnitude

Primary LIME Use Case

Text data with TF-IDF or bag-of-words representations

Tabular data with normalized numerical features

High-dimensional sparse data with L1 regularization

Invariant to Document Length

Computational Complexity

O(n) dot product with normalization

O(n) with square root

O(n) absolute sum

Behavior with Sparse Vectors

Efficient; only non-zero dimensions contribute to dot product

Sensitive to high dimensionality; distance grows with sparsity

Less sensitive to outliers than Euclidean

Interpretation in LIME Kernel

Directly used as distance input to exponential kernel for text explanations

Requires feature normalization before distance computation

Rarely used; L2 norm preferred for kernel weighting

COSINE DISTANCE EXPLAINED

Frequently Asked Questions

A technical deep dive into the proximity measure used in LIME to compare text documents by the angle between their TF-IDF vectors, ignoring magnitude differences.

Cosine Distance is a measure of dissimilarity between two non-zero vectors that calculates the cosine of the angle between them in a multi-dimensional space. It is defined mathematically as 1 - Cosine Similarity. The Cosine Similarity is computed as the dot product of the vectors divided by the product of their magnitudes: cos(θ) = (A · B) / (||A|| * ||B||). Consequently, Cosine Distance ranges from 0 (for identical vectors pointing in the same direction) to 2 (for vectors pointing in opposite directions). In the context of Local Interpretable Model-agnostic Explanations (LIME) for text, this metric is crucial because it quantifies how semantically similar a perturbed document sample is to the original instance, ignoring the raw count of words (vector magnitude) and focusing purely on the relative distribution of terms.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.