pytorch学习(一)模型保存,加载

pytorch:训练分类器
https://ptorch.com/docs/3/cifar10_tutorial

如何保存训练的参数?


# 保存和加载整个模型  
torch.save(net, 'net.pth')  
model = torch.load('net.pth')  
 
# 仅保存和加载模型参数  
torch.save(model_object.state_dict(), 'net.pth')  
model_object.load_state_dict(torch.load('net.pth'))

net是model object,即训练过后的模型。
完整代码:

训练图像分类器
我们将按顺序执行以下步骤:
1、使用CIFAR10培训和测试数据集加载和归一化 torchvision
2、定义卷积神经网络
3、定义损失函数
4、训练网络上的训练数据
5、测试网络上的测试数据


#1、使用CIFAR10培训和测试数据集加载和归一化 torchvision 
import torch
import torchvision
import torchvision.transforms as transforms

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

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)

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、定义卷积神经网络 
from torch.autograd import Variable
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()

#3、定义损失函数 
import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

#4、训练网络上的训练数据 
for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)

        # 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.data[0]
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

#5、测试网络上的测试数据
#可以看一下预测结果,即对应图像中的东西叫什么名字
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)))

我们可以保存训练的参数:

torch.save(net,'net.pth')

接下来就可以用这个训练后的参数模型来判断图片是什么了。

import torch
from PIL import Image
import torchvision.transforms as trans
from torch.autograd import Variable
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


def testNet():
    net=torch.load("models/net.pth")#加载网络

    img=Image.open("0.jpg")
    t=trans.Compose([
        trans.Resize(32),
        trans.CenterCrop( 32 ),
        trans.ToTensor(),#255 hwc chw
        trans.Normalize((0.4914, 0.4822, 0.4465),(0.2023, 0.1994, 0.2010))
    ])
    img=t(img).unsqueeze(0)
    #nchw
    output=net(img)
    print(output)
    leibie=('飞机','汽车','鸟','猫','鹿','狗','青蛙','马','船','卡车')
    index=output.argmax(1)
    print("预测的结果是:" +leibie[index])
    
    
testNet()

    #output.argmax(output,dim=)

结果:

tensor([[-0.0166,  0.9878,  0.0168,  0.0208,  0.0049,  0.0225, -0.0295,  0.0261,
         -0.0208, -0.0727]], grad_fn=<AddmmBackward>)
预测的结果是:汽车

需要注意的是:
如果出现这种错误:

pytorch AttributeError: Can’t get attribute ‘Net’ on <module ‘main’>

将声明模型的class的部分代码或者你模型定义的代码加进新的项目中,这样就可以正常加载使用了。即“Net”

发布了53 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/YUEXILIULI/article/details/103033606