Create A PyTorch Tensor Full Of Zeros

Create a PyTorch Tensor full of zeros so that each element is a zero using the PyTorch Zeros operation

Create a PyTorch Tensor full of zeros so that each element is a zero using the PyTorch Zeros operation

Video Transcript


This video will show how to create a PyTorch tensor where each element is a zero by using the PyTorch zeros operation.


First, we import PyTorch.

import torch


Then we print the PyTorch version we are using.

print(torch.__version__)

We are using PyTorch 0.3.1.post2.


Let’s create the PyTorch tensor full of zeros using the zeros operation.

pt_zeros_tensor_ex_one = torch.zeros(4, 3, 2)


Let’s print the pt_zeros_tensor_ex_one Python variable to see what we have.

print(pt_zeros_tensor_ex_one)

We see that we have four matrices where each matrix has three rows and two columns.

We see that all of the elements are the number zero.

We also see that the PyTorch zeros operation creates a floating tensor by default.


If we want to have a PyTorch tensor full of zeros that are integers, we could cast this floating tensor to be an integer tensor.

pt_zeros_tensor_ex_two = pt_zeros_tensor_ex_one.int()

We use the PyTorch int operation.


Let’s print the pt_zeros_tensor_ex_two Python variable to see what we have.

print(pt_zeros_tensor_ex_two)

We see that we again have four matrices where each matrix has three rows and two columns.

We see that all of the elements are the number zero.

And we also see that this time, we now have a PyTorch IntTensor.


Terrific!


We were able to create a PyTorch tensor where every element is a floating zero or integer zero using the PyTorch zeros operation.

Receive the Data Science Weekly Newsletter every Thursday

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Easy to unsubscribe at any time. Your e-mail address is safe.