MXNET保存模型结构(.json文件)

今天被这个问题搞得焦头烂额,因为要把mxnet的模型转成caffe必须要有结构文件。

方法就是先要把普通的Block变成HybridBlock,也就是静态化,改写的方法看官方文档:HybridBlocks.
HybridBlock:mxnet.gluon中的一个Block基础类,支持混合模式,即同时支持动态图+静态图。
其具有以下特点:

  • 其所有的children层都必须是HybridBlock。
  • 只有 NDArray和Symbol同时支持的操作才能使用。
  • 运行过程中,操作不能改变。也即操作只有一条路径,不能在执行过程中发生变化。

注意,forward(self, x)函数要改写成hybrid_forward(self, F, x),这个F是什么意思呢?

The hybrid_forward function takes an additional input, F, which stands for a backend. This exploits one awesome feature of MXNet. MXNet has both a symbolic API (mxnet.symbol) and an imperative API (mxnet.ndarray). In this book, so far, we’ve only focused on the latter. Owing to fortuitous historical reasons, the imperative and symbolic interfaces both support roughly the same API. They have many of same functions (currently about 90% overlap) and when they do, they support the same arguments in the same order. When we define hybrid_forward, we pass in F. When running in imperative mode, hybrid_forward is called with F as mxnet.ndarray and x as some ndarray input. When we compile with hybridize, F will be mxnet.symbol and x will be some placeholder or intermediate symbolic value. Once we call hybridize, the net is compiled, so we’ll never need to call hybrid_forward again.

简单来说F可以根据情况在mxnet.ndarray和mxnet.symbol两种数据类型间切换。(普通Block里是mxnet.ndarry)
然后就可以愉快的输出了,可以用下面这段代码也可以用export。

 from mxnet import sym
 import json
 x = sym.var('data')
 print('=== input data holder ===')
 print(x)

 y = model(x)
 print('\n=== the symbolic program of net===')
 print(y)

 y_json = y.tojson()
 print('\n=== the according json definition===')
 print(y_json)
 filename='model.json'
 with open(filename,'w') as file_obj:
     json.dump(y_json,file_obj)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值