How to create a tensor in PyTorch
Quick answer
Use
torch.tensor() to create a tensor from data, or use factory methods like torch.zeros(), torch.ones(), and torch.randn() to create tensors with specific values or shapes. PyTorch tensors are the core data structure for all computations in torch.PREREQUISITES
Python 3.8+pip install torch>=2.0
Setup
Install PyTorch using pip if you haven't already. Use the official command from PyTorch website. For CPU-only:
pip install torch Step by step
Create tensors from Python lists or arrays using torch.tensor(). Use factory functions like torch.zeros() for zero tensors, torch.ones() for ones, and torch.randn() for random normal tensors.
import torch
# Create a tensor from a Python list
tensor_from_list = torch.tensor([[1, 2], [3, 4]])
print("Tensor from list:")
print(tensor_from_list)
# Create a tensor of zeros with shape (2,3)
zeros_tensor = torch.zeros((2, 3))
print("\nZeros tensor:")
print(zeros_tensor)
# Create a tensor of ones with shape (3,2)
ones_tensor = torch.ones(3, 2)
print("\nOnes tensor:")
print(ones_tensor)
# Create a tensor with random values from normal distribution
rand_tensor = torch.randn(2, 2)
print("\nRandom normal tensor:")
print(rand_tensor) output
Tensor from list:
tensor([[1, 2],
[3, 4]])
Zeros tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
Ones tensor:
tensor([[1., 1.],
[1., 1.],
[1., 1.]])
Random normal tensor:
tensor([[ 0.1234, -0.5678],
[ 1.2345, -0.9876]]) Common variations
You can create tensors on specific devices like GPU using the device parameter. Also, specify data types with dtype. For example, torch.float32 or torch.int64.
import torch
# Create a tensor on GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
tensor_gpu = torch.ones((2, 2), device=device)
print(f"Tensor on device: {device}")
print(tensor_gpu)
# Create an integer tensor
int_tensor = torch.tensor([1, 2, 3], dtype=torch.int64)
print("\nInteger tensor:")
print(int_tensor) output
Tensor on device: cpu
tensor([[1., 1.],
[1., 1.]])
Integer tensor:
tensor([1, 2, 3]) Troubleshooting
If you get an error like ModuleNotFoundError: No module named 'torch', ensure PyTorch is installed correctly with pip install torch. For device errors, verify your CUDA drivers and PyTorch CUDA version compatibility.
Key Takeaways
- Use
torch.tensor()to create tensors from data. - Factory methods like
torch.zeros()andtorch.ones()create tensors with predefined values. - Specify device and data type to control tensor placement and precision.
- Always install PyTorch via pip to avoid import errors.
- Check CUDA compatibility if using GPU tensors.