PyTorch浅尝辄止(1)
与数据共舞
PyTorch跟数据相关的类有三个:torch.utils.data.DataLoader
,torch.utils.data.Dataset
,torch.utils.data.Sampler
。Dataset
是一个抽象类,你需要继承它并实现__len__
和__getitem__
方法。DataLoader
是一个迭代器,它能够把Dataset
包装起来,提供一些有用的方法。Sampler
是一个抽象类,它能够提供索引的迭代器,用于DataLoader
从Dataset
中获取样本。
PyTorch跟领域相关的库包括torchaudio
、torchvision
和torchtext
。torchaudio
包含与音频处理相关的数据集。torchvision
包含了一些常用的图像、视频数据集,比如MNIST
,CIFAR10
,COCO
等。torchtext
包含了一些常用的文本数据集,比如AG_NEWS
,SogouNews
,DBpedia
等。
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data\FashionMNIST\raw\train-images-idx3-ubyte.gz
0%| | 0/26421880 [00:00<?, ?it/s]
Extracting data\FashionMNIST\raw\train-images-idx3-ubyte.gz to data\FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data\FashionMNIST\raw\train-labels-idx1-ubyte.gz
0%| | 0/29515 [00:00<?, ?it/s]
Extracting data\FashionMNIST\raw\train-labels-idx1-ubyte.gz to data\FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data\FashionMNIST\raw\t10k-images-idx3-ubyte.gz
0%| | 0/4422102 [00:00<?, ?it/s]
Extracting data\FashionMNIST\raw\t10k-images-idx3-ubyte.gz to data\FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data\FashionMNIST\raw\t10k-labels-idx1-ubyte.gz
0%| | 0/5148 [00:00<?, ?it/s]
Extracting data\FashionMNIST\raw\t10k-labels-idx1-ubyte.gz to data\FashionMNIST\raw
DataLoader
是一个迭代器,它能够把Dataset
包装起来,提供一些有用的方法。所以在调用时,把Dataset
作为参数传递给DataLoader
。后者会返回一个迭代器,我们可以用它来遍历Dataset
,并支持自动分批、采样、打乱数据和多进程数据加载等功能。
下面我们定义批次大小为64,然后创建一个DataLoader
实例,这样每次迭代就会返回64个样本。
batch_size = 64
# 创建一个 DataLoader 来迭代训练数据
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
print(f"Label categories: {training_data.classes}, {len(training_data.classes)}")
print("Done!")
Shape of X [N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of y: torch.Size([64]) torch.int64
Label categories: ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'], 10
Done!
与模型同在
在PyTorch中定义神经网络,我们定义一个类,继承自nn.Module
。在类的构造函数中,我们定义网络的结构,即各个层的类型和参数。在类的forward
函数中,我们定义网络的前向传播逻辑。为了加速计算,当有硬件支持的时候,我们可以把网络的计算放在GPU上。
从上面对数据的形状的输出中,可以看到我们的数据批次为64,神经网络的输入为28*28,所以我们需要把数据展平,即把每个样本的形状从(1, 28, 28)变成(1, 784)。然后我们定义一个神经网络,它包含两个全连接层,第一个全连接层的输入为784,输出为512,第二个全连接层的输入为512,输出为10。
这个10是因为我们的数据集有10个类别,所以我们的输出也是10个类别的概率分布。
device =(
"cuda"
if torch.cuda.is_available()
else "cpu"
)
print("Using {} device".format(device))
Using cpu 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),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
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)
)
)
模型训练
在训练模型时,我们需要定义损失函数和优化器。损失函数用于衡量模型的预测结果和真实值之间的差异,优化器则用于更新模型的参数,使得模型的预测结果更接近真实值。
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
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}]")
还应该在测试集上评估模型的性能,以确保模型在训练过程中没有过拟合。
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.302288 [ 0/60000]
loss: 2.295353 [ 6400/60000]
loss: 2.275450 [12800/60000]
loss: 2.272285 [19200/60000]
loss: 2.248172 [25600/60000]
loss: 2.220821 [32000/60000]
loss: 2.220658 [38400/60000]
loss: 2.192120 [44800/60000]
loss: 2.190701 [51200/60000]
loss: 2.152144 [57600/60000]
Test Error:
Accuracy: 54.1%, Avg loss: 2.150920
Epoch 2
-------------------------------
loss: 2.157440 [ 0/60000]
loss: 2.149096 [ 6400/60000]
loss: 2.094668 [12800/60000]
loss: 2.113385 [19200/60000]
loss: 2.047285 [25600/60000]
loss: 1.991776 [32000/60000]
loss: 2.012696 [38400/60000]
loss: 1.941758 [44800/60000]
loss: 1.951613 [51200/60000]
loss: 1.859037 [57600/60000]
Test Error:
Accuracy: 58.6%, Avg loss: 1.871845
Epoch 3
-------------------------------
loss: 1.904892 [ 0/60000]
loss: 1.874474 [ 6400/60000]
loss: 1.766521 [12800/60000]
loss: 1.803286 [19200/60000]
loss: 1.680894 [25600/60000]
loss: 1.642499 [32000/60000]
loss: 1.653953 [38400/60000]
loss: 1.570671 [44800/60000]
loss: 1.598109 [51200/60000]
loss: 1.476388 [57600/60000]
Test Error:
Accuracy: 61.1%, Avg loss: 1.506833
Epoch 4
-------------------------------
loss: 1.573699 [ 0/60000]
loss: 1.539440 [ 6400/60000]
loss: 1.397835 [12800/60000]
loss: 1.462805 [19200/60000]
loss: 1.341058 [25600/60000]
loss: 1.344851 [32000/60000]
loss: 1.349764 [38400/60000]
loss: 1.286765 [44800/60000]
loss: 1.320334 [51200/60000]
loss: 1.216479 [57600/60000]
Test Error:
Accuracy: 63.6%, Avg loss: 1.243597
Epoch 5
-------------------------------
loss: 1.317790 [ 0/60000]
loss: 1.302650 [ 6400/60000]
loss: 1.139997 [12800/60000]
loss: 1.243143 [19200/60000]
loss: 1.119455 [25600/60000]
loss: 1.145241 [32000/60000]
loss: 1.161800 [38400/60000]
loss: 1.106545 [44800/60000]
loss: 1.146681 [51200/60000]
loss: 1.061042 [57600/60000]
Test Error:
Accuracy: 64.8%, Avg loss: 1.079930
Done!
模型保存和读入
训练之后,我们可以保存模型的参数,以便后续使用。
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
Saved PyTorch Model State to model.pth
model_loaded = NeuralNetwork()
model_loaded.load_state_dict(torch.load("model.pth"))
<All keys matched successfully>
模型预测
直接使用训练好的模型可以进行预测。训练好的模型可以是在本地训练好的,也可以是从其他地方下载的。下面我们使用训练好的模型对测试集中的第一张图片进行预测。
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot",
] # classes = train_dataset.classes,这里假装我们没有任何dataset
model_loaded.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
pred = model_loaded(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
Predicted: "Ankle boot", Actual: "Ankle boot"
import matplotlib.pyplot as plt
plt.imshow(x.squeeze(), cmap='gray')
plt.title(f'Predicted: "{predicted}", Actual: "{actual}"')
Text(0.5, 1.0, 'Predicted: "Ankle boot", Actual: "Ankle boot"')
总结
- PyTorch神经网络的概念相对直观;
- 数据集合与数据集合装载器的概念;
- 模型的训练、保存、读入、预测等。