Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.

In [1]:
%load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p torch
Sebastian Raschka 

CPython 3.6.8
IPython 7.2.0

torch 1.0.0
  • Runs on CPU or GPU (if available)

Model Zoo -- Multilayer Perceptron

Imports

In [2]:
import time
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch


if torch.cuda.is_available():
    torch.backends.cudnn.deterministic = True

Settings and Dataset

In [3]:
##########################
### SETTINGS
##########################

# Device
device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")

# Hyperparameters
random_seed = 1
learning_rate = 0.1
num_epochs = 10
batch_size = 64

# Architecture
num_features = 784
num_hidden_1 = 128
num_hidden_2 = 256
num_classes = 10


##########################
### MNIST DATASET
##########################

# Note transforms.ToTensor() scales input images
# to 0-1 range
train_dataset = datasets.MNIST(root='data', 
                               train=True, 
                               transform=transforms.ToTensor(),
                               download=True)

test_dataset = datasets.MNIST(root='data', 
                              train=False, 
                              transform=transforms.ToTensor())


train_loader = DataLoader(dataset=train_dataset, 
                          batch_size=batch_size, 
                          shuffle=True)

test_loader = DataLoader(dataset=test_dataset, 
                         batch_size=batch_size, 
                         shuffle=False)

# Checking the dataset
for images, labels in train_loader:  
    print('Image batch dimensions:', images.shape)
    print('Image label dimensions:', labels.shape)
    break
Image batch dimensions: torch.Size([64, 1, 28, 28])
Image label dimensions: torch.Size([64])
In [4]:
##########################
### MODEL
##########################

class MultilayerPerceptron(torch.nn.Module):

    def __init__(self, num_features, num_classes):
        super(MultilayerPerceptron, self).__init__()
        
        ### 1st hidden layer
        self.linear_1 = torch.nn.Linear(num_features, num_hidden_1)
        # The following two lines are not necessary, 
        # but used here to demonstrate how to access the weights
        # and use a different weight initialization.
        # By default, PyTorch uses Xavier/Glorot initialization, which
        # should usually be preferred.
        self.linear_1.weight.detach().normal_(0.0, 0.1)
        self.linear_1.bias.detach().zero_()
        
        ### 2nd hidden layer
        self.linear_2 = torch.nn.Linear(num_hidden_1, num_hidden_2)
        self.linear_2.weight.detach().normal_(0.0, 0.1)
        self.linear_2.bias.detach().zero_()
        
        ### Output layer
        self.linear_out = torch.nn.Linear(num_hidden_2, num_classes)
        self.linear_out.weight.detach().normal_(0.0, 0.1)
        self.linear_out.bias.detach().zero_()
        
    def forward(self, x):
        out = self.linear_1(x)
        out = F.relu(out)
        out = self.linear_2(out)
        out = F.relu(out)
        logits = self.linear_out(out)
        probas = F.log_softmax(logits, dim=1)
        return logits, probas

    
torch.manual_seed(random_seed)
model = MultilayerPerceptron(num_features=num_features,
                             num_classes=num_classes)

model = model.to(device)

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)  
In [5]:
def compute_accuracy(net, data_loader):
    net.eval()
    correct_pred, num_examples = 0, 0
    with torch.no_grad():
        for features, targets in data_loader:
            features = features.view(-1, 28*28).to(device)
            targets = targets.to(device)
            logits, probas = net(features)
            _, predicted_labels = torch.max(probas, 1)
            num_examples += targets.size(0)
            correct_pred += (predicted_labels == targets).sum()
        return correct_pred.float()/num_examples * 100
    

