快速入门 目录
快速入门
张量
数据集和数据加载器
转换
建立模型
自动区分
优化循环
保存,加载和使用模型
0 包加载 PyTorch有两个处理数据的原语: torch.utils.data.DataLoader和torch.utils.data.Dataset。 Dataset存储样本及其相应的标签,并DataLoader在周围包裹一个可迭代的对象Dataset。
1 2 3 4 5 6 import torchfrom torch import nnfrom torch.utils.data import DataLoaderfrom torchvision import datasetsfrom torchvision.transforms import ToTensor, Lambda, Composeimport matplotlib.pyplot as plt
1 数据库和数据导入 PyTorch提供了特定领域的库,例如TorchText, TorchVision和TorchAudio,所有这些库都包含数据集。在本教程中,我们将使用TorchVision数据集。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 training_data = datasets.FashionMNIST( root="data" , train=True , download=True , transform=ToTensor(), ) test_data = datasets.FashionMNIST( root="data" , train=False , download=True , transform=ToTensor(), )
2 数据处理 将Dataset当作参数传递给DataLoader。这在我们的数据集上包装了一个可迭代的对象,并支持自动批处理,采样,改组和多进程数据加载。在这里,我们将批处理大小定义为64,即,可迭代的数据加载器中的每个元素将返回一批64个功能部件和标签。
1 2 3 4 5 6 7 8 9 10 batch_size = 64 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
3.1 创建模型 为了在PyTorch中定义一个神经网络,我们创建了一个从nn.Module继承的类。我们在__init__函数中定义网络的层,并在函数中指定数据如何通过网络forward。为了加速神经网络中的操作,我们将其移至GPU(如果有)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 device = "cuda" if torch.cuda.is_available() else "cpu" print ("Using {} device" .format (device))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)
3.2-4 前项传播/损失函数/优化器 训练模型,我们需要损失函数 和优化器。
1 2 loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3 )
3.5 反向传播 在单个训练循环中,模型对训练数据集进行预测(分批进给),然后反向传播预测误差以调整模型的参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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) pred = model(X) loss = loss_fn(pred, y) 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} ]" )
4 验证模型 我们还将对照测试数据集检查模型的性能,以确保模型正在学习。
1 2 3 4 5 6 7 8 9 10 11 12 13 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.1 f} %, Avg loss: {test_loss:>8f} \n" )
训练过程是在几个迭代(历元)上进行的。在每个时期,模型都会学习参数以做出更好的预测。我们在每个时期打印模型的准确性和损失;我们希望看到每个时期的精度都会提高而损耗会降低。
1 2 3 4 5 6 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!")
5 使用模型 保存模型 保存模型的常用方法是序列化内部状态字典(包含模型参数)。
1 2 torch.save(model.state_dict(), "model.pth") print("Saved PyTorch Model State to model.pth")
加载模型 加载模型的过程包括重新创建模型结构并将状态字典加载到其中
1 2 model = NeuralNetwork() model.load_state_dict(torch.load("model.pth" ))
模型预测 现在可以使用该模型进行预测。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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} "' )