<jupyter_start><jupyter_text>Feed Forward Neural NetworkIn this notebook, we will perform a multi-layer feed-forward Neural Network using the MNIST dataset.\This this we will perform:- MNIST dataset- DataLoader, Transformation- Multi-layer Neural Network, Activation Functions- Loss and Optimizer- Batch Training - Model Evaluation and Accuracy- GPU support<jupyter_code># import the libraries
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# device config
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# hyperparameters
input_size = 784 # 28x28
hidden_size = 100
n_classes = 10
n_epoch = 8
batch_size = 100
learning_rate = 0.001
# import dataset
train_dataset = torchvision.datasets.MNIST(root='./data', train=True,
                                            transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False,
                                            transform=transforms.ToTensor())
# prepare the data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
examples = iter(train_loader)
samples, labels = examples.next()
print(samples.shape, labels.shape)
# plot a few samples
for i in range(6):
    plt.subplot(2, 3, i+1)
    plt.imshow(samples[i][0], cmap='gray')
plt.show()
# create a Neural Network
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, n_classes):
        super(NeuralNet, self).__init__()
        self.l1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.l2 = nn.Linear(hidden_size, n_classes)
        
    def forward(self, x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        return out

model = NeuralNet(input_size, hidden_size, n_classes)
# set the loss function and the optimizer
criteria = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# training loop
n_total_steps = len(train_loader)
for epoch in range(n_epoch):
    for i, (images, labels) in enumerate(train_loader):
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        
        # forward pass
        outputs = model(images)
        loss = criteria(outputs, labels)
        
        # backward pass
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        if (i+1) % 100 == 0:
            print(f"epoch {epoch+1}/{n_epoch}, step {i+1}/{n_total_steps}, loss = {loss.item():.4f}")
        
# test and evaluation
with torch.no_grad():
    n_correct = 0
    n_samples = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        
        outputs = model(images)
        # value, index
        _, predictions = torch.max(outputs, 1)
        n_samples += labels.shape[0]
        n_correct += (predictions == labels).sum().item()
    
    acc = 100.0 * n_correct / n_samples
    print(f"Accuracy = {acc}")<jupyter_output>Accuracy = 97.37
{'fraction_non_alphanumeric': 0.11083743842364532, 'fraction_numerical': 0.01816502463054187, 'mean_word_length': 3.102272727272727, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '618747', 'license': 'MIT', 'n_tokens_mistral': 1051, 'n_tokens_neox': 995, 'n_words': 254, 'path': 'DL/MultiClassNeuralNetPyTorch_MNIST.ipynb', 'repo_name': 'kaiju-python/DataScience', 'size': '3248'}