(原)torch模型转pytorch模型
2017-11-15 15:38
691 查看
转载请注明出处:
http://www.cnblogs.com/darkknightzh/p/7839263.html
目前使用的torch模型转pytorch模型的程序为:
https://github.com/clcarwin/convert_torch_to_pytorch
该程序中,常见的模型都可以转换,但是对于torch中为BatchNormalization的则会提示出错:
Not Implement BatchNormalization
torch中的SpatialBatchNormalization对应于输入为4d的特征(batchsize*featdim*featHeight*featWidth),对应于pytorch中的nn.BatchNorm2d。
而torch中的BatchNormalization对应于输入为2d的特征(batchsize*featdim),对应于pytorch中的nn.BatchNorm1d。
因而修改方法很简单:
1. 在convert_torch.py的74行(elif name == 'ReLU':)之前添加:
2. 在convert_torch.py的(未修改前的)175行(elif name == 'ReLU':)之前添加:
3. 在convert_torch.py的(未修改前的)245行(s = map(lambda x: x.replace(',(0, 0),ceil_mode=False),#MaxPool2d',')'),s))之前添加:
经过上述修改后,torch模型中含有BatchNormalization,转换到pytorch后的模型性能和转换前的模型性能一致。
顺便说一下,2天前更新的该程序,添加了BatchNorm3d的支持,但是在243、244行之后,并没有增加BatchNorm3d的相关代码,不清楚是否会有问题。我这边没有用到BatchNorm3d,因而没有测试。
另一方面,上面的3步中,我是根据BatchNorm2d去修改,没有测试如果不修改某一步(如第3步),程序是否会有问题。反正都改了,模型没有问题。。。
http://www.cnblogs.com/darkknightzh/p/7839263.html
目前使用的torch模型转pytorch模型的程序为:
https://github.com/clcarwin/convert_torch_to_pytorch
该程序中,常见的模型都可以转换,但是对于torch中为BatchNormalization的则会提示出错:
Not Implement BatchNormalization
torch中的SpatialBatchNormalization对应于输入为4d的特征(batchsize*featdim*featHeight*featWidth),对应于pytorch中的nn.BatchNorm2d。
而torch中的BatchNormalization对应于输入为2d的特征(batchsize*featdim),对应于pytorch中的nn.BatchNorm1d。
因而修改方法很简单:
1. 在convert_torch.py的74行(elif name == 'ReLU':)之前添加:
elif name == 'BatchNormalization': n = nn.BatchNorm1d(m.running_mean.size(0), m.eps, m.momentum, m.affine) copy_param(m,n) add_submodule(seq,n)
2. 在convert_torch.py的(未修改前的)175行(elif name == 'ReLU':)之前添加:
elif name == 'BatchNormalization': s += ['nn.BatchNorm1d({},{},{},{}),#BatchNorm1d'.format(m.running_mean.size(0), m.eps, m.momentum, m.affine)]
3. 在convert_torch.py的(未修改前的)245行(s = map(lambda x: x.replace(',(0, 0),ceil_mode=False),#MaxPool2d',')'),s))之前添加:
s = map(lambda x: x.replace(',1e-05,0.1,True),#BatchNorm1d',')'),s) s = map(lambda x: x.replace('),#BatchNorm1d',')'),s)
经过上述修改后,torch模型中含有BatchNormalization,转换到pytorch后的模型性能和转换前的模型性能一致。
顺便说一下,2天前更新的该程序,添加了BatchNorm3d的支持,但是在243、244行之后,并没有增加BatchNorm3d的相关代码,不清楚是否会有问题。我这边没有用到BatchNorm3d,因而没有测试。
另一方面,上面的3步中,我是根据BatchNorm2d去修改,没有测试如果不修改某一步(如第3步),程序是否会有问题。反正都改了,模型没有问题。。。
相关文章推荐
- 利用pytorch构建简单的CNN模型(二)
- PyTorch中使用预训练的模型初始化网络的一部分参数
- 计算一下pytorch中Resnet34模型前传一次所需要的时间
- Pytorch——把模型的所有参数的梯度清0
- pytorch入门(3)pytorch-seq2seq模型
- pytorch构建网络模型的4种方法
- (原+译)pytorch中保存和载入模型
- (继)pytorch中的pretrain模型网络结构修改
- pytorch中的pre-train函数模型或者旧的模型的引用及修改(增减网络层,修改某层参数等) finetune微调等
- pytorch学习-迁移模型
- pytorch finetune模型
- 浅谈将Pytorch模型从CPU转换成GPU
- pytorch中获取模型input/output shape
- pytorch 如何加载部分预训练模型
- PyTorch(7)——模型的训练和测试、保存和加载
- PyTorch快速入门教程四(cnn:卷积神经网络 )
- PyTorch no longer supports this GPU because it is too old.
- pytorch 中的 backward()
- PyTorch - 打印梯度
- pytorch Dropout过拟合