官网链接
Quickstart — PyTorch Tutorials 2.0.1+cu117 documentation
快速开始
本节将介绍机器学习中常见任务的API。请参阅每个部分中的链接以深入了解。
数据处理
PyTorch有两个处理数据源,torch.utils.data.DataLoader 和 torch.utils.data.Dataset 。Dataset存储样本及其相应的标签,DataLoader在Dataset之上包装一个可迭代对象。
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
PyTorch提供了特定领域的库,如TorchText, TorchVision和TorchAudio,它们都包含数据集。在本教程中,我们将使用TorchVision数据集。
torchvision.datasets 模块包含了真实数据的Dataset对象。比如 CIFAR, COCO(完整列表参考Datasets — Torchvision 0.15 documentation)。在本教程中,我们使用FashionMNIST数据集。每个TorchVision数据集包含两个参数:transform和target_transform,分别用于修改样本和标签。
# 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(),
)
我们将Dataset作为DataLoader的入参,Dataset在数据集上包装了一个可迭代对象,并支持自动批处理、采样、洗牌和多进程数据加载。这里我们定义了一个批处理大小为64,即dataloader可迭代对象中的每个元素将返回一批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(f"Shape of X [N, C, H, W]: {X.shape}")
print(f"Shape of y: {y.shape} {y.dtype}")
break
输出:
Shape of X [N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of y: torch.Size([64]) torch.int64
创建模型
为了在PyTorch中定义一个神经网络,我们创建了一个继承了nn.Module的类,我们在__init__函数中定义网络层,并在forward函数中指定数据如何通过网络。为了加速神经网络的操作,我们将其转移到GPU或MPS(如果可用)。
注:
PyTorch MPS (Multi-Process Service)是 PyTorch 中的一种分布式训练方式。它是基于Apple的MPS(Metal Performance Shaders) 框架开发的
# Get cpu, gpu or mps device for training.
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"Using {device} device")
# Define model
class NeuralNetwork(nn.Module):
def __init__(self):
super().__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)
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
输出
Using mps device
NeuralNetwork(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear_relu_stack): Sequential(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): ReLU()
(2): Linear(in_features=512, out_features=512, bias=True)
(3): ReLU()
(4): Linear(in_features=512, out_features=10, bias=True)
)
)
注:因为我的设备是苹果,所以输出是mps,跟官网显示不同
优化模型参数
为了训练一个模型,我们需要一个损失函数和一个优化器。
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
在单个训练循环中,模型对训练数据集进行预测(批量提供给它),并反向传播预测误差以调整模型的参数。
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
model.train()
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
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), (batch + 1) * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
我们还根据测试数据集检查模型的性能,以确保它正在学习。
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
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 /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
训练过程在几个迭代(epochs)中进行。在每个epochs,模型学习参数以做出更好的预测。我们打印出模型在每个epochs的精度和损失;我们希望看到精度随着时间的推移而提高,损失随着时间的推移而减少。
输出
Epoch 1
-------------------------------
loss: 2.304695 [ 64/60000]
loss: 2.293914 [ 6464/60000]
loss: 2.271139 [12864/60000]
loss: 2.267832 [19264/60000]
loss: 2.240983 [25664/60000]
loss: 2.217048 [32064/60000]
loss: 2.230957 [38464/60000]
loss: 2.190546 [44864/60000]
loss: 2.180454 [51264/60000]
loss: 2.167166 [57664/60000]
Test Error:
Accuracy: 43.7%, Avg loss: 2.148366
Epoch 2
-------------------------------
loss: 2.155765 [ 64/60000]
loss: 2.153187 [ 6464/60000]
loss: 2.084353 [12864/60000]
loss: 2.106838 [19264/60000]
loss: 2.051079 [25664/60000]
loss: 1.998855 [32064/60000]
loss: 2.030421 [38464/60000]
loss: 1.942099 [44864/60000]
loss: 1.941234 [51264/60000]
loss: 1.891874 [57664/60000]
Test Error:
Accuracy: 55.8%, Avg loss: 1.873747
Epoch 3
-------------------------------
loss: 1.904033 [ 64/60000]
loss: 1.885520 [ 6464/60000]
loss: 1.749947 [12864/60000]
loss: 1.801118 [19264/60000]
loss: 1.690538 [25664/60000]
loss: 1.652585 [32064/60000]
loss: 1.680197 [38464/60000]
loss: 1.571219 [44864/60000]
loss: 1.597052 [51264/60000]
loss: 1.505626 [57664/60000]
Test Error:
Accuracy: 61.0%, Avg loss: 1.510632
Epoch 4
-------------------------------
loss: 1.579605 [ 64/60000]
loss: 1.553953 [ 6464/60000]
loss: 1.388195 [12864/60000]
loss: 1.468328 [19264/60000]
loss: 1.347958 [25664/60000]
loss: 1.354385 [32064/60000]
loss: 1.368013 [38464/60000]
loss: 1.285745 [44864/60000]
loss: 1.321613 [51264/60000]
loss: 1.226315 [57664/60000]
Test Error:
Accuracy: 63.1%, Avg loss: 1.248957
Epoch 5
-------------------------------
loss: 1.330482 [ 64/60000]
loss: 1.320243 [ 6464/60000]
loss: 1.139326 [12864/60000]
loss: 1.250566 [19264/60000]
loss: 1.124903 [25664/60000]
loss: 1.160373 [32064/60000]
loss: 1.176003 [38464/60000]
loss: 1.108413 [44864/60000]
loss: 1.148409 [51264/60000]
loss: 1.063753 [57664/60000]
Test Error:
Accuracy: 64.3%, Avg loss: 1.086042
Done!
保存模型
保存模型的一种常用方法是序列化内部状态字典(包含模型参数)。
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
输出
Saved PyTorch Model State to model.pth
加载模型
model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))
这个模型现在可以用来做预测。文章来源:https://www.toymoban.com/news/detail-499260.html
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():
x = x.to(device)
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
输出文章来源地址https://www.toymoban.com/news/detail-499260.html
Predicted: "Ankle boot", Actual: "Ankle boot"
到了这里,关于PyTorch翻译官网教程1-QUICKSTART的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!