torch模型转tensorflow模型汇总

本文详细介绍了如何将训练好的PyTorch模型转换为TensorFlow模型,包括使用onnx-tf和pytorch2keras模块的方法,以及在训练过程中两个框架之间的相互调用。还提到了转换过程中需要注意的细节,如数据归一化、权重维度、BN层的处理等,以减少转换带来的偏差。
摘要由CSDN通过智能技术生成

torch模型转tensorflow模型汇总

1,针对已训练的模型,有两种思路
(1) 通过onnx-tf模块转换:
a,具体流程:
pth=>onnx=>pb
b,环境配置:
conda create -n pth_pb python=3.7
pip install tensorflow2.1.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install tensorflow-addons
0.9.1 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install onnx-tf1.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install onnx
1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
conda install pytorch torchvision #(这里我用的版本为pytorch1.4, torchvision0.5.0)
c,代码:
pth转onnx

import torchvision
import torch.onnx
import torch.nn as nn
def resnet50():
    model = torchvision.models.resnet50(pretrained=False)
    model.fc = nn.Linear(2048, 2)
    return model
model = resnet50()
model = torch.nn.DataParallel(model)
pthfile = my.pth'
loaded_model = torch.load(pthfile, map_location='cpu')
model.load_state_dict(loaded_model['state_dict'])
input = torch.randn(1, 3, 200, 200)
input_names = ["head_input"]
output_names = ["output"]
onnx_filename = “my.onnx"
torch.onnx.export(model.module, input, onnx_filename, verbose=True, input_names=input_names, output_names=output_names)

参数 input_names表示模型的输入参数(随便起名字),output_names表示输出名字

onnx转pb

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值