Summary - PyTorch
- Machine Learning course
- Advanced
- Lesson 12/78
- 6 min
In this group you learned tensor creation, properties, and GPU support.
Summary: PyTorch
In this group:
- PyTorch: tensors, autograd and
nn; code runs line by line. - Tensor: an n-dimensional array; back to Python with
item()andtolist(). from_numpyshares memory,torch.tensorcopies.- Creation:
zeros,ones,arange,rand,randn;manual_seed. shape,dtype(input float32, labels int64),device;.to(device)and.cpu().
Practice Prepare data as tensors
Convert the NumPy arrays X_np (float64) and y_np into tensors: X should be float32 and y int64. Print both dtype values on one line, then X.shape.
Starter code
import numpy as np
import torch
X_np = np.random.default_rng(0).normal(size=(8, 3))
y_np = np.array([0, 1, 1, 0, 2, 2, 1, 0])
# buraya yazSample solution
import numpy as np
import torch
X_np = np.random.default_rng(0).normal(size=(8, 3))
y_np = np.array([0, 1, 1, 0, 2, 2, 1, 0])
X = torch.from_numpy(X_np).float()
y = torch.from_numpy(y_np).long()
print(X.dtype, y.dtype)
print(X.shape)Expected output
torch.float32 torch.int64 torch.Size([8, 3])
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should be done to float64 features from NumPy before giving them to the model?
- Nothing
- Convert to a list
- Convert to float32 with .float() Correct answer
- Convert to integers with .long()
Explanation: Model weights are float32; mismatched types raise an error.
2 Make the labels int64.
y = torch.from_numpy(y_np).____()
y = torch.from_numpy(y_np).long()
Explanation: The cross-entropy loss needs class labels as long (int64).
3 Match the tools.
| Term | Meaning |
|---|---|
torch.from_numpy |
Shared conversion |
torch.manual_seed |
Seed |
.float() |
float32 |
.cpu().numpy() |
Back to NumPy |