Machine Learning Workflow: data → modeling → optimizing parameters → save model
Example data: FashionMNIST (10 classes: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, or Ankle boot)
(1) `torch.utils.data.Dataset` : stores the samples and their corresponding labels
(2) `torch.utils.data.DataLoader` : wraps an iterable around the `Dataset`
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
Some domain-specific libraries: `TorchText`, `TorchVision`, `TorchAudio`
`torchvision.datasets` includes `CIFAR`, `COCO` etc.
Every TorchVision `Dataset` includes two arguments:
(1) `transform` : modify samples
(2) `target_transform` : modify labels
# Download training data from open datasets.
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
# Download test data from open datasets.
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
Pass `Dataset` as an argument to `DataLoader` → wraps an iterable over the dataset
(1) automatic batching (2) sampling (3) shuffling (4) multiprocess data loading
Below example, batch_size = 64.
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
Defining a model → a class that inherits from `nn.Module`.
Layers → `__init__` function
Data flow → `forward` function
※ Use GPU if available.
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
# Define model
class NeuralNetwork(nn.Module):
def __init__(self): # 모델 레이어는 여기에 정의
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x): # 정의된 레이어에 데이터 들어감
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
Want to train model? You need:
(1) loss function
(2) optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
1 training loop → (1) batch_size training dataset make prediction (2) backpropagation adjusts parameters
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# Compute prediction error
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
test function, refer to below.
def test(dataloader, model):
size = len(dataloader.dataset)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= size
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
Define epoch and print loss.
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dataloader, model, loss_fn, optimizer)
test(test_dataloader, model)
print("Done!")
So, this is how you can train your model.
Done training? Save the model by serializing the internal state dictionary (which contains the model parameters).
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
Saved model and want to use it again? Load it.
model = NeuralNetwork()
model.load_state_dict(torch.load("model.pth"))
Use the model for prediction.
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot",
]
model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
Reference: Quickstart — PyTorch Tutorials 1.8.1+cu102 documentation
파이토치 기본예제 손코딩하기 (0) | 2021.06.09 |
---|---|
1. Tensors (0) | 2021.06.07 |
aiconnnect (0) | 2021.06.07 |
ResNet18 (0) | 2021.06.04 |
sigmoid function (0) | 2021.06.03 |