The Difference Between Tensor.size and Tensor.shape in PyTorch – PyTorch Tutorial

By | April 26, 2022

We may find tensor.size and tensor.shape in some pytorch scripts. What the difference between them? In this tutorial, we will introduce it for you.

Difference Between Tensor.size and Tensor.shape

You should know:

tensor.size() = tensor.shape

We will use an example to explain.

For example:

import torch

x = torch.randn(3, 4)
print(x.shape)
print(x.size)
print(x.size())

Run this code, we will get:

torch.Size([3, 4])
<built-in method size of Tensor object at 0x0000024833BDB278>
torch.Size([3, 4])

We can find:

tensor.shape = tensor.size()≠tensor.size

tensor.shape and tensor.size() will ouput a tensor.Size. However, tensor.size is a method.

Then, we can output the value of tensor.shape as follows:

print(x.shape[0], x.shape[1])
print(x.size(0), x.size(1))
print(x.size()[0], x.size()[1])

We will get:

3 4
3 4
3 4

Leave a Reply