<jupyter_start><jupyter_text>Structure-1 (Same as given Notebook)<jupyter_code>class Net(nn.Module): # image siE in mnist is 1x28x28
                                           


    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1) 
        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
        self.conv4 = nn.Conv2d(128, 256, 3, padding=1)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.conv5 = nn.Conv2d(256, 512, 3)
        self.conv6 = nn.Conv2d(512, 1024, 3)
        self.conv7 = nn.Conv2d(1024, 10, 3)

    def forward(self, x):
        x = self.pool1(F.relu(self.conv2(F.relu(self.conv1(x))))) # 1 convolutional block
        x = self.pool2(F.relu(self.conv4(F.relu(self.conv3(x)))))
        x = F.relu(self.conv6(F.relu(self.conv5(x))))
        x = F.relu(self.conv7(x))
        x = x.view(-1, 10)
        return F.log_softmax(x)
# Checking that cuda is available or not
torch.cuda.is_available()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = Net().to(device)
summary(model, input_size=(1, 28, 28))
torch.manual_seed(1)
batch_size = 128

kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                    transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)

def train(model, device, train_loader, optimizer, epoch):
    model.train()
    pbar = tqdm(train_loader)
    for batch_idx, (data, target) in enumerate(pbar):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx}')


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)


for epoch in range(1, 2):
    train(model, device, train_loader, optimizer, epoch)
    test(model, device, test_loader)<jupyter_output><empty_output><jupyter_text>Structure-2 (Except structure all are same)<jupyter_code>class Net(nn.Module): # image siE in mnist is 1x28x28
                                           
## Without max pooling, use kernels with different shapes and randomly increase as well as decreasing the filter size.

    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1)    #  32x28x28.
        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)   #  64x28x28.
        #self.pool1 = nn.MaxPool2d(2, 2)               #  Cancelling the maxpool part.
        self.conv3 = nn.Conv2d(64, 128, 3, padding=1)  #  128x28x28.
        self.conv4 = nn.Conv2d(128, 256, 3, padding=1) #  256x28x28.
        #self.pool2 = nn.MaxPool2d(2, 2)
        self.conv5 = nn.Conv2d(256, 512, 3)            #  512x26x26
        self.conv6 = nn.Conv2d(512, 1024, 5)           #  1024x22x22
        self.conv7 = nn.Conv2d(1024, 2048, 7)          #  2048x16x16
        self.conv8 = nn.Conv2d(2048, 512, 3)           #  512x14x14
        self.conv9 = nn.Conv2d(512, 1024, 7)           #  1024x8x8
        self.conv10 = nn.Conv2d(1024, 2048, 5)         #  2048x4x4
        self.conv11 = nn.Conv2d(2048, 1024, 3)         #  1024x2x2
        self.conv12 = nn.Conv2d(1024, 10, 2)           #  10x1x1

    def forward(self, x):
        x = F.relu(self.conv2(F.relu(self.conv1(x))))   # 1 convolutional block, self.pool1(
        x = F.relu(self.conv4(F.relu(self.conv3(x))))   #self.pool2(
        x = F.relu(self.conv6(F.relu(self.conv5(x))))
        x = F.relu(self.conv8(F.relu(self.conv7(x))))
        x = F.relu(self.conv10(F.relu(self.conv9(x))))
        x = F.relu(self.conv12(F.relu(self.conv11(x))))
        
        x = x.view(-1, 10)
        return F.log_softmax(x)
# Checking that cuda is available or not
torch.cuda.is_available()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = Net().to(device)
summary(model, input_size=(1, 28, 28))
torch.manual_seed(1)
batch_size = 128

kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                    transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)

def train(model, device, train_loader, optimizer, epoch):
    model.train()
    pbar = tqdm(train_loader)
    for batch_idx, (data, target) in enumerate(pbar):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx}')


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)   ## It is taking more and moere time to train. I think because of the
                                                                   ## filters dimension as i chnaged them randomly and lot of number of channels such as 2048, 1024.
                                                                   ## I decrease them and also increase them in a random manner.
                                                                   ## The next reason may be i did not use the maxpooling and use the kernels randomly 
                                                                   ## Such as 3x3, 5x5, 7x7. As kernels are high in dimension with high number of filters,
                                                                   ## this will be the reason for taking so much time to train.

''' it is taking --> "2h 1m 7s" to train and give the prediction. The accuracy is also
decrease.'''


for epoch in range(1, 2):
    train(model, device, train_loader, optimizer, epoch)
    test(model, device, test_loader)<jupyter_output><empty_output><jupyter_text>Structure-3<jupyter_code>class Net(nn.Module): # image siE in mnist is 1x28x28
                                           
# More maxpooling and more padding.

    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1)               ## 32x28x28
        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)              ## 64x28x28
        self.pool1 = nn.MaxPool2d(2, 2)                           ## 64x14x14
        self.conv3 = nn.Conv2d(64, 128, 3, padding=1)             ## 128x14x14
        self.conv4 = nn.Conv2d(128, 256, 3, padding=1)            ## 256x14x14
        self.pool2 = nn.MaxPool2d(4, 2)                           ## 256x6x6
        self.conv5 = nn.Conv2d(256, 512, 3, padding=1)            ## 512x6x6
        self.conv6 = nn.Conv2d(512, 1024, 3, padding = 1)         ## 1024x6x6  
        
        #self.pool3 = nn.MaxPool2d(2, 2)                           ## 1024x5x5
        
        self.conv7 = nn.Conv2d(1024, 512, 3, padding = 1)         ## 512x6x6
        self.pool3 =  nn.MaxPool2d(2, 1)                          ## 512x5x5
        self.conv8 = nn.Conv2d(512, 1024, 3)                      ## 1024x3x3
        self.conv9 = nn.Conv2d(1024, 10, 3)                       ## 10x1x1



    def forward(self, x):
        x = self.pool1(F.relu(self.conv2(F.relu(self.conv1(x))))) # 1 convolutional block
        x = self.pool2(F.relu(self.conv4(F.relu(self.conv3(x)))))
        x = F.relu(self.conv6(F.relu(self.conv5(x))))
        x = self.pool3(F.relu(self.conv7(x)))
        x = F.relu(self.conv9(F.relu(self.conv8(x))))
        x = x.view(-1, 10)
        return F.log_softmax(x)
# Checking that cuda is available or not
torch.cuda.is_available()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = Net().to(device)
summary(model, input_size=(1, 28, 28))
torch.manual_seed(1)
batch_size = 128

kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                    transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)

def train(model, device, train_loader, optimizer, epoch):
    model.train()
    pbar = tqdm(train_loader)
    for batch_idx, (data, target) in enumerate(pbar):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx}')


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)   


for epoch in range(1, 2):
    train(model, device, train_loader, optimizer, epoch)
    test(model, device, test_loader)<jupyter_output><empty_output><jupyter_text>Structure - 4<jupyter_code>class Net(nn.Module): # image siE in mnist is 1x28x28
                                           
# More maxpooling, bigger kernel size as well as padding size

    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 7, padding=3)         ## 32x28x28
        self.conv2 = nn.Conv2d(32, 64, 7, padding=3)        ## 64x28x28
        self.pool1 = nn.MaxPool2d(2, 2)                     ## 64x14x14
        self.conv3 = nn.Conv2d(64, 128, 3, padding=1)       ## 128x14x14
        self.conv4 = nn.Conv2d(128, 256, 7, padding=3)      ## 256x14x14
        self.pool2 = nn.MaxPool2d(4, 2)                     ## 256x6x6
        self.conv5 = nn.Conv2d(256, 512, 3, padding=1)      ## 512x6x6
        self.conv6 = nn.Conv2d(512, 1024, 3, padding=1)     ## 1024x6x6
        self.pool3 = nn.MaxPool2d(2, 2)                     ## 1024x3x3
        self.conv7 = nn.Conv2d(1024, 10, 3)                 ## 10x1x1

    def forward(self, x):
        x = self.pool1(F.relu(self.conv2(F.relu(self.conv1(x))))) # 1 convolutional block
        x = self.pool2(F.relu(self.conv4(F.relu(self.conv3(x)))))
        x = self.pool3(F.relu(self.conv6(F.relu(self.conv5(x)))))
        x = F.relu(self.conv7(x))
        x = x.view(-1, 10)
        return F.log_softmax(x)
# Checking that cuda is available or not
torch.cuda.is_available()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = Net().to(device)
summary(model, input_size=(1, 28, 28))
torch.manual_seed(1)
batch_size = 128

kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                    transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=False, transform=transforms.Compose([
                        transforms.ToTensor(),
                        transforms.Normalize((0.1307,), (0.3081,))
                    ])),
    batch_size=batch_size, shuffle=True, **kwargs)

def train(model, device, train_loader, optimizer, epoch):
    model.train()
    pbar = tqdm(train_loader)
    for batch_idx, (data, target) in enumerate(pbar):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx}')


def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)   

for epoch in range(1, 2):
    train(model, device, train_loader, optimizer, epoch)
    test(model, device, test_loader)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1387747593058196, 'fraction_numerical': 0.05322867480223217, 'mean_word_length': 2.249900358708649, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 27, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '489743', 'license': 'MIT', 'n_tokens_mistral': 6027, 'n_tokens_neox': 5460, 'n_words': 1158, 'path': 'Mrinal/assignments/Packt_Mrinal_Shahi_Neural_Network_Structure.ipynb', 'repo_name': 'ks1320/Traffic-Surveillance-System', 'size': '16307'}