<jupyter_start><jupyter_text>[View in Colaboratory](https://colab.research.google.com/github/robmarkcole/robins-google-colaboratory/blob/master/Getting_started_with_pytorch.ipynb) work through https://medium.com/@chsafouane/getting-started-with-pytorch-on-google-colab-811c59a656b6The good news about Colab is that Google offers a Tesla K80 GPU. One can keep working with the GPU instance continuously up to 12 hoursWe can also work through the tutorials on https://notebooks.azure.com/pytorch<jupyter_code>!pip3 install torch torchvision
import torch
torch.__version__<jupyter_output><empty_output><jupyter_text>Lets follow the tutorials on pytorch https://pytorch.org/tutorials/WHAT IS PYTORCH?It’s a Python-based scientific computing package targeted at two sets of audiences:* A replacement for NumPy to use the power of GPUs* a deep learning research platform that provides maximum flexibility and speed<jupyter_code>x = torch.empty(5, 3)
print(x)
print(x.size())
y = torch.rand(5, 3)
print(x + y)
print(x[:, 1])
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())<jupyter_output>torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])<jupyter_text>Converting a Torch Tensor to a NumPy Array<jupyter_code>a = torch.ones(5)
print(a)
b = a.numpy()
print(b)<jupyter_output>[1. 1. 1. 1. 1.]<jupyter_text>CUDA TENSORSTensors can be moved onto any device using the .to method.<jupyter_code># let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!<jupyter_output>tensor([[-1.0558,  1.1853,  0.6714, -0.8438],
        [ 2.3848,  1.1295,  3.0584,  0.5120],
        [ 0.5200,  0.8300,  0.1142,  0.9183],
        [-1.1471,  0.4829, -0.0223,  0.5914]], device='cuda:0')
tensor([[-1.0558,  1.1853,  0.6714, -0.8438],
        [ 2.3848,  1.1295,  3.0584,  0.5120],
        [ 0.5200,  0.8300,  0.1142,  0.9183],
        [-1.1471,  0.4829, -0.0223,  0.5914]], dtype=torch.float64)<jupyter_text>CUDA is a parallel computing platform and application programming interface (API) model created by Nvidia.[1] It allows software developers and software engineers to use a CUDA-enabled graphics processing unit (GPU) for general purpose processing<jupyter_code><jupyter_output><empty_output><jupyter_text>Training a classifierhttp://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html<jupyter_code>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=True, 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=True, 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')
ls
ls data/
ls data/cifar-10-batches-py/
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

# functions to show an image


def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))


# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()

# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
from torch.autograd import Variable
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, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)

        # 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.data[0]
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
outputs = net(Variable(images))
_, predicted = torch.max(outputs.data, 1)

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))
correct = 0
total = 0
for data in testloader:
    images, labels = data
    outputs = net(Variable(images))
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum()

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1344292518051928, 'fraction_numerical': 0.05023813181748348, 'mean_word_length': 3.06875, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '156000', 'license': 'MIT', 'n_tokens_mistral': 2413, 'n_tokens_neox': 2210, 'n_words': 579, 'path': 'Getting_started_with_pytorch.ipynb', 'repo_name': 'robmarkcole/robins-google-colaboratory', 'size': '6509'}