How to get a 2D numpy array representing cosine distance between a list of pytorch 1d…
- User
How to get a 2D numpy array representing cosine distance between a list of pytorch 1d tensors
- Assistant
How to get a 2D numpy array representing cosine distance between a list of pytorch 1d tensors
To compute a 2D NumPy array representing the cosine distance between a list of PyTorch 1D tensors, you can follow these steps:
Here's a step-by-step implementation:
import torch
import torch.nn.functional as F
import numpy as np
def cosine_distance_matrix(tensor_list):
"""
Computes the cosine distance matrix for a list of 1D PyTorch tensors.
Args:
tensor_list (List[torch.Tensor]): List of 1D PyTorch tensors. All tensors must have the same shape.
Returns:
np.ndarray: A 2D NumPy array where element (i, j) represents the cosine distance between tensor_list[i] and tensor_list[j].
"""
# Stack the list of tensors into a 2D tensor of shape (N, D)
tensor_stack = torch.stack(tensor_list) # Shape: (N, D)
# Normalize each vector to have unit norm
# F.normalize handles zero vectors by leaving them as is, but you may want to handle them separately
tensor_norm = F.normalize(tensor_stack, p=2, dim=1) # Shape: (N, D)
# Compute cosine similarity matrix by matrix multiplication
# (N, D) @ (D, N) -> (N, N)
cosine_similarity = torch.mm(tensor_norm, tensor_norm.transpose(0, 1)) # Shape: (N, N)
# Convert cosine similarity to cosine distance
cosine_distance = 1 - cosine_similarity # Shape: (N, N)
# Handle numerical issues: Clamp values to [0, 2] as cosine distance ranges from 0 to 2
cosine_distance = torch.clamp(cosine_distance, min=0.0, max=2.0)
# Convert the result to a NumPy array
return cosine_distance.cpu().numpy()
# Example Usage
if __name__ == "__main__":
# Create some example 1D tensors
tensor1 = torch.tensor([1.0, 2.0, 3.0])
tensor2 = torch.tensor([4.0, 5.0, 6.0])
tensor3 = torch.tensor([7.0, 8.0, 9.0])
# List of tensors
tensors = [tensor1, tensor2, tensor3]
# Compute the cosine distance matrix
distance_matrix = cosine_distance_matrix(tensors)
print("Cosine Distance Matrix:")
print(distance_matrix)
Stacking Tensors:
tensor_stack = torch.stack(tensor_list)
This combines the list of 1D tensors into a single 2D tensor of shape (N, D), where N is the number of tensors and D is the dimensionality of each tensor.
Normalizing Vectors:
tensor_norm = F.normalize(tensor_stack, p=2, dim=1)
Each vector is normalized to have a unit L2 norm. This is essential for computing cosine similarity.
Computing Cosine Similarity:
cosine_similarity = torch.mm(tensor_norm, tensor_norm.transpose(0, 1))
The cosine similarity between all pairs of vectors is computed by taking the matrix multiplication of the normalized tensor with its transpose.
Converting to Cosine Distance:
cosine_distance = 1 - cosine_similarity
Cosine distance is simply (1 - \text{cosine similarity}).
Clamping Values:
cosine_distance = torch.clamp(cosine_distance, min=0.0, max=2.0)
Due to floating-point precision, it's possible to get values slightly outside the expected range of [0, 2] for cosine distance. Clamping ensures the distances are within valid bounds.
Conversion to NumPy:
return cosine_distance.cpu().numpy()
The final cosine distance matrix is converted to a NumPy array for ease of use outside of PyTorch.
Cosine Distance Matrix:
[[0.0000000 0.0253682 0.0253682]
[0.0253682 0.0000000 0.0253682]
[0.0253682 0.0253682 0.0000000]]
Note: The exact values may vary slightly due to floating-point precision.
Zero Vectors: If any of the input tensors is a zero vector, normalization will leave it as a zero vector, resulting in NaN values during cosine similarity computation. To handle this, you can add a small epsilon to the denominator during normalization or filter out zero vectors before computation.
Different Dimensions: Ensure all tensors have the same dimensionality. Attempting to stack tensors of different shapes will raise an error.
torch.cdist (PyTorch ≥1.1.0):PyTorch's torch.cdist function can compute pairwise distances efficiently. As of recent versions, it supports the 'cosine' metric directly.
def cosine_distance_matrix_cdist(tensor_list):
tensor_stack = torch.stack(tensor_list) # Shape: (N, D)
distance = torch.cdist(tensor_stack, tensor_stack, p=2) # Replace 'p=2' with 'metric='cosine'' if supported
return distance.cpu().numpy()
Note: Verify the availability of the 'cosine' metric in your PyTorch version, as support may vary.
The provided method efficiently computes the pairwise cosine distances between a list of PyTorch 1D tensors and returns the result as a NumPy array. This approach leverages PyTorch's optimized tensor operations for performance and can be easily integrated into machine learning workflows.
Not yet included in a published release.