<jupyter_start><jupyter_text><jupyter_code>import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as dsets
train_dset = dsets.MNIST(root = './data', train = True,
                         transform = transforms.ToTensor(), download = True)
len(train_dset)
(train_dset[0])
train_dset[0][1]
type(train_dset[0])<jupyter_output><empty_output><jupyter_text>Showing the Dataset<jupyter_code>import matplotlib.pyplot as plt
 %matplotlib inline

import numpy as np
train_dset[0][0].numpy().shape
show_img = train_dset[0][0].numpy().reshape(28,28)
plt.imshow(show_img, cmap = 'gray')<jupyter_output><empty_output><jupyter_text>Load the test dataset<jupyter_code>test_dset = dsets.MNIST(root = './data', train = False,
                        transform = transforms.ToTensor(), download = True)
len(test_dset)<jupyter_output><empty_output><jupyter_text>Now make the dataset iterable<jupyter_code>len(train_dset)
batch_size = 100
n_iters = 3000
num_epochs = n_iters / (len(train_dset) / batch_size)
num_epochs = int(num_epochs)<jupyter_output><empty_output><jupyter_text>Create iterable object  (Data loader)<jupyter_code>train_loader = torch.utils.data.DataLoader(dataset = train_dset,
                                          batch_size = batch_size,
                                          shuffle = True)<jupyter_output><empty_output><jupyter_text>check iterability<jupyter_code>import collections
isinstance(train_loader, collections.Iterable)
 test_loader = torch.utils.data.DataLoader(dataset = test_dset,
                                          batch_size = batch_size,
                                          shuffle = False)<jupyter_output><empty_output><jupyter_text>Now Build the model<jupyter_code>class logistic_regression_model(nn.Module):
  def __init__(self, input_dim, output_dim):
    super(logistic_regression_model, self).__init__()
    self.linear = nn.Linear(input_dim, output_dim)
    
    
  def forward(self, x):
    out = self.linear(x)
    return out
input_dim = 28*28
output_dim = 10

model = logistic_regression_model(input_dim, output_dim)
criterion = nn.CrossEntropyLoss()
learning_rate = 0.001
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)<jupyter_output><empty_output><jupyter_text>Let's Check the parameters ourselves  you have to put this in the form of list to be able to measure its length<jupyter_code>print(len(list(model.parameters())))
print(list(model.parameters())[0].size)

iter = 0
for epoch in range(num_epochs):
  for i, (images, labels) in enumerate(train_loader):
    images = Variable(images.view(-1,28*28))
    
    labels = Variable(labels)
    
    optimizer.zero_grad()
    
    outputs = model(images)
    
    loss = criterion(outputs, labels)
    
    loss.backward()
    
    optimizer.step()
    
    iter = iter + 1
    
    if iter % 500 == 0:
      correct = 0
      total = 0
      
      for images, labels in test_loader:
        images = Variable(images.view(-1,28*28))
        outputs = model(images)
        
        _, predicted = torch.max(outputs.data, 1)
        
        total += labels.size(0)
        
        correct += (predicted == labels).sum()
        
      accuracy  = 100 * correct / total
      
      print('Iteration: {}. Loss: {}. Accuracy: {}' .format(iter, loss.data, accuracy))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10898942420681551, 'fraction_numerical': 0.015569917743830788, 'mean_word_length': 3.3542199488491047, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '644114', 'license': 'MIT', 'n_tokens_mistral': 1152, 'n_tokens_neox': 1096, 'n_words': 214, 'path': 'Logistic_Regression_PyTorch.ipynb', 'repo_name': 'moustafa-7/PyTorch-Course', 'size': '3404'}