View file src/colab/quadratic.py - Download

# -*- coding: utf-8 -*-
"""quadratic.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1M1LBk0LL2gDnqcaVGc6_2LkMq7rbz90_

Neural network with quadratic layer
"""

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.transforms import ToTensor
from torch.utils.data import TensorDataset

# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")

transform = transforms.ToTensor()
training_data = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_data = datasets.MNIST(root='./data', train=False, download=True, transform=transform)

batch_size = 50

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

for X, y in test_dataloader:
    print(f"Shape of X [N, C, H, W]: {X.shape}")
    print(f"Shape of y: {y.shape} {y.dtype}")
    break

# Define model

def sigmoid(x): return 1/(1+torch.exp(-x))

lr = 1

class NeuralNetwork1(nn.Module):
    def __init__(self):
        super().__init__()
        self.W1 = torch.randn((784, 32), requires_grad=True, device=device)
        self.B1 = torch.randn(32, requires_grad=True, device=device)
        self.Q2 = torch.randn((32, 32, 32), requires_grad=True, device=device)
        self.W2 = torch.randn((32, 32), requires_grad=True, device=device)
        self.B2 = torch.randn(32, requires_grad=True, device=device)
        self.W3 = torch.randn((32, 10), requires_grad=True, device=device)
        self.B3 = torch.randn(10, requires_grad=True, device=device)

    def forward(self, x):
        # Layer 1 : linear : y1 = sigmoid(x W1 + B1)
        y1 = sigmoid((x @ self.W1) + self.B1)
        # Layer 2 : quadratic : y2 = sigmoid(y1 y1 Q2 + y1 W2 + B2)
        t = torch.tensordot(y1, self.Q2, dims=[[1], [0]])
        t = torch.tensordot(y1, t, dims=[[1], [1]])
        t = t.diagonal(offset=0, dim1=0, dim2=1)
        t = torch.transpose(t, 0, 1)
        y2 = sigmoid(t + (y1 @ self.W2) + self.B2)
        # Layer 3 : linear : y3 = sigmoid(y2 W3 + B3)
        y3 = sigmoid((y2 @ self.W3) + self.B3)
        return y3

    def zero_grad(self):
        if self.W1.grad is not None: self.W1.grad.zero_()
        if self.B1.grad is not None: self.B1.grad.zero_()
        if self.Q2.grad is not None: self.Q2.grad.zero_()
        if self.W2.grad is not None: self.W2.grad.zero_()
        if self.B2.grad is not None: self.B2.grad.zero_()
        if self.W3.grad is not None: self.W3.grad.zero_()
        if self.B3.grad is not None: self.B3.grad.zero_()

    def optimize(self):
        # print(f"B2 grad = {self.B2.grad.data}")
        self.W1.data -= lr * self.W1.grad.data
        self.B1.data -= lr * self.B1.grad.data
        self.Q2.data -= lr * self.Q2.grad.data
        self.W2.data -= lr * self.W2.grad.data
        self.B2.data -= lr * self.B2.grad.data
        self.W3.data -= lr * self.W3.grad.data
        self.B3.data -= lr * self.B3.grad.data
        return

    def print(self):
        print(f"B1 = {self.B1}")
        # print(f"B2 = {self.B2}")
        # print(f"B3 = {self.B3}")

model1 = NeuralNetwork1().to(device)

# Commented out IPython magic to ensure Python compatibility.
# %%script echo Disabled
# for batch, (X, y) in enumerate(test_dataloader):
#     X, y = X.to(device), y.to(device)
#     X = torch.flatten(X, 1, 3)
#     model1.print()
#     print(f"X:{X.shape}")
#     print(f"X = {X}")
#     pred = model1(X)
#     # print(f"pred = {pred}")
#     loss = loss_fn(pred, y)
#     print(f"loss = {loss}")
#     model1.zero_grad()
#     loss.backward()
#     model1.optimize()
#     break
#

loss_fn = torch.nn.CrossEntropyLoss()

def train(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)
        X = torch.flatten(X, 1, 3)  # transform X of shape 50, 1, 28, 28 into 50, 28*28
        # Compute prediction error
        pred = model(X)
        # Compute loss
        # print(f"pred:{pred.shape} y:{y.shape}")
        loss = loss_fn(pred, y)
        # Backpropagation
        model.zero_grad()
        loss.backward()
        # Optimize parameters
        model.optimize()
        if batch % 200 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            X = torch.flatten(X, 1, 3)  # transform X of shape 50, 1, 28, 28 into 50, 28*28
            pred = model(X)
            test_loss += loss_fn(pred, y)
            correct += (pred.argmax(1) == y).type(torch.float32).sum().item()

    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

epochs = 5
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(train_dataloader, model1, loss_fn)
    test(test_dataloader, model1, loss_fn)

print("Done!")