# How to Pad a Tensor with Zeros or Ones in Python using PyTorch

In this article, we show how to pad a tensor with zeros or ones in Python using PyTorch.

When a tensor is padded with zeros, all of the elements in the tensor are 0s.

When a tensor is padded with ones, all of the elements in the tensor are 1s.

Numpy has the same functionality capability with numpy arrays.

To pad a tensor with zeros, we use the torch.zeros() function.

The torch.zeros() function takes in a single parameter, which is the size of the tensor.

This is shown in the code below.

So you can see that the torch.zeros() function pads a tensor with all 0s based on the size specified.

We create a variable, a, which is a one-dimensional tensor consisting of 10 values. All these 10 values are 0s with the torch.zeros() function.

We then create a variable, b, which is a two-dimensional tensor consisting of 2 rows, with each row containing 4 values. All of these values are 0s with the torch.zeros() function.

The torch.ones() function works in the same way.

Below is code that shows this.

So you can see that everything is the same as with the zeros() function except now using the ones() function, we have 1s instead of 0s.

And this is how to pad a tensor with zeros or ones in Python using PyTorch.

Related Resources