Practical record · Deep Learning

10 Python Programs
with Code & Output

All ten experiments in one page. Each program has its expected output and separate copy buttons, so you can quickly copy the code or output.

10 ExperimentsNumPy + PyTorchCopy-ready codeSingle HTML file
Note: These are the codes and outputs from your uploaded practical document, arranged by experiment number. The original document also mentions this common setup command: pip install -q torch torchvision pytorch-lightning tensorboard. Notebook-only commands are shown as comments where needed; run those in Jupyter Notebook.
EXPERIMENT 01

Forward Pass in NumPy

↑ Top
import numpy as np

np.random.seed(0)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
W1 = np.random.randn(2, 3)
W2 = np.random.randn(3, 1)

h = np.maximum(0, X @ W1)
y = 1 / (1 + np.exp(-(h @ W2)))
print(y)
[[0.5       ]
 [0.86370131]
 [0.81971456]
 [0.96957717]]
EXPERIMENT 02

Backpropagation in NumPy

↑ Top
import numpy as np

np.random.seed(1)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
W1, b1 = np.random.randn(2, 4), np.zeros(4)
W2, b2 = np.random.randn(4, 1), np.zeros(1)
sig = lambda z: 1 / (1 + np.exp(-z))

for i in range(5001):
    a = sig(X @ W1 + b1)
    p = sig(a @ W2 + b2)
    d2 = (p - y) * p * (1 - p)
    d1 = d2 @ W2.T * a * (1 - a)
    W2 -= 0.5 * a.T @ d2
    b2 -= 0.5 * d2.sum(0)
    W1 -= 0.5 * X.T @ d1
    b1 -= 0.5 * d1.sum(0)
    if i % 1000 == 0:
        print(i, ((p - y) ** 2).mean())
print(p.round(2))
0 0.26492080137612617
1000 0.0092373803402633
2000 0.00230151655445914
3000 0.0012164901913738176
4000 0.0008073584764733662
5000 0.0005975813429730062
[[0.01]
 [0.98]
 [0.97]
 [0.03]]
EXPERIMENT 03

Adam Optimizer from Scratch

↑ Top
import numpy as np

np.random.seed(1)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
P = [np.random.randn(2, 4), np.zeros(4), np.random.randn(4, 1), np.zeros(1)]
m = [np.zeros_like(p) for p in P]
v = [np.zeros_like(p) for p in P]
sig = lambda z: 1 / (1 + np.exp(-z))

for t in range(1, 2001):
    a = sig(X @ P[0] + P[1])
    p = sig(a @ P[2] + P[3])
    d2 = (p - y) * p * (1 - p)
    d1 = d2 @ P[2].T * a * (1 - a)
    G = [X.T @ d1, d1.sum(0), a.T @ d2, d2.sum(0)]
    for k in range(4):
        m[k] = 0.9 * m[k] + 0.1 * G[k]
        v[k] = 0.999 * v[k] + 0.001 * G[k] ** 2
        P[k] -= 0.05 * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
    if t % 500 == 0:
        print(t, ((p - y) ** 2).mean())
print(p.round(2))
500 0.000496713227503653
1000 0.00014525904113733352
1500 6.966527369401401e-05
2000 4.026820201433972e-05
[[0.  ]
 [0.99]
 [0.99]
 [0.01]]
EXPERIMENT 04

PyTorch Gradient Verification

↑ Top
import torch

x = torch.tensor([1., 2., 3.])
w = torch.tensor([0.1, 0.2, 0.3], requires_grad=True)

loss = (w @ x - 2) ** 2
loss.backward()

manual = 2 * (w.detach() @ x - 2) * x
print("PyTorch :", w.grad)
print("Manual :", manual)
print("Match :", torch.allclose(w.grad, manual))
PyTorch : tensor([-1.2000, -2.4000, -3.6000])
Manual : tensor([-1.2000, -2.4000, -3.6000])
Match : True
EXPERIMENT 05

Modular PyTorch Project

↑ Top
import os
os.makedirs('modular', exist_ok=True)

# Create modular/data.py
import torch
from torchvision import datasets, transforms

def loader(train):
    d = datasets.FashionMNIST("data", train=train, download=True, transform=transforms.ToTensor())
    return torch.utils.data.DataLoader(d, batch_size=64, shuffle=train)

# Create modular/model.py
import torch.nn as nn

model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))

# Create modular/train.py
import torch
from data import loader
from model import model

opt = torch.optim.Adam(model.parameters())
loss_fn = torch.nn.CrossEntropyLoss()

for e in range(2):
    tl, tot = loader(True), 0
    for x, y in tl:
        opt.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        opt.step()
        tot += loss.item()
    print("Epoch", e + 1, "Loss", round(tot / len(tl), 4))

with torch.no_grad():
    ok = sum((model(x).argmax(1) == y).sum().item() for x, y in loader(False))
print("Accuracy:", ok / 100, "%")

# Run in Jupyter:
# %run modular/train.py
Epoch 1 Loss 0.548
Epoch 2 Loss 0.4009
Accuracy: 85.38 %
EXPERIMENT 06

CNN for Image Classification

↑ Top
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

tf = transforms.ToTensor()
train = DataLoader(datasets.FashionMNIST("data", True, transform=tf, download=True), 64, shuffle=True)
test = DataLoader(datasets.FashionMNIST("data", False, transform=tf), 1000)

