45. Your First Neural Network in PyTorch
45.3 Train Loop
45.3 Train loop
Training म्हणजे loop: predict → loss → backward → step.
हे का शिकायचं?
Why. Training एक loop आहे: predict → loss → backward → step.
हे काय आहे?
What. एक epoch = training tensors वर एक पूर्ण pass. Tiny toy set वर beginners डझनांनी epochs चालवू शकतात.
कसं करायचं?
How.
Minimal train loop
- zero_grad
- forward
- loss compute
- backward
- optimizer.step
- दर काही epochs loss print
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(0)
X = torch.tensor([
[120., 8., 12.],
[80., 5., 40.],
[200., 12., 8.],
[60., 4., 55.],
[180., 11., 10.],
[90., 6., 35.],
], dtype=torch.float32)
# fictional reorder labels
y = torch.tensor([[1.], [0.], [1.], [0.], [1.], [0.]])
model = nn.Sequential(nn.Linear(3, 8), nn.ReLU(), nn.Linear(8, 1))
criterion = nn.BCEWithLogitsLoss()
opt = optim.Adam(model.parameters(), lr=0.05)
for epoch in range(40):
opt.zero_grad()
logits = model(X)
loss = criterion(logits, y)
loss.backward()
opt.step()
if epoch % 10 == 0:
print(epoch, float(loss))
Output / जे दिसायला हवं. Loss खाली येण्याकडे (प्रत्येक step monotone नसतो). Fictional Mauli-style numbers — production trainer नाही.
Fictional data. फक्त सहा rows — CPU लगेच संपते. Real projects ला जास्त data आणि योग्य train/test split (Chapter 31).
Six rows only so CPU finishes instantly. Real projects need more data and a proper train/test split (Chapter 31).