How to Create Tensor in PyTorch: Syntax and Examples
In PyTorch, you create a tensor using the
torch.tensor() function by passing a list or array of values. You can also create tensors filled with zeros, ones, or random numbers using functions like torch.zeros(), torch.ones(), and torch.rand().Syntax
The basic syntax to create a tensor in PyTorch is torch.tensor(data, dtype=None, device=None). Here, data is a list, tuple, or NumPy array of values. The optional dtype sets the data type (like float or int), and device specifies if the tensor is on CPU or GPU.
Other common tensor creation functions include:
torch.zeros(size): creates a tensor filled with zeros.torch.ones(size): creates a tensor filled with ones.torch.rand(size): creates a tensor with random values between 0 and 1.
python
import torch # Create tensor from list tensor = torch.tensor([1, 2, 3], dtype=torch.float32) # Create tensor of zeros zeros = torch.zeros((2, 3)) # Create tensor of ones ones = torch.ones((2, 3)) # Create tensor with random values random = torch.rand((2, 3))
Example
This example shows how to create different types of tensors and print their values and shapes.
python
import torch # Tensor from list tensor = torch.tensor([4, 5, 6], dtype=torch.float32) print('Tensor:', tensor) print('Shape:', tensor.shape) # Tensor of zeros zeros = torch.zeros((2, 2)) print('Zeros tensor:\n', zeros) # Tensor of ones ones = torch.ones((3, 1)) print('Ones tensor:\n', ones) # Tensor with random values random = torch.rand((2, 3)) print('Random tensor:\n', random)
Output
Tensor: tensor([4., 5., 6.])
Shape: torch.Size([3])
Zeros tensor:
tensor([[0., 0.],
[0., 0.]])
Ones tensor:
tensor([[1.],
[1.],
[1.]])
Random tensor:
tensor([[0.1234, 0.5678, 0.9101],
[0.2345, 0.6789, 0.3456]])
Common Pitfalls
Common mistakes when creating tensors include:
- Passing a Python list without specifying
dtypecan lead to unexpected types. - Trying to create a tensor from nested lists with inconsistent lengths causes errors.
- Forgetting to move tensors to GPU with
to(device)if needed.
Example of wrong and right ways:
python
import torch # Wrong: inconsistent nested list lengths try: bad_tensor = torch.tensor([[1, 2], [3]]) except Exception as e: print('Error:', e) # Right: consistent nested list lengths good_tensor = torch.tensor([[1, 2], [3, 4]]) print('Good tensor:', good_tensor)
Output
Error: expected sequence of length 2 at dim 1 (got 1)
Good tensor: tensor([[1, 2],
[3, 4]])
Quick Reference
| Function | Description | Example |
|---|---|---|
| torch.tensor(data) | Create tensor from data | torch.tensor([1, 2, 3]) |
| torch.zeros(size) | Tensor filled with zeros | torch.zeros((2, 2)) |
| torch.ones(size) | Tensor filled with ones | torch.ones((3, 1)) |
| torch.rand(size) | Tensor with random values | torch.rand((2, 3)) |
Key Takeaways
Use torch.tensor() to create tensors from Python lists or arrays.
Specify dtype to control the data type of the tensor.
Use torch.zeros(), torch.ones(), and torch.rand() for common tensor initializations.
Ensure nested lists have consistent lengths to avoid errors.
Move tensors to GPU with .to(device) if needed for faster computation.