How to Create a Tensor of Ones in PyTorch with torch.ones
A tensor of ones is handy as a starting value, such as weights that all begin equal, or a mask that keeps everything. You give PyTorch the shape, and it makes the tensor. This guide uses torch.ones for a row, a table and a table of whole numbers in PyTorch 2.15.0.
Syntax
torch.ones(*size, dtype=None, device=None)
| Part | What it means |
|---|---|
*size | The shape: one whole number per dimension, such as 3, 2 for three rows of two. A tuple or list, such as [3, 2], works too |
dtype | Optional, given by name. The data type, such as torch.int64 for whole numbers. Left out, it's PyTorch's default, torch.float32 |
device | Optional, given by name. Where to make the tensor, such as the GPU. Left out, it's the CPU |
PyTorch's reference describes it as returning "a tensor filled with the scalar value 1, with the shape defined by the variable argument size."
The Example
A script makes three tensors of ones: a row of four, a table of three rows and two columns, and the same table as whole numbers.
Prerequisites
- A uv project with PyTorch and NumPy.
uv add torch numpyadds both; without NumPy, PyTorch 2.15.0 prints a warning each time it starts. This guide uses PyTorch 2.15.0 and NumPy 2.5.5 on Python 3.15.2, with uv 0.13.10, on an Apple M1 Pro.
Step 1: Write the Script
import torch
print(torch.ones(4))
print(torch.ones(3, 2))
print(torch.ones(3, 2, dtype=torch.int64))

One number makes a single row; two numbers make a table, rows first. The last line asks for whole numbers with dtype=torch.int64.
Step 2: Run It
uv run python ones.py
tensor([1., 1., 1., 1.])
tensor([[1., 1.],
[1., 1.],
[1., 1.]])
tensor([[1, 1],
[1, 1],
[1, 1]])

The first two tensors print 1. with a dot: they're decimals, torch.float32, the default. torch.ones(3, 2) has three rows of two. The third tensor prints 1 without a dot, because dtype=torch.int64 made whole numbers. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting whole numbers | torch.ones(3, 2) makes decimals, printed 1. | Add dtype=torch.int64 |
Reading torch.ones(3, 2) as three columns | It's three rows of two columns: the first number is the rows | Give the rows first |
FAQ
How do I fill a tensor with another number?
Use torch.full(size, value): torch.full((2, 3), 7) printed a two-by-three table of 7. The size goes in brackets of its own, as a tuple or a list, because the value comes after it.
Can I give the size as a list?
Yes: torch.ones([3, 2]).shape printed torch.Size([3, 2]), the same as torch.ones(3, 2).
Conclusion
torch.ones(4) made a row of four ones, torch.ones(3, 2) a table of three rows and two columns, both as torch.float32 decimals, and dtype=torch.int64 made the same table as whole numbers.
Additional Resources
- torch.ones — PyTorch's reference for the function.
- torch.full — a tensor filled with any value.
- Tensors tutorial — PyTorch's introduction to tensors.
