Fill A PyTorch Tensor With A Certain Scalar

Fill A PyTorch Tensor with a certain scalar by using the PyTorch fill operation

Type: FREE   By: Sebastian Gutierrez, Instructor Sebastian Gutierrez   Duration: 2:09   Technologies: PyTorch, Python

Page Sections: Video  |  Code  |  Transcript

< > Code:

You must be a Member to view code

Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.

    or   Log In


This video will show you how to fill a PyTorch tensor with a certain scalar by using the PyTorch fill operation.

To get started, we import PyTorch.

import torch

Then we print the PyTorch version we are using.


We are using PyTorch 0.3.1.post2.

Let's now initialize a PyTorch tensor with the shape of 2x4x6 using the torch.Tensor functionality, and we're going to assign that tensor to the Python variable pt_tensor_empty_ex.

pt_tensor_empty_ex = torch.Tensor(2, 4, 6)

Note that because we're passing in number comma number comma and not square bracket end square bracket, we are just allocating the size at this point than having passed any data.

When we print the pt_tensor_empty_ex Python variable, we see that it is filled with all zeros and negative twos.


This is just uninitialized values which are just gibberish.

You can just ignore them.

So again, because we didn't pass in a list here, we just passed in the dimensions, we have an uninitialized tensor that is a torch.FloatTensor of size 2x4x6.

Let's now use the PyTorch fill operation to fill this tensor with a scalar of our choosing.

We're going to fill it with the scalar 12345.

pt_tensor_filled_ex = pt_tensor_empty_ex.fill_(12345)

Note that we're going to use an underscore here after the fill operation to specify and signify that this is an in-place operation.

We're going to assign the tensor that gets returned to pt_tensor_filled_ex Python variable.

When we print the pt_tensor_filled_ex Python variable:


we see that we have our torch.FloatTensor of size 2x4x6, and every single element of this tensor is the scalar or the number 12345.

However, because we used fill underscore to do an in-place operation, that means that we want it to change our initial pt_tensor_empty_ex Python variable to be filled with that scalar.

So when we do a print(pt_tensor_empty_ex):


we see that it is now in fact filled with the scalar that we wanted, the 12345.

Perfect - We were able to fill a PyTorch tensor with a certain scalar of our choosing by using the PyTorch fill underscore operation.

Back to deep learning tutorial lesson list