当前位置:网站首页>PyTorch(15)---模型保存和加载
PyTorch(15)---模型保存和加载
2022-08-02 14:07:00 【伏月三十】
模型保存和加载
模型保存
import torch
import torchvision
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
#模型:vgg16
vgg16=torchvision.models.vgg16(pretrained=False)
'''第一种:模型参数都保存'''
torch.save(vgg16,"vgg16_method1.pth")
'''第二种:只保存参数,保存成字典(官方推荐)'''
torch.save(vgg16.state_dict(),"vgg16_method2.pth")
'''陷阱1:使用自己搭建的网络(第一种)'''
class Demo(nn.Module):
def __init__(self) -> None:
super().__init__()
self.model1=Sequential(
Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1, ),
MaxPool2d(kernel_size=2, ),
Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2, ),
MaxPool2d(kernel_size=2),
Conv2d(32, 64, 5, 1, 2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 10),
)
def forward(self,x):
x=self.model1(x)
return x
#模型2
demo=Demo()
torch.save(demo,"demo_method1.pth")
模型加载
import torch
import torchvision
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
from model_save import *
'''方式1:(使用保存方式1),加载模型'''
model=torch.load("vgg16_method1.pth")
print(model)
print("------------------------------------------------------------")
'''方式2'''
#先把结构搞出来
vgg16=torchvision.models.vgg16(pretrained=False)
#再把字典形式的参数放进去(自己训练的参数!!!)
vgg16.load_state_dict(torch.load("vgg16_method2.pth"))
print(vgg16)
print("------------------------------------------------------------")
'''陷阱1:要把自己的网络模型放过来,但是不用实例化了 或者将模型保存的文件import过来 '''
medel1=torch.load("demo_method1.pth")
print(medel1)
边栏推荐
猜你喜欢

浮点数的运算方法

tensorflow实战之手写体识别

关于spark

华为防火墙IPS

宝塔搭建PHP自适应懒人网址导航源码实测

It is not allowed to subscribe with a(n) xxx multiple times.Please create a fresh instance of xxx

绕过正则实现SQL注入

内存申请(malloc)和释放(free)之下篇

宝塔面板搭建小说CMS管理系统源码实测 - ThinkPHP6.0

Using the cloud GPU + pycharm training model to realize automatic background run programs, save training results, the server automatically power off
随机推荐
Flink-独立集群/Yarn
统计偏科最严重的前100名学生
Word2vec词向量
profiler network乱码
6.如何使用CardView制作卡片布局效果
LLVM系列第十九章:写一个简单的Module Pass
ConstraintLayout从入门到放弃
boost库智能指针
checkPermissions Missing write access to /usr/local/lib
Seq2Seq模型PyTorch版本
关于UDF
华为防火墙
详解RecyclerView系列文章目录
spark on yarn
Ehcache基础学习
什么是 Web 3.0:面向未来的去中心化互联网
再见篇:App专项技术优化
LLVM系列第十章:控制流语句if-else-phi
Cannot figure out how to save this field into database. You can consider adding a type converter for
LLVM系列第二十四章:用Xcode编译调试LLVM源码