How to get a 2D matrix of cosine distance between a list of pytorch 1d tensors
- User
How to get a 2D matrix of cosine distance between a list of pytorch 1d tensors
- Assistant
How to get a 2D matrix of cosine distance between a list of pytorch 1d tensors
To compute a 2D matrix of cosine distances between a list of PyTorch 1D tensors, follow these steps:
torch.stack. This results in a matrix where each row represents one of your original vectors.import torch
# Assume x_list is your list of 1D tensors
x_list = [tensor1, tensor2, tensor3, ..., tensorN]
X = torch.stack(x_list) # Shape: (N, D) where N is number of tensors, D is their dimension
dot_products = X @ X.T # Shape: (N, N)
norms = X.norm(dim=1) # Shape: (N,)
(i, j) is the product of the norms of vectors i and j.norm_products = norms.unsqueeze(1) * norms.unsqueeze(0) # Shape: (N, N)
cosine_similarities = dot_products / norm_products # Shape: (N, N)
cosine_distances = 1 - cosine_similarities # Shape: (N, N)
Complete Code Example:
import torch
# Example list of 1D tensors
x_list = [torch.rand(5) for _ in range(10)] # Replace with your tensors
# Stack tensors into a matrix
X = torch.stack(x_list) # Shape: (N, D)
# Compute the dot products between all pairs
dot_products = X @ X.T # Shape: (N, N)
# Compute the norms of each vector
norms = X.norm(dim=1) # Shape: (N,)
# Compute the outer product of norms to get norm products
norm_products = norms.unsqueeze(1) * norms.unsqueeze(0) # Shape: (N, N)
# Avoid division by zero by adding a small epsilon to norm_products if necessary
epsilon = 1e-8
norm_products = norm_products + epsilon
# Compute the cosine similarities
cosine_similarities = dot_products / norm_products # Shape: (N, N)
# Clamp values to the range [-1, 1] to correct for numerical errors
cosine_similarities = cosine_similarities.clamp(-1.0, 1.0)
# Compute the cosine distances
cosine_distances = 1 - cosine_similarities # Shape: (N, N)
# Now, cosine_distances is your 2D matrix of cosine distances
print(cosine_distances)
Notes:
Numerical Stability: To prevent division by zero or extremely small norms, you can add a small epsilon (like 1e-8) to norm_products.
Clamping Values: After computing cosine similarities, it's a good practice to clamp the values to the valid range of [-1, 1] to account for any numerical inaccuracies due to floating-point arithmetic.
Broadcasting: The use of unsqueeze and element-wise multiplication leverages broadcasting to compute the outer product efficiently.
This method efficiently computes the pairwise cosine distances without explicit loops, utilizing PyTorch's optimized tensor operations for better performance.
Summary: Stack your tensors into a matrix, compute dot products and norms, calculate cosine similarities, and finally subtract from 1 to get the cosine distances arranged in a 2D matrix.
Not yet included in a published release.