In this tutorial, we will use an example to show you how to compare two torch tensors whether have the same shape or not. In order to achieve this aim, we can use torch.equal().
torch.equal()
It is defined as:
torch.equal(input, other)
if two tensors have the same size and elements, it will return True.
We should notice input and other are torch tensors.
How to check two torch tensors have the same size or shape?
Here is an example:
import torch # Create some tensors x = torch.tensor([ [1, 2], [3, 4], ]) y = torch.tensor([ [1, 2], [3, 4], ]) z = torch.tensor([ [1, 2, 3], [4, 5, 6], ]) if torch.equal(torch.as_tensor(x.shape), torch.as_tensor(y.shape)): print("yes") if not torch.equal(torch.as_tensor(x.shape), torch.as_tensor(z.shape)): print("no")
In this example code, we can use if torch.equal(torch.as_tensor(x.shape), torch.as_tensor(y.shape)): to get the result.
Moreover, we also can use:
if x.shape == y.shape: print("yes")
to get the same result.