how to compute l-inf distance between two tensors with pytorch
- User
how to compute l-inf distance between two tensors with pytorch
Assistant
The L-infinity (L∞) distance between two tensors is the maximum absolute difference between their corresponding elements. Here are several ways to compute it in PyTorch:
Method 1: Using
torch.dist()import torch # Create two example tensors tensor1 = torch.tensor([1.0, 2.0, 3.0]) tensor2 = torch.tensor([1.5, 2.3, 2.8]) # Compute L-inf distance l_inf_distance = torch.dist(tensor1, tensor2, p=float('inf')) print(l_inf_distance) # tensor(0.3000)Method 2: Using
torch.norm()on the difference# Compute the difference and then take the inf-norm diff = tensor1 - tensor2 l_inf_distance = torch.norm(diff, p=float('inf')) print(l_inf_distance) # tensor(0.3000)Method 3: Manual computation
# Compute absolute differences and take the maximum l_inf_distance = torch.max(torch.abs(tensor1 - tensor2)) print(l_inf_distance) # tensor(0.3000)Working with multi-dimensional tensors
All these methods work with tensors of any shape:
# 2D tensors example tensor1 = torch.randn(3, 4) tensor2 = torch.randn(3, 4) # Any of these methods will work l_inf_distance = torch.dist(tensor1, tensor2, p=float('inf')) # or l_inf_distance = torch.norm(tensor1 - tensor2, p=float('inf')) # or l_inf_distance = torch.max(torch.abs(tensor1 - tensor2))The most concise and clear approach is typically using
torch.dist()withp=float('inf'), as it directly expresses the intent of computing the L-infinity distance between two tensors.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.