View file src/colab/constant_input.py - Download

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

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/14zCs-jhEipeKOxRTl7nfPDHzLve6gi-H
"""

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")

torch.manual_seed(14)

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

"""Functions to train and test a model"""

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
        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")

"""In the first model, there are weights W and biases B, and Y = sigmoid(X W + B)"""

# Define model

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

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

    def forward(self, x):
        y1 = sigmoid((x @ self.W1) + self.B1)
        y2 = sigmoid((y1 @ self.W2) + self.B2)
        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.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):
        self.W1.data -= self.lr * self.W1.grad.data
        self.B1.data -= self.lr * self.B1.grad.data
        self.W2.data -= self.lr * self.W2.grad.data
        self.B2.data -= self.lr * self.B2.grad.data
        self.W3.data -= self.lr * self.W3.grad.data
        self.B3.data -= self.lr * self.B3.grad.data

model1 = NeuralNetwork1().to(device)

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!")

"""In the second model, biases are replaced with a constant input with value 1, and Y = sigmoid((1|X) W) where 1|X represents X with 1 inserted at the beginning. The first row of W replaces the biases B.

"""

# Define model

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

def input_with_ones(x):
    n = x.shape[0]  # batch size
    u = torch.ones(n)[:, None].to(device)
    x1 = torch.cat([u, x], axis=-1)  # insert 1 at the beginning of each line of x
    return x1

class NeuralNetwork2(nn.Module):
    def __init__(self):
        super().__init__()
        self.lr = 1
        self.W1 = torch.randn((785, 256), requires_grad=True, device=device)
        self.W2 = torch.randn((257, 256), requires_grad=True, device=device)
        self.W3 = torch.randn((257, 10), requires_grad=True, device=device)

    def forward(self, x):
        y1 = sigmoid(input_with_ones(x) @ self.W1)
        y2 = sigmoid(input_with_ones(y1) @ self.W2)
        y3 = sigmoid(input_with_ones(y2) @ self.W3)
        return y3

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

    def optimize(self):
        self.W1.data -= self.lr * self.W1.grad.data
        self.W2.data -= self.lr * self.W2.grad.data
        self.W3.data -= self.lr * self.W3.grad.data

model2 = NeuralNetwork2().to(device)

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

print("Done!")