How do I get the average distance between two tensors (element-wise) in pytorch?
- User
How do I get the average distance between two tensors (element-wise) in pytorch?
Assistant
Here is how you can calculate the average element-wise distance between two tensors in PyTorch:
pythonimport torch t1 = torch.tensor([1, 2, 3]) t2 = torch.tensor([3, 2, 1]) diff = torch.abs(t1 - t2) # Element-wise absolute difference dist = torch.mean(diff) # Average distance print(dist) # 2.0The key steps are:
-
Take the absolute difference between the two tensors using
torch.abs(t1 - t2). This gives a tensor containing the element-wise absolute differences. -
To calculate average distance, take the mean of the absolute difference tensor using
torch.mean(diff).
So in just two lines you can calculate the average L1 distance between two tensors in PyTorch. The same logic extends to higher dimensional tensors as well.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.