0
0
PytorchHow-ToBeginner · 3 min read

How to Create Ones Tensor in PyTorch: Syntax and Examples

In PyTorch, you can create a tensor filled with ones using the torch.ones() function. Specify the desired shape as a tuple, for example, torch.ones((2, 3)) creates a 2x3 tensor of ones.
📐

Syntax

The basic syntax to create a tensor of ones in PyTorch is:

  • torch.ones(size, dtype=None, device=None, requires_grad=False)

Where:

  • size: a tuple defining the shape of the tensor (e.g., (2, 3))
  • dtype: (optional) data type of the tensor elements (e.g., torch.float32)
  • device: (optional) device to place the tensor on (e.g., 'cpu' or 'cuda')
  • requires_grad: (optional) if True, tracks operations for gradient computation
python
torch.ones(size, dtype=None, device=None, requires_grad=False)
💻

Example

This example creates a 2x3 tensor filled with ones and prints it. It also shows how to specify the data type and device.

python
import torch

# Create a 2x3 tensor of ones
ones_tensor = torch.ones((2, 3))
print("Tensor of ones:\n", ones_tensor)

# Create a 3x2 tensor of ones with float64 data type
ones_tensor_float64 = torch.ones((3, 2), dtype=torch.float64)
print("\nTensor of ones with dtype float64:\n", ones_tensor_float64)

# Create a tensor on GPU if available
if torch.cuda.is_available():
    ones_tensor_cuda = torch.ones((2, 2), device='cuda')
    print("\nTensor of ones on CUDA device:\n", ones_tensor_cuda)
else:
    print("\nCUDA device not available.")
Output
Tensor of ones: tensor([[1., 1., 1.], [1., 1., 1.]]) Tensor of ones with dtype float64: tensor([[1., 1.], [1., 1.], [1., 1.]], dtype=torch.float64) CUDA device not available.
⚠️

Common Pitfalls

Common mistakes when creating ones tensors include:

  • Passing size as separate arguments instead of a tuple, e.g., torch.ones(2, 3) works but torch.ones(2,3,4) is needed for 3D tensors.
  • Not specifying the device when working with GPUs, which can cause errors when mixing CPU and GPU tensors.
  • Forgetting to set requires_grad=True if you want to compute gradients for the tensor.
python
import torch

# Wrong: passing size as a list instead of tuple (works but not recommended)
# torch.ones([2, 3]) works but tuple is preferred

# Wrong: mixing devices without specifying
try:
    cpu_tensor = torch.ones((2, 2))
    gpu_tensor = torch.ones((2, 2), device='cuda')
    result = cpu_tensor + gpu_tensor  # This will raise an error if devices differ
except Exception as e:
    print(f"Error mixing devices: {e}")

# Right: specify device consistently
if torch.cuda.is_available():
    gpu_tensor1 = torch.ones((2, 2), device='cuda')
    gpu_tensor2 = torch.ones((2, 2), device='cuda')
    result = gpu_tensor1 + gpu_tensor2
    print("Sum on GPU:\n", result)
Output
Error mixing devices: expected device cuda:0 but got device cpu Sum on GPU: tensor([[2., 2.], [2., 2.]], device='cuda:0')
📊

Quick Reference

Summary tips for creating ones tensors in PyTorch:

  • Use torch.ones(size) with size as a tuple for shape.
  • Specify dtype to control data type (default is float32).
  • Use device='cuda' to create tensors on GPU.
  • Set requires_grad=True if gradients are needed for training.

Key Takeaways

Use torch.ones() with a tuple to create a tensor filled with ones of any shape.
Specify dtype and device to control data type and hardware placement.
Set requires_grad=True if you need gradients for training.
Avoid mixing CPU and GPU tensors without proper device specification.
Tuple is the preferred way to define tensor shape for clarity and consistency.