Creating tensors
- Machine Learning course
- Advanced
- Lesson 9/78
- 5 min
A tensor is created from a list with torch.tensor().
Creating tensors
Most NumPy functions have a PyTorch counterpart:
torch.zeros(2, 3) # zeros
torch.ones(4) # ones
torch.full((2, 2), 7.0) # a constant value
torch.arange(0, 10, 2) # tensor([0, 2, 4, 6, 8])
torch.linspace(0, 1, 5) # 5 evenly spaced values
torch.eye(3) # identity matrixSizes can be given as separate arguments (zeros(2, 3)) or as a tuple (zeros((2, 3))).
Random tensors and the seed
Random tensors are used for weight initialisation and shuffling data. torch.manual_seed makes the results reproducible:
torch.manual_seed(0)
a = torch.rand(3) # uniform on [0, 1)
b = torch.randn(2, 2) # standard normal
torch.manual_seed(0)
print(torch.equal(a, torch.rand(3))) # True: same seed, same numbersThe _like versions copy another tensor's shape and type: torch.zeros_like(x).
Practice Tensor factory
Turn torch.arange(6) into a 2×3 matrix and print it with tolist(). Print the sum of torch.full((2, 2), 5) with item(). Then print with torch.equal that two torch.rand(4) tensors produced with seed 0 are equal.
Starter code
import torch
# buraya yazSample solution
import torch
print(torch.arange(6).reshape(2, 3).tolist())
print(torch.full((2, 2), 5).sum().item())
torch.manual_seed(0)
a = torch.rand(4)
torch.manual_seed(0)
print(torch.equal(a, torch.rand(4)))Expected output
[[0, 1, 2], [3, 4, 5]] 20 True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>torch.arange(1, 8, 3).tolist()</code> give?
- [3, 6]
- [1, 4, 7] Correct answer
- [1, 4]
- [1, 3, 5, 7]
Explanation: The end (8) is excluded; it starts at 1 and steps by three.
2 Produce a zero tensor with the same shape as another tensor.
z = torch.____(x)
z = torch.zeros_like(x)
Explanation: _like functions copy the shape and type.
3 Match the functions.
| Term | Meaning |
|---|---|
torch.rand |
Uniform [0, 1) |
torch.randn |
Standard normal |
torch.eye |
Identity matrix |
torch.manual_seed |
Reproducibility |