PyTorch Zeros and Ones
Zeros and ones build tensors already filled with one chosen value. A filled tensor works as a blank canvas with a known shape.
All zeros
Zeros fills every cell with 0. The two numbers give the shape, two rows and three columns.
import torch
print(torch.zeros(2, 3))All ones
Ones fills every cell with 1. One number gives a row of that length.
print(torch.ones(3))One chosen value with full
Full fills every cell with a chosen value. Its first argument is the shape as a tuple.
print(torch.full((2, 2), 7.0))The same shape as another tensor
Zeros_like copies the shape of another tensor. The new tensor holds zeros in that shape.
base = torch.tensor([[1, 2], [3, 4]])
print(torch.zeros_like(base))Example
import torch
board = torch.zeros(4, 4)
board[1, 2] = 1
print(board)Key points
- A filled tensor starts with the same value in every cell
- Use zeros to build a tensor of zeros with a chosen shape
- Use ones to build a tensor of ones with a chosen shape
- Use full to build a tensor filled with any chosen value
- Cell name: brackets with a row number and a column number name one cell
- Use zeros_like to copy the shape and dtype of another tensor
In this example, the program builds a blank board with zeros. The board has four rows and four columns. The next line writes 1 into one cell. The brackets name one cell by its row and column numbers. Counting starts at 0, so row 1 is the second row. The print line shows the board with the single filled cell.
Note
Zeros and ones hold decimals by default, so their cells print as 0. and 1.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
What does torch.zeros(2, 3) build?