start_time = time.time()
for epoch in range(num_epochs):
    model.train()
    for batch_idx, (features, targets) in enumerate(train_loader):
        
        features = features.view(-1, 28*28).to(device)
        targets = targets.to(device)
            
        ### FORWARD AND BACK PROP
        logits, probas = model(features)
        cost = F.cross_entropy(logits, targets)
        optimizer.zero_grad()
        
        cost.backward()
        
        ### UPDATE MODEL PARAMETERS
        optimizer.step()
        
        ### LOGGING
        if not batch_idx % 50:
            print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' 
                   %(epoch+1, num_epochs, batch_idx, 
                     len(train_loader), cost))

    with torch.set_grad_enabled(False):
        print('Epoch: %03d/%03d training accuracy: %.2f%%' % (
              epoch+1, num_epochs, 
              compute_accuracy(model, train_loader)))
        
    print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))
    
print('Total Training Time: %.2f min' % ((time.time() - start_time)/60))
Epoch: 001/010 | Batch 000/938 | Cost: 2.4231
Epoch: 001/010 | Batch 050/938 | Cost: 0.7213
Epoch: 001/010 | Batch 100/938 | Cost: 0.3137
Epoch: 001/010 | Batch 150/938 | Cost: 0.4774
Epoch: 001/010 | Batch 200/938 | Cost: 0.3311
Epoch: 001/010 | Batch 250/938 | Cost: 0.3082
Epoch: 001/010 | Batch 300/938 | Cost: 0.3940
Epoch: 001/010 | Batch 350/938 | Cost: 0.2292
Epoch: 001/010 | Batch 400/938 | Cost: 0.0837
Epoch: 001/010 | Batch 450/938 | Cost: 0.2238
Epoch: 001/010 | Batch 500/938 | Cost: 0.2501
Epoch: 001/010 | Batch 550/938 | Cost: 0.1543
Epoch: 001/010 | Batch 600/938 | Cost: 0.2353
Epoch: 001/010 | Batch 650/938 | Cost: 0.4138
Epoch: 001/010 | Batch 700/938 | Cost: 0.2955
Epoch: 001/010 | Batch 750/938 | Cost: 0.3486
Epoch: 001/010 | Batch 800/938 | Cost: 0.1391
Epoch: 001/010 | Batch 850/938 | Cost: 0.0675
Epoch: 001/010 | Batch 900/938 | Cost: 0.2827
Epoch: 001/010 training accuracy: 94.90%
Time elapsed: 0.22 min
Epoch: 002/010 | Batch 000/938 | Cost: 0.3237
Epoch: 002/010 | Batch 050/938 | Cost: 0.2792
Epoch: 002/010 | Batch 100/938 | Cost: 0.0915
Epoch: 002/010 | Batch 150/938 | Cost: 0.2269
Epoch: 002/010 | Batch 200/938 | Cost: 0.2248
Epoch: 002/010 | Batch 250/938 | Cost: 0.1607
Epoch: 002/010 | Batch 300/938 | Cost: 0.0551
Epoch: 002/010 | Batch 350/938 | Cost: 0.2369
Epoch: 002/010 | Batch 400/938 | Cost: 0.0538
Epoch: 002/010 | Batch 450/938 | Cost: 0.0951
Epoch: 002/010 | Batch 500/938 | Cost: 0.2423
Epoch: 002/010 | Batch 550/938 | Cost: 0.2082
Epoch: 002/010 | Batch 600/938 | Cost: 0.1623
Epoch: 002/010 | Batch 650/938 | Cost: 0.1743
Epoch: 002/010 | Batch 700/938 | Cost: 0.1987
Epoch: 002/010 | Batch 750/938 | Cost: 0.0871
Epoch: 002/010 | Batch 800/938 | Cost: 0.1662
Epoch: 002/010 | Batch 850/938 | Cost: 0.1087
Epoch: 002/010 | Batch 900/938 | Cost: 0.1574
Epoch: 002/010 training accuracy: 96.62%
Time elapsed: 0.45 min
Epoch: 003/010 | Batch 000/938 | Cost: 0.1088
Epoch: 003/010 | Batch 050/938 | Cost: 0.0994
Epoch: 003/010 | Batch 100/938 | Cost: 0.0771
Epoch: 003/010 | Batch 150/938 | Cost: 0.1926
Epoch: 003/010 | Batch 200/938 | Cost: 0.1231
Epoch: 003/010 | Batch 250/938 | Cost: 0.2532
Epoch: 003/010 | Batch 300/938 | Cost: 0.0637
Epoch: 003/010 | Batch 350/938 | Cost: 0.1193
Epoch: 003/010 | Batch 400/938 | Cost: 0.0839
Epoch: 003/010 | Batch 450/938 | Cost: 0.0830
Epoch: 003/010 | Batch 500/938 | Cost: 0.0689
Epoch: 003/010 | Batch 550/938 | Cost: 0.0504
Epoch: 003/010 | Batch 600/938 | Cost: 0.1999
Epoch: 003/010 | Batch 650/938 | Cost: 0.1190
Epoch: 003/010 | Batch 700/938 | Cost: 0.2022
Epoch: 003/010 | Batch 750/938 | Cost: 0.0598
Epoch: 003/010 | Batch 800/938 | Cost: 0.0216
Epoch: 003/010 | Batch 850/938 | Cost: 0.0174
Epoch: 003/010 | Batch 900/938 | Cost: 0.0660
Epoch: 003/010 training accuracy: 97.70%
Time elapsed: 0.67 min
Epoch: 004/010 | Batch 000/938 | Cost: 0.0067
Epoch: 004/010 | Batch 050/938 | Cost: 0.0344
Epoch: 004/010 | Batch 100/938 | Cost: 0.1624
Epoch: 004/010 | Batch 150/938 | Cost: 0.0572
Epoch: 004/010 | Batch 200/938 | Cost: 0.0306
Epoch: 004/010 | Batch 250/938 | Cost: 0.1564
Epoch: 004/010 | Batch 300/938 | Cost: 0.2233
Epoch: 004/010 | Batch 350/938 | Cost: 0.0229
Epoch: 004/010 | Batch 400/938 | Cost: 0.1174
Epoch: 004/010 | Batch 450/938 | Cost: 0.1853
Epoch: 004/010 | Batch 500/938 | Cost: 0.1418
Epoch: 004/010 | Batch 550/938 | Cost: 0.1071
Epoch: 004/010 | Batch 600/938 | Cost: 0.0354
Epoch: 004/010 | Batch 650/938 | Cost: 0.0487
Epoch: 004/010 | Batch 700/938 | Cost: 0.1886
Epoch: 004/010 | Batch 750/938 | Cost: 0.1568
Epoch: 004/010 | Batch 800/938 | Cost: 0.0702
Epoch: 004/010 | Batch 850/938 | Cost: 0.0533
Epoch: 004/010 | Batch 900/938 | Cost: 0.1500
Epoch: 004/010 training accuracy: 98.01%
Time elapsed: 0.89 min
Epoch: 005/010 | Batch 000/938 | Cost: 0.0225
Epoch: 005/010 | Batch 050/938 | Cost: 0.0168
Epoch: 005/010 | Batch 100/938 | Cost: 0.1133
Epoch: 005/010 | Batch 150/938 | Cost: 0.0691
Epoch: 005/010 | Batch 200/938 | Cost: 0.0413
Epoch: 005/010 | Batch 250/938 | Cost: 0.0840
Epoch: 005/010 | Batch 300/938 | Cost: 0.0697
Epoch: 005/010 | Batch 350/938 | Cost: 0.0901
Epoch: 005/010 | Batch 400/938 | Cost: 0.0370
Epoch: 005/010 | Batch 450/938 | Cost: 0.0514
Epoch: 005/010 | Batch 500/938 | Cost: 0.1403
Epoch: 005/010 | Batch 550/938 | Cost: 0.1164
Epoch: 005/010 | Batch 600/938 | Cost: 0.0624
Epoch: 005/010 | Batch 650/938 | Cost: 0.0280
Epoch: 005/010 | Batch 700/938 | Cost: 0.0555
Epoch: 005/010 | Batch 750/938 | Cost: 0.0432
Epoch: 005/010 | Batch 800/938 | Cost: 0.0434
Epoch: 005/010 | Batch 850/938 | Cost: 0.1074
Epoch: 005/010 | Batch 900/938 | Cost: 0.0353
Epoch: 005/010 training accuracy: 98.56%
Time elapsed: 1.12 min
Epoch: 006/010 | Batch 000/938 | Cost: 0.1073
Epoch: 006/010 | Batch 050/938 | Cost: 0.0901
Epoch: 006/010 | Batch 100/938 | Cost: 0.0736
Epoch: 006/010 | Batch 150/938 | Cost: 0.0290
Epoch: 006/010 | Batch 200/938 | Cost: 0.0399
Epoch: 006/010 | Batch 250/938 | Cost: 0.0720
Epoch: 006/010 | Batch 300/938 | Cost: 0.0863
Epoch: 006/010 | Batch 350/938 | Cost: 0.0629
Epoch: 006/010 | Batch 400/938 | Cost: 0.1095
Epoch: 006/010 | Batch 450/938 | Cost: 0.0531
Epoch: 006/010 | Batch 500/938 | Cost: 0.0680
Epoch: 006/010 | Batch 550/938 | Cost: 0.1777
Epoch: 006/010 | Batch 600/938 | Cost: 0.0525
Epoch: 006/010 | Batch 650/938 | Cost: 0.0364
Epoch: 006/010 | Batch 700/938 | Cost: 0.0836
Epoch: 006/010 | Batch 750/938 | Cost: 0.1251
Epoch: 006/010 | Batch 800/938 | Cost: 0.0638
Epoch: 006/010 | Batch 850/938 | Cost: 0.0725
Epoch: 006/010 | Batch 900/938 | Cost: 0.1785
Epoch: 006/010 training accuracy: 98.88%
Time elapsed: 1.34 min
Epoch: 007/010 | Batch 000/938 | Cost: 0.0043
Epoch: 007/010 | Batch 050/938 | Cost: 0.0928
Epoch: 007/010 | Batch 100/938 | Cost: 0.0375
Epoch: 007/010 | Batch 150/938 | Cost: 0.1094
Epoch: 007/010 | Batch 200/938 | Cost: 0.0237
Epoch: 007/010 | Batch 250/938 | Cost: 0.0398
Epoch: 007/010 | Batch 300/938 | Cost: 0.0592
Epoch: 007/010 | Batch 350/938 | Cost: 0.0340
Epoch: 007/010 | Batch 400/938 | Cost: 0.0255
Epoch: 007/010 | Batch 450/938 | Cost: 0.0472
Epoch: 007/010 | Batch 500/938 | Cost: 0.0172
Epoch: 007/010 | Batch 550/938 | Cost: 0.0860
Epoch: 007/010 | Batch 600/938 | Cost: 0.1124
Epoch: 007/010 | Batch 650/938 | Cost: 0.0783
Epoch: 007/010 | Batch 700/938 | Cost: 0.0307
Epoch: 007/010 | Batch 750/938 | Cost: 0.0686
Epoch: 007/010 | Batch 800/938 | Cost: 0.0128
Epoch: 007/010 | Batch 850/938 | Cost: 0.0684
Epoch: 007/010 | Batch 900/938 | Cost: 0.0541
Epoch: 007/010 training accuracy: 98.98%
Time elapsed: 1.56 min
Epoch: 008/010 | Batch 000/938 | Cost: 0.0237
Epoch: 008/010 | Batch 050/938 | Cost: 0.0167
Epoch: 008/010 | Batch 100/938 | Cost: 0.0446
Epoch: 008/010 | Batch 150/938 | Cost: 0.0324
Epoch: 008/010 | Batch 200/938 | Cost: 0.0068
Epoch: 008/010 | Batch 250/938 | Cost: 0.0529
Epoch: 008/010 | Batch 300/938 | Cost: 0.0278
Epoch: 008/010 | Batch 350/938 | Cost: 0.0289
Epoch: 008/010 | Batch 400/938 | Cost: 0.0099
Epoch: 008/010 | Batch 450/938 | Cost: 0.0052
Epoch: 008/010 | Batch 500/938 | Cost: 0.0116
Epoch: 008/010 | Batch 550/938 | Cost: 0.0049
Epoch: 008/010 | Batch 600/938 | Cost: 0.0214
Epoch: 008/010 | Batch 650/938 | Cost: 0.0397
Epoch: 008/010 | Batch 700/938 | Cost: 0.0494
Epoch: 008/010 | Batch 750/938 | Cost: 0.0166
Epoch: 008/010 | Batch 800/938 | Cost: 0.0482
Epoch: 008/010 | Batch 850/938 | Cost: 0.0049
Epoch: 008/010 | Batch 900/938 | Cost: 0.0482
Epoch: 008/010 training accuracy: 99.25%
Time elapsed: 1.78 min
Epoch: 009/010 | Batch 000/938 | Cost: 0.0367
Epoch: 009/010 | Batch 050/938 | Cost: 0.0624
Epoch: 009/010 | Batch 100/938 | Cost: 0.0095
Epoch: 009/010 | Batch 150/938 | Cost: 0.0166
Epoch: 009/010 | Batch 200/938 | Cost: 0.0764
Epoch: 009/010 | Batch 250/938 | Cost: 0.0056
Epoch: 009/010 | Batch 300/938 | Cost: 0.0066
Epoch: 009/010 | Batch 350/938 | Cost: 0.0060
Epoch: 009/010 | Batch 400/938 | Cost: 0.0583
Epoch: 009/010 | Batch 450/938 | Cost: 0.0170
Epoch: 009/010 | Batch 500/938 | Cost: 0.0252
Epoch: 009/010 | Batch 550/938 | Cost: 0.0140
Epoch: 009/010 | Batch 600/938 | Cost: 0.0911
Epoch: 009/010 | Batch 650/938 | Cost: 0.0469
Epoch: 009/010 | Batch 700/938 | Cost: 0.0146
Epoch: 009/010 | Batch 750/938 | Cost: 0.0573
Epoch: 009/010 | Batch 800/938 | Cost: 0.0067
Epoch: 009/010 | Batch 850/938 | Cost: 0.1513
Epoch: 009/010 | Batch 900/938 | Cost: 0.0029
Epoch: 009/010 training accuracy: 99.30%
Time elapsed: 2.01 min
Epoch: 010/010 | Batch 000/938 | Cost: 0.0207
Epoch: 010/010 | Batch 050/938 | Cost: 0.0154
Epoch: 010/010 | Batch 100/938 | Cost: 0.0135
Epoch: 010/010 | Batch 150/938 | Cost: 0.0122
Epoch: 010/010 | Batch 200/938 | Cost: 0.0354
Epoch: 010/010 | Batch 250/938 | Cost: 0.0217
Epoch: 010/010 | Batch 300/938 | Cost: 0.0102
Epoch: 010/010 | Batch 350/938 | Cost: 0.0189
Epoch: 010/010 | Batch 400/938 | Cost: 0.0015
Epoch: 010/010 | Batch 450/938 | Cost: 0.0101
Epoch: 010/010 | Batch 500/938 | Cost: 0.0950
Epoch: 010/010 | Batch 550/938 | Cost: 0.0130
Epoch: 010/010 | Batch 600/938 | Cost: 0.0328
Epoch: 010/010 | Batch 650/938 | Cost: 0.0506
Epoch: 010/010 | Batch 700/938 | Cost: 0.0182
Epoch: 010/010 | Batch 750/938 | Cost: 0.0091
Epoch: 010/010 | Batch 800/938 | Cost: 0.0075
Epoch: 010/010 | Batch 850/938 | Cost: 0.0092
Epoch: 010/010 | Batch 900/938 | Cost: 0.0413
Epoch: 010/010 training accuracy: 99.00%
Time elapsed: 2.23 min
Total Training Time: 2.23 min
In [6]:
print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))
Test accuracy: 97.54%
In [7]:
%watermark -iv
numpy       1.15.4
torch       1.0.0