具体函数使用方法参考官方文档
https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-datasets/
1、数据转化
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
#把一个取值范围是[0,255]的PIL.Image 转换成 Tensor,将取值变换到(-1,1)之间
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
#载入训练集
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
#每个batch加载4个样本,每个epoch重新打乱数据
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
#载入测试集
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
2、训练集的图片与标签
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
3、定义网络
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self): #定义层的参数
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x): #定义数据在层之间的流动顺序
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5) #变成一维张量,接入全连接层
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
网络结构如下
Net(
(conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(conv3): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(conv4): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(fc1): Linear(in_features=512, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=10, bias=True)
)
4、损失函数
https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-optim/
import torch.optim as optim
criterion = nn.CrossEntropyLoss() #交叉熵损失函数
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) #随机梯度下降,学习率0.001,动量因子0.9
损失函数用的是随机梯度下降。
例子的学习率是固定的,在实践中,有必要随着时间的推移逐渐降低学习率。
class torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)[source]
参数:
params (iterable)
– 待优化参数的iterable
或者是定义了参数组的dict
lr (float)
– 学习率
momentum
(float
, 可选) – 动量因子(默认:0)
weight_decay
(float
, 可选) – 权重衰减(L2惩罚)(默认:0)
dampening
(float
, 可选) – 动量的抑制因子(默认:0)
nesterov
(bool
, 可选) – 使用Nesterov
动量(默认:False)
5、训练过程
for epoch in range(2): # 全部训练集训练两次:epoch=[0,1]
running_loss = 0.0 #清空
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels) #计算损失
loss.backward() #反向传递
optimizer.step() #更新所有参数
# print statistics
running_loss += loss.item() #计算每次batch的损失
if i % 2000 == 1999: # print every 2000 mini-batches #每2000次batch计算一次loss
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
6、测试过程
dataiter = iter(testloader) #迭代
images, labels = dataiter.next() #配套迭代使用效果更佳
# print images 随意测试四张测试集图片看准确度
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
outputs = net(images)
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
7、通过GPU训练
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assume that we are on a CUDA machine, then this should print a CUDA device:
print(device)
#cpu移到GPU主要移俩:数据和网络
net.to(device) #移网络
inputs, labels = inputs.to(device),labels.to(device) #移数据