model = nn.Sequential(nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                      nn.Flatten(), nn.Linear(16 * 14 * 14, 10))
opt = torch.optim.Adam(model.parameters())

for e in range(2):
    tot = 0
    for x, y in train:
        opt.zero_grad()
        loss = nn.functional.cross_entropy(model(x), y)
        loss.backward()
        opt.step()
        tot += loss.item()
    print("Epoch", e + 1, "Loss", round(tot / len(train), 4))

with torch.no_grad():
    ok = sum((model(x).argmax(1) == y).sum().item() for x, y in test)
print("Accuracy:", ok / 100, "%")
Epoch 1 Loss 0.4884
Epoch 2 Loss 0.3344
Accuracy: 87.46 %
EXPERIMENT 07

LSTM Sequence Modeling

↑ Top
import torch
import torch.nn as nn

s = torch.sin(torch.linspace(0, 50, 500))
X = torch.stack([s[i:i + 10] for i in range(490)]).unsqueeze(-1)
y = s[10:]

lstm, fc = nn.LSTM(1, 16, batch_first=True), nn.Linear(16, 1)
opt = torch.optim.Adam(list(lstm.parameters()) + list(fc.parameters()), 0.01)

for e in range(101):
    pred = fc(lstm(X)[0][:, -1]).squeeze()
    loss = ((pred - y) ** 2).mean()
    opt.zero_grad()
    loss.backward()
    opt.step()
    if e % 20 == 0:
        print("Epoch", e, "Loss", round(loss.item(), 5))
print("Actual :", y[:3].numpy().round(3))
print("Predicted:", pred[:3].detach().numpy().round(3))
Epoch 0 Loss 0.5996
Epoch 20 Loss 0.05403
Epoch 40 Loss 0.00569
Epoch 60 Loss 0.00112
Epoch 80 Loss 0.00036
Epoch 100 Loss 0.00013
Actual : [0.843 0.892 0.933]
Predicted: [0.837 0.884 0.923]
EXPERIMENT 08

Training Monitoring and Visualization

↑ Top
import torch
from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter("runs")
X = torch.randn(100, 10)
y = X.sum(1, keepdim=True)
model = torch.nn.Linear(10, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=10, gamma=0.5)

for e in range(30):
    loss = ((model(X) - y) ** 2).mean()
    opt.zero_grad()
    loss.backward()
    opt.step()
    sched.step()
    writer.add_scalar("loss", loss, e)
    writer.add_scalar("lr", opt.param_groups[0]["lr"], e)
    if e % 5 == 0:
        print("Epoch", e, "Loss", round(loss.item(), 4), "LR", opt.param_groups[0]["lr"])

# Run these commands in Jupyter:
# %load_ext tensorboard
# %tensorboard --logdir runs
Epoch 0 Loss 9.0317 LR 0.1
Epoch 5 Loss 1.1034 LR 0.1
Epoch 10 Loss 0.1977 LR 0.05
Epoch 15 Loss 0.0928 LR 0.05
Epoch 20 Loss 0.0447 LR 0.025
Epoch 25 Loss 0.0314 LR 0.025
EXPERIMENT 09

PyTorch Lightning Migration

↑ Top
import torch
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

class Lit(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.net = torch.nn.Sequential(torch.nn.Flatten(), torch.nn.Linear(784, 128),
                                       torch.nn.ReLU(), torch.nn.Linear(128, 10))

    def training_step(self, batch, i):
        x, y = batch
        loss = torch.nn.functional.cross_entropy(self.net(x), y)
        self.log("train_loss", loss)
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters())

data = datasets.FashionMNIST("data", download=True, transform=transforms.ToTensor())
trainer = pl.Trainer(max_epochs=2, enable_progress_bar=False)
trainer.fit(Lit(), DataLoader(data, batch_size=64))
print(trainer.callback_metrics)
`Trainer.fit` stopped: `max_epochs=2` reached.
{'train_loss': tensor(0.3194)}
EXPERIMENT 10

Transfer Learning with ResNet

↑ Top
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms, models

tf = transforms.Compose([transforms.Resize(64), transforms.Grayscale(3), transforms.ToTensor()])
train = DataLoader(Subset(datasets.FashionMNIST("data", True, transform=tf, download=True), range(3000)),
                  64, shuffle=True)
test = DataLoader(Subset(datasets.FashionMNIST("data", False, transform=tf), range(1000)), 100)

model = models.resnet18(weights="DEFAULT")
for p in model.parameters():
    p.requires_grad = False
model.fc = nn.Linear(512, 10)
opt = torch.optim.Adam(model.fc.parameters())

for e in range(3):
    tot = 0
    for x, y in train:
        opt.zero_grad()
        loss = nn.functional.cross_entropy(model(x), y)
        loss.backward()
        opt.step()
        tot += loss.item()
    print("Epoch", e + 1, "Loss", round(tot / len(train), 4))

with torch.no_grad():
    ok = sum((model(x).argmax(1) == y).sum().item() for x, y in test)
print("Accuracy:", ok / 10, "%")
Epoch 1 Loss 2.0636
Epoch 2 Loss 1.5481
Epoch 3 Loss 1.278
Accuracy: 68.3 %