首页 > 应用开发 > IT综合 > 泰山众筹SUN4.0模式软件开发
一、pytorch模型保存/加载
有两种方式可用于保存/加载pytorch模型1)文件中保存模型结构和权重参数2)文件只保留模型权重.
1、文件中保存模型结构和权重参数
1)pytorch模型保存
import torch
torch.save(selfmodel,"save.pt")
2)pytorch模型加载
import torch
torch.load("save.pt")
2、文件只保留模型权重
1)pytorch模型保存
import torch
torch.save(selfmodel.state_dict(),"save.pt")
2)pytorch模型加载
关于区块链技术项目开发威:yy625019
selfmodel.load_state_dict(torch.load("save.pt"))
二、pytorch模型转ONNX模型
1、文件中保存模型结构和权重参数
import torch
torch_model=torch.load("save.pt")#pytorch模型加载
batch_size=1#批处理大小
input_shape=(3,244,244)#输入数据
#set the model to inference mode
torch_model.eval()
x=torch.randn(batch_size,*input_shape)#生成张量
export_onnx_file="test.onnx"#目的ONNX文件名
torch.onnx.export(torch_model,
x,
export_onnx_file,
opset_version=10,
do_constant_folding=True,#是否执行常量折叠优化
input_names=["input"],#输入名
output_names=["output"],#输出名
dynamic_axes={"input":{0:"batch_size"},#批处理变量
"output":{0:"batch_size"}})
注:dynamic_axes字段用于批处理.若不想支持批处理或固定批处理大小,移除dynamic_axes字段即可.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70029947/viewspace-2951811/ ,如需转载,请注明出处,否则将追究法律责任。