QUICKSTART
首先展示一个完整的pytorch代码:
- load data
- create the model
- train the model
- save & load the model
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt
### Working with data ###
### step 1: get datasets.
### step 2: get dataloaders. Pass the 'Dataset' as an argument to 'DataLoader'. This supports automatic batching, sampling, shuffling and multiprocess data loading.
# Download training data from open datasets.
training_data = datasets.FashionMNIST(root="data", train=True, download=True, transform=ToTensor())
test_data = datasets.FashionMNIST(root="data", train=False, download=True, transform=ToTensor())
batch_size = 64
# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
for X, y in test_dataloader:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
### Creating Models ###
### step 1: create a class that inherits from nn.Module
### step 2: define the layers in '__init__' function
### step 3: define specify the data flow in 'forward' function
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available(