torch.utils.data.DataLoader
torch.utils.data.Dataset. Dataset
torchvision.datasets模块数据集包含许多真实世界视觉数据的对象,如 CIFAR、COCO。在本教程中,我们使用 FashionMNIST 数据集。每个 TorchVision的数据集包含两个参数:transform和 target_transform样本和标签。
下载数据集
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# 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这里对我们的数据集进行了迭代,自动批处理、采样、混洗和多进程数据加载。这里我们定义了一个64的batch size,即dataloader iterable中的每个元素都会返回一个batch 64个特征和标签。
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:#dataloader iterable中的每个元素都会返回一个batch64个特征和标签。
print(f"Shape of X [N,C,H,W]:{X.shape}")
print(f"Shape of y:{y.shape}{y.dtype}")
break
创建模型
为了在 PyTorch 中定义神经网络,我们创建了一个继承自nn.Module的类。我们在函数中定义网络层,并在__init__函数中指定数据将如何通过网络forward。为了加速神经网络中的操作,我们将其移至 GPU(如果可用)。
device="cuda" if torch.cuda.is_available() else "cpu"#GPU加速
print(f"Using{device}device")
class NeuralNetwork(nn.Module):#继承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.Linear(in_features,out_features)
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)
优化模型参数
在单个训练循环中,模型对训练数据集进行预测(分批输入),并反向传播预测误差以调整模型的参数。
loss_fn=nn.CrossEntropyLoss()#损失函数
optimizer=torch.optim.SGD(model.parameters(),lr=1e-3)#优化器
def train(dataloader,model,loss_fn,optimizer):#batch直接在处理数据时就已经设定好了
size=len(dataloader.dataset)
model.train()
for batch,(X,y) in enumerate(dataloader):
X,y=X.to(device),y.to(device)
pred=model(X)#forward
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():#每次计算requires_grad=False,禁止梯度计算
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)中进行。在每个时期,模型都会学习参数以做出更好的预测。我们在每个时期打印模型的准确性和损失;我们希望看到每个 epoch 的准确率增加和损失减少。
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!")
保存模型
torch.save(model.state_dict(),"model.pth")
print("Save Pytorch Model State to model.pth")
加载模型
model = NeuralNetwork()
model.load_state_dict(torch.load("model.pth"))
#预测
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}"')