Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/main/beginner_source/basics/quickstart_tutorial.py
Views: 713
"""1`Learn the Basics <intro.html>`_ ||2**Quickstart** ||3`Tensors <tensorqs_tutorial.html>`_ ||4`Datasets & DataLoaders <data_tutorial.html>`_ ||5`Transforms <transforms_tutorial.html>`_ ||6`Build Model <buildmodel_tutorial.html>`_ ||7`Autograd <autogradqs_tutorial.html>`_ ||8`Optimization <optimization_tutorial.html>`_ ||9`Save & Load Model <saveloadrun_tutorial.html>`_1011Quickstart12===================13This section runs through the API for common tasks in machine learning. Refer to the links in each section to dive deeper.1415Working with data16-----------------17PyTorch has two `primitives to work with data <https://pytorch.org/docs/stable/data.html>`_:18``torch.utils.data.DataLoader`` and ``torch.utils.data.Dataset``.19``Dataset`` stores the samples and their corresponding labels, and ``DataLoader`` wraps an iterable around20the ``Dataset``.2122"""2324import torch25from torch import nn26from torch.utils.data import DataLoader27from torchvision import datasets28from torchvision.transforms import ToTensor2930######################################################################31# PyTorch offers domain-specific libraries such as `TorchText <https://pytorch.org/text/stable/index.html>`_,32# `TorchVision <https://pytorch.org/vision/stable/index.html>`_, and `TorchAudio <https://pytorch.org/audio/stable/index.html>`_,33# all of which include datasets. For this tutorial, we will be using a TorchVision dataset.34#35# The ``torchvision.datasets`` module contains ``Dataset`` objects for many real-world vision data like36# CIFAR, COCO (`full list here <https://pytorch.org/vision/stable/datasets.html>`_). In this tutorial, we37# use the FashionMNIST dataset. Every TorchVision ``Dataset`` includes two arguments: ``transform`` and38# ``target_transform`` to modify the samples and labels respectively.3940# Download training data from open datasets.41training_data = datasets.FashionMNIST(42root="data",43train=True,44download=True,45transform=ToTensor(),46)4748# Download test data from open datasets.49test_data = datasets.FashionMNIST(50root="data",51train=False,52download=True,53transform=ToTensor(),54)5556######################################################################57# We pass the ``Dataset`` as an argument to ``DataLoader``. This wraps an iterable over our dataset, and supports58# automatic batching, sampling, shuffling and multiprocess data loading. Here we define a batch size of 64, i.e. each element59# in the dataloader iterable will return a batch of 64 features and labels.6061batch_size = 646263# Create data loaders.64train_dataloader = DataLoader(training_data, batch_size=batch_size)65test_dataloader = DataLoader(test_data, batch_size=batch_size)6667for X, y in test_dataloader:68print(f"Shape of X [N, C, H, W]: {X.shape}")69print(f"Shape of y: {y.shape} {y.dtype}")70break7172######################################################################73# Read more about `loading data in PyTorch <data_tutorial.html>`_.74#7576######################################################################77# --------------78#7980################################81# Creating Models82# ------------------83# To define a neural network in PyTorch, we create a class that inherits84# from `nn.Module <https://pytorch.org/docs/stable/generated/torch.nn.Module.html>`_. We define the layers of the network85# in the ``__init__`` function and specify how data will pass through the network in the ``forward`` function. To accelerate86# operations in the neural network, we move it to the GPU or MPS if available.8788# Get cpu, gpu or mps device for training.89device = (90"cuda"91if torch.cuda.is_available()92else "mps"93if torch.backends.mps.is_available()94else "cpu"95)96print(f"Using {device} device")9798# Define model99class NeuralNetwork(nn.Module):100def __init__(self):101super().__init__()102self.flatten = nn.Flatten()103self.linear_relu_stack = nn.Sequential(104nn.Linear(28*28, 512),105nn.ReLU(),106nn.Linear(512, 512),107nn.ReLU(),108nn.Linear(512, 10)109)110111def forward(self, x):112x = self.flatten(x)113logits = self.linear_relu_stack(x)114return logits115116model = NeuralNetwork().to(device)117print(model)118119######################################################################120# Read more about `building neural networks in PyTorch <buildmodel_tutorial.html>`_.121#122123124######################################################################125# --------------126#127128129#####################################################################130# Optimizing the Model Parameters131# ----------------------------------------132# To train a model, we need a `loss function <https://pytorch.org/docs/stable/nn.html#loss-functions>`_133# and an `optimizer <https://pytorch.org/docs/stable/optim.html>`_.134135loss_fn = nn.CrossEntropyLoss()136optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)137138139#######################################################################140# In a single training loop, the model makes predictions on the training dataset (fed to it in batches), and141# backpropagates the prediction error to adjust the model's parameters.142143def train(dataloader, model, loss_fn, optimizer):144size = len(dataloader.dataset)145model.train()146for batch, (X, y) in enumerate(dataloader):147X, y = X.to(device), y.to(device)148149# Compute prediction error150pred = model(X)151loss = loss_fn(pred, y)152153# Backpropagation154loss.backward()155optimizer.step()156optimizer.zero_grad()157158if batch % 100 == 0:159loss, current = loss.item(), (batch + 1) * len(X)160print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")161162##############################################################################163# We also check the model's performance against the test dataset to ensure it is learning.164165def test(dataloader, model, loss_fn):166size = len(dataloader.dataset)167num_batches = len(dataloader)168model.eval()169test_loss, correct = 0, 0170with torch.no_grad():171for X, y in dataloader:172X, y = X.to(device), y.to(device)173pred = model(X)174test_loss += loss_fn(pred, y).item()175correct += (pred.argmax(1) == y).type(torch.float).sum().item()176test_loss /= num_batches177correct /= size178print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")179180##############################################################################181# The training process is conducted over several iterations (*epochs*). During each epoch, the model learns182# parameters to make better predictions. We print the model's accuracy and loss at each epoch; we'd like to see the183# accuracy increase and the loss decrease with every epoch.184185epochs = 5186for t in range(epochs):187print(f"Epoch {t+1}\n-------------------------------")188train(train_dataloader, model, loss_fn, optimizer)189test(test_dataloader, model, loss_fn)190print("Done!")191192######################################################################193# Read more about `Training your model <optimization_tutorial.html>`_.194#195196######################################################################197# --------------198#199200######################################################################201# Saving Models202# -------------203# A common way to save a model is to serialize the internal state dictionary (containing the model parameters).204205torch.save(model.state_dict(), "model.pth")206print("Saved PyTorch Model State to model.pth")207208209210######################################################################211# Loading Models212# ----------------------------213#214# The process for loading a model includes re-creating the model structure and loading215# the state dictionary into it.216217model = NeuralNetwork().to(device)218model.load_state_dict(torch.load("model.pth", weights_only=True))219220#############################################################221# This model can now be used to make predictions.222223classes = [224"T-shirt/top",225"Trouser",226"Pullover",227"Dress",228"Coat",229"Sandal",230"Shirt",231"Sneaker",232"Bag",233"Ankle boot",234]235236model.eval()237x, y = test_data[0][0], test_data[0][1]238with torch.no_grad():239x = x.to(device)240pred = model(x)241predicted, actual = classes[pred[0].argmax(0)], classes[y]242print(f'Predicted: "{predicted}", Actual: "{actual}"')243244245######################################################################246# Read more about `Saving & Loading your model <saveloadrun_tutorial.html>`_.247#248249250