<jupyter_start><jupyter_text>README- This notebook uses the GPU for CNN.  Image Classification with Convolution Neural Network (CNN)<jupyter_code># get a dataset using pytorch
import torch
import torchvision
from torchvision import transforms

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5,), (0.5,))])

trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True, num_workers=2)

testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testLoader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False, num_workers=2)
# Prepare the CNN to run on the GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# print out the device
print(device)
# implement a CNN
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # first convolution layer, 1 input (image), 32 kernels, 3x3
        self.conv1 = nn.Conv2d(1, 32, 3)
        # second convolution layer, 32 inputs, 64 kernels, 3x3
        self.conv2 = nn.Conv2d(32, 64, 3)
        # third convolution layer, 64 inputs, 64 kernels, 3x3
        self.conv3 = nn.Conv2d(64, 64, 3)
        # fourth convolution layer, 64 inputs, 64 kernels, 3x3
        self.conv4 = nn.Conv2d(64, 64, 3)
        # first linear layer with output size of 10
        self.fc1 = nn.Linear(4096, 10)
    
    def forward(self, x):
        # first relu activation after first convolution
        x = F.relu(self.conv1(x))
        # second relu activation after second convolution
        x = F.relu(self.conv2(x))
        # maxpool layer with kernels 2x2
        x = F.max_pool2d(x, (2, 2))
        # third relu activation after third convolution
        x = F.relu(self.conv3(x))
        # fourth relu activation after fourth convolution
        x = F.relu(self.conv4(x))
        # flattening layer
        x = torch.flatten(x, 1, 3)
        # linear layer with output size 10
        x = self.fc1(x)
        return x

# initialize the CNN
net = Net()
# convert the methods to CUDA tensors
net.to(device)
import torch.optim as optim

# Create SGD optimizer with learning rate 0.001
optimizer = optim.SGD(net.parameters(), lr=0.001)
# Create categorical cross entropy criterion
criterion = nn.CrossEntropyLoss()
# train the CNN for 10 epochs
for epoch in range(10):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs, data is a list of [inputs, labels]
        inputs, labels = data
        # send data to the GPU
        inputs = inputs.to(device)
        labels = labels.to(device)
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        # print statistics
        running_loss += loss.item()
        if i % 1000 == 999:    # print every 1000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 1000))
            running_loss = 0.0

print('Finished Training!')
# save the trained model
torch.save(net.state_dict(), 'mnist_net.pth')
# predict the labels of the test images and measure the accuracy
correct = 0
total = 0
with torch.no_grad():
    for data in testLoader:
        images, labels = data
        images = images.to(device)
        labels = labels.to(device)
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'Accuracy of the network on the test images: {correct / total * 100}%')<jupyter_output>Accuracy of the network on the test images: 98.32%
{'fraction_non_alphanumeric': 0.10609538383065545, 'fraction_numerical': 0.03340984442744198, 'mean_word_length': 2.8526522593320234, '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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '521650', 'license': 'MIT', 'n_tokens_mistral': 1323, 'n_tokens_neox': 1192, 'n_words': 386, 'path': 'image-classification/image_clf_cnn.ipynb', 'repo_name': 'onrcayci/computer-vision', 'size': '3921'}