<jupyter_start><jupyter_text>The Sparks Foundation    Iot and Computer Vision Author: <NAME> 1: Object Detection/Optical Character Recognition(OCR)<jupyter_code>import torch
import torch.nn as nn
import torchvision
import torch.nn.functional as F
import numpy as np
import pandas as pd
from torchvision import datasets, transforms, models, utils
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import os
device = "cuda" if torch.cuda.is_available() else "cpu"
print(device)<jupyter_output>cuda<jupyter_text>Kaggle Dataset<jupyter_code>!kaggle datasets download -d positivepc/object-detection
from zipfile import ZipFile
with ZipFile('object-detection.zip', 'r') as zf:
    zf.extractall('G:\Object-Detection')<jupyter_output><empty_output><jupyter_text>Transforms<jupyter_code>data_dir = "G:\Object-Detection"

train_transform = torchvision.transforms.Compose([transforms.ToTensor(),
                                                  transforms.Resize((36,36)),
                                                  transforms.RandomCrop(36),
                                                 ])
train_dataset = torchvision.datasets.ImageFolder(data_dir + "\\Training_set", transform = train_transform)

trainloader = torch.utils.data.DataLoader(
    train_dataset, batch_size=64, shuffle = True
)

print((train_dataset[0][0].shape))
K = len(set(train_dataset.targets))
print(K)<jupyter_output>2<jupyter_text>Custom CNN model<jupyter_code>class CNN(nn.Module):
    def __init__(self, K):
        super(CNN, self).__init__()
        
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 36, kernel_size = 3, padding = 1),
            nn.ReLU(),
            nn.BatchNorm2d(36),
            nn.MaxPool2d(2),
        )
        
        self.conv2 = nn.Sequential(
            nn.Conv2d(36, 64, kernel_size = 3, padding = 1),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.MaxPool2d(2),
        )
        
        self.conv3 = nn.Sequential(
            nn.Conv2d(64, 128, kernel_size = 3, padding = 1),
            nn.ReLU(),
            nn.BatchNorm2d(128),
            nn.MaxPool2d(2),
        )
        
        self.fc1 = nn.Linear(128 * 4 * 4, 1024)
        self.fc2 = nn.Linear(1024, 512)
        self.fc3 = nn.Linear(512, K)
        
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = x.view(x.size(0), -1)
        x = F.dropout(x, p=0.12)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, p=0.8)
        x = F.relu(self.fc2(x))
        x = F.dropout(x, p=0.6)
        x = self.fc3(x)
        return x
model = CNN(K)
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())<jupyter_output><empty_output><jupyter_text>Training model<jupyter_code>def objectDetection(model, criterion, optimizer, trainloader, epochs):
  train_losses = np.zeros(epochs)

  for i in range(epochs):
    train_loss = []
    for inputs, targets in trainloader:
      inputs, targets = inputs.to(device), targets.to(device)

      optimizer.zero_grad()

      outputs = model(inputs)
      loss = criterion(outputs, targets)

      loss.backward()
      optimizer.step()

      train_loss.append(loss.item())
      
    train_loss = np.mean(train_loss)

    train_losses[i] = train_loss

    print(f'Epoch:{i+1}/{epochs}, Train Loss: {train_loss:.4f}')
    
  return train_losses
train_losses = objectDetection(model, criterion, optimizer, trainloader, epochs=10)<jupyter_output>C:\Users\<NAME>\anaconda3\lib\site-packages\torch\nn\functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  ..\c10/core/TensorImpl.h:1156.)
  return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)<jupyter_text>Saving model<jupyter_code>PATH = "objectDetection.pt"

#Save
torch.save(model, PATH)
#Load
model = torch.load(PATH)
model.eval()<jupyter_output><empty_output><jupyter_text>Training Accuracy<jupyter_code>correct = 0
total = 0

for inputs, targets in trainloader:
    inputs, targets = inputs.to(device), targets.to(device)

    output = model.forward(inputs)

    total += criterion(output, targets).item()

    ps = torch.exp(output).data
    equality = (targets.data == ps.max(1)[1])

    correct += equality.type_as(torch.FloatTensor()).mean()

print("Train Accuracy: {:.3f}%".format(100 * correct/len(trainloader)))<jupyter_output>Train Accuracy: 97.982%<jupyter_text>Testing model<jupyter_code>def imshow(image, ax=None, title=None):
    """Imshow for Tensor."""
    if ax is None:
        fig, ax = plt.subplots()
    images = image.numpy().transpose((1, 2, 0))

    ax.imshow(images)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.tick_params(axis='both', length=0)
    ax.set_xticklabels('')
    ax.set_yticklabels('')

    return ax
model.to('cpu')
model.eval()

images, targets = next(iter(trainloader))
print(images.shape, targets.shape)
fig, axes = plt.subplots(figsize=(10, 10), ncols=5)

for i in range(5):
    ax = axes[i]
    imshow(images[i], ax=ax)
with torch.no_grad():
    output = model.forward(images)

ps = F.softmax(output,dim=1)
rand_img = np.random.randint(64, size=1)[0]
rand_img
probability = ps[rand_img].data.numpy().squeeze()
probability
imshow(images[rand_img])<jupyter_output><empty_output><jupyter_text>Output<jupyter_code>ind = np.arange(2)
targets = ['electric bus','electric car']
width = 0.35
locations = ind

class_probability = plt.barh(ind, probability, width, alpha=1, label = 'Object detection')

plt.yticks(np.arange(2))
plt.title('Probability')
plt.yticks(locations,targets)

#legend
plt.legend()
plt.ylim(top=5)
plt.ylim(bottom=-2)
plt.show();<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13371996685998344, 'fraction_numerical': 0.0231980115990058, 'mean_word_length': 3.386627906976744, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '335304', 'license': 'MIT', 'n_tokens_mistral': 2201, 'n_tokens_neox': 2063, 'n_words': 401, 'path': 'Object-Detection.ipynb', 'repo_name': 'avishshah11/Object-Detection', 'size': '6048'}