This video will show you how to calculate the number of elements in a PyTorch tensor by using the PyTorch numel operation.
First, we import PyTorch.
Then we print the PyTorch version we are using.
We are using PyTorch 0.4.0.
Let’s now create a PyTorch identity matrix of size 3x3.
pt_3_by_3_eye_ex = torch.eye(3)
So we use the PyTorch eye operation and we pass the 3 here.
So this n will be used for both the columns, so we have three columns, and for the rows, so three rows.
We assign the tensor that is created by using this operation to the Python variable pt_3_by_3_eye_ex.
Let’s print the pt_3_by_3_eye_ex Python variable to see what we have.
We can see that it’s a two-dimensional PyTorch floating tensor.
So we have three rows, three columns, and because it’s 3x3, we can see that it’s one, two, three, four, five, six, seven, eight, nine elements.
To check this, using a calculation, we’re going to use the PyTorch numel operation.
So we pass in our tensor, pt_3_by_3_eye_ex, and we use the PyTorch numel operation, so .numel:
and it returns the number 9, which is what we expect because it is a 3x3 matrix.
Perfect - We were able to calculate the number of elements in a PyTorch tensor by using the PyTorch numel operation.