学习视频——B站【小土堆】
网络模型的保存,代码
import torch
import torchvision
from torch import nn
vgg16 = torchvision.models.vgg16(pretrained=False)
# 保存方式1 模型结构+模型参数
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")
网络模型的读取,代码
import torch
import torchvision
from torch import nn
# 方式1,加载模型
# model = torch.load("vgg16_method1.pth")
# print(model)
# 方式二,加载模型
vgg16 = torchvision.models.vgg16(pretrained=False)
vgg16.load_state_dict(torch.load("vgg16_method2.pth"))
# model2 = torch.load("vgg16_method2.pth")
# print(model2)
#print(vgg16)
# 陷阱1
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
model3 = torch.load("tudui_method1.pth")
print(model3)
# 从模型当中import所有也可,如:
# from model_save import *
# model3 = torch.load("tudui_method1.pth")
# print(model3) # 其中model_save为模型所在文件