working with data (处理数据)
PyTorch 提供了两个基本方法用于数据处理,torch.utils.data.DataLoader 和 torch.utils.data.Dataset。DataSet 存储样本及其对应的标签,DataLoader 在 Dataset 基础上封装了一个可迭代的对象。
PyTorch 提供了不同应用领域的库,例如 TorchText, TorchVision 和 TorchAudio ,它们都包含了 datasets, 这个教程主要以 TorchVision 为主;
torchvision.datasets 包含了 CIFAR 与 COCO 等 ,本教程使用 FashionMNIST 数据集,每个 TorchVision 数据集包含了参数 transform 和 target_transform 用于修改样本和标签。
我们将 Dataset 作为参数传递给 DataLoader, 这样就可以封装一个可迭代的访问器,支持自动批处理,采样,打乱顺序和多进程数据加载。这里我们定义 batch size 为 64, 这样就可以每次访问获得 64 个样本和对应的标签。
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# 下载FashionMNIST训练数据
training_data = datasets.FashionMNIST(
root = "../../data",
train = True,
download = True,
transform = ToTensor(),
)
# 下载FashionMNIST测试数据
test_data = datasets.FashionMNIST(
root = "../../data",
train = False,
download = True,
transform = ToTensor(),
)
batch_size = 64
# 创建 DataLoader
train_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=True)
for X, Y in test_dataloader:
print(f"Shape of X[N, C, H, W]: {X.shape}")
print(f"Shape of Y[N]: {Y.shape}")
break
Shape of X[N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of Y[N]: torch.Size([64])
Creating Models (创建模型)
为了在 PyTorch 里定义神经网络,我们创建一个类从 nn.Module里继承,在 __init__
里定义网络层,在 forward
里定义数据传输的过程,如果有 GPU,可以将数据迁移到 GPU上加速神经网络的训练。
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")
# 定义模型
class FirstNN(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):
output = self.flatten(x)
output = self.linear_relu_stack(output)
return output
model = FirstNN().to(device)
print(model)
Using cuda device
FirstNN(
(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)
)
)
Optimizing the Model Parameters ( 优化模型参数 )
训练一个模型需要 loss function 和优化器 optimizer.
在一个单独的训练循环中,模型预测训练过程会进行预测,并将预测结果的偏差反向传播从而调整训练模型参数。
训练过程需要进行多次迭代(epoch)。在每个 epoch 中,模型会学习参数使得预测效果更好,我们打印每次的准确率和 loss 。
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# 定义训练函数
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)
# 计算误差
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}]")
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 = 5
for t in range(epochs):
print(f"Epoch {t+1} \n-----------------------")
train(train_dataloader, model, loss_fn, optimizer)
test(test_dataloader, model, loss_fn)
print("Done!")
Epoch 1
-----------------------
loss: 2.309391 [ 0/60000]
loss: 2.306924 [ 6400/60000]
loss: 2.277485 [12800/60000]
loss: 2.252887 [19200/60000]
loss: 2.247070 [25600/60000]
loss: 2.228895 [32000/60000]
loss: 2.207972 [38400/60000]
loss: 2.216034 [44800/60000]
loss: 2.187572 [51200/60000]
loss: 2.134164 [57600/60000]
Test Error:
Accuracy: 41.2%, Avg loss: 2.160574
Epoch 2
-----------------------
loss: 2.162140 [ 0/60000]
loss: 2.163433 [ 6400/60000]
loss: 2.128148 [12800/60000]
loss: 2.115601 [19200/60000]
loss: 2.057952 [25600/60000]
loss: 2.054668 [32000/60000]
loss: 2.031033 [38400/60000]
loss: 1.978136 [44800/60000]
...
Test Error:
Accuracy: 65.4%, Avg loss: 1.092799
Done!
Lnton羚通专注于音视频算法、算力、云平台的高科技人工智能企业。 公司基于视频分析技术、视频智能传输技术、远程监测技术以及智能语音融合技术等, 拥有多款可支持ONVIF、RTSP、GB/T28181等多协议、多路数的音视频智能分析服务器/云平台。
标签:loss,torch,nn,dataloader,test,PyTorch,60000,羚通,Lnton From: https://blog.51cto.com/LNTON/7131859