<jupyter_start><jupyter_text>TRAINNING A CLASSIFIER<jupyter_code>"""What about data?
-Generally, when you have to deal with image, text, audio or video data, 
 you can use standard python packages that load data into a numpy array. 
 Then you can convert this array into a torch.*Tensor.
 * For images, packages such as Pillow, OpenCV are useful
 * For audio, packages such as scipy and librosa
 * For text, either raw Python or Cython based loading, or NLTK and SpaCy are useful
-Specifically for vision, we have created a package called torchvision, 
 that has data loaders for common datasets such as Imagenet, CIFAR10, MNIST, etc. 
 and data transformers for images, viz., torchvision.datasets and torch.utils.data.DataLoader.
"""
"""Training an image classifier
-We will do the following steps in order:
 1. Load and normalizing the CIFAR10 training and test datasets using torchvision
 2. Define a Convolutional Neural Network
 3. Define a loss function
 4. Train the network on the training data
 5. Test the network on the test data
"""
# loading and normalizing CIFAR10
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = torchvision.datasets.CIFAR10(root='./data',
                                        train=True,
                                        download=False,
                                        transform=transform)
trainloader = torch.utils.data.DataLoader(trainset,
                                          batch_size=4,
                                          shuffle=True,
                                          num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data',
                                       train=False,
                                       download=False,
                                       transform=transform)
testloader = torch.utils.data.DataLoader(testset,
                                         batch_size=4,
                                         shuffle=False,
                                         num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck')
import matplotlib.pyplot as plt
import numpy as np

def imshow(img):
    img = img/2 + 0.5
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()
    
dataiter = iter(trainloader)
images, labels = dataiter.next()

imshow(torchvision.utils.make_grid(images))
print(' '.join("%5s" % classes[labels[j]] for j in range(4)))
# define a convolutional neural network
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
        
    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
    def num_flat_features(self, x):
        size = x.size()[1:]
        s = 1
        for i in size:
            s *= i
        return s
    
net = Net()
# define a loss function and optimizer
import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# train the network
for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        
        running_loss += loss.item()
        if i%2000 == 1999:
            print('[%d, %5d] loss: %.3f'%
                 (epoch+1, i+1, running_loss/2000))
            running_loss = 0.0
print('Finished Training')
# save the model
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
# testing the network on the test data
dataiter = iter(testloader)
images, labels = dataiter.next()

# print images
imshow(torchvision.utils.make_grid(images))
print(' '.join("%5s" % classes[labels[j]] for j in range(4)))
net = Net()
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels).squeeze()
        for i in range(4):
            label = labels[i]
            class_correct[label] += c[i].item()
            class_total[label] += 1


for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))
# training on GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# net.to(device)
# inputs, labels = data[0].to(device), data[1].to(device)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12055749128919861, 'fraction_numerical': 0.025087108013937282, 'mean_word_length': 2.2975301550832854, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '572908', 'license': 'MIT', 'n_tokens_mistral': 1847, 'n_tokens_neox': 1745, 'n_words': 517, 'path': 'src/DQN/pytorch_tutorial/04-TRAINING A CLASSIFIER.ipynb', 'repo_name': 'BepfCp/RL-imple', 'size': '5740'}