网络模型的保存与读取————PyTorch

哔哩大学的PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】
的P26讲讲述了如何保存与读取网络模型.

保存代码:

import torch
import torchvision
from torch import nn

vgg16 = torchvision.models.vgg16(pretrained=False)
# 保存方式1 “保存路径.pth”什么后缀都行推荐为.pth   保存了结构和参数pip
torch.save(vgg16, "vgg16_method1.pth")

# 保存方式2 , 模型参数(官方推荐)
torch.save(vgg16.state_dict(), "vgg16_method2.pth")

# 陷阱
class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3)

    def forward(self, x):
        x = self.conv1(x)
        return x

tudui = Tudui()
torch.save(tudui, "tudui_method1.pth")

效果:
网络模型的保存与读取————PyTorch_第1张图片
图中tudui_method1.pth即为代码中的tudui模型:

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3)

    def forward(self, x):
        x = self.conv1(x)
        return x

读取代码为:

import torch

from model_save import *

import torchvision

model = torch.load("vgg16_method1.pth")

vgg16 = torchvision.models.vgg16(pretrained=False)
vgg16.load_state_dict(torch.load("vgg16_method2.pth"))

model = torch.load('tudui_method1.pth')
print(model)

运行结果为上边写的tudui_method1.pth
网络模型的保存与读取————PyTorch_第2张图片

你可能感兴趣的:(pytorch,pytorch,网络,深度学习)