H5模型转pb模型转tflite模型

from keras.models import load_model
import tensorflow as tf
import os 
import os.path as osp
from keras import backend as K
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" 


    
def h5_to_pb(h5_model,output_dir,model_name,out_prefix = "yourname_",log_tensorboard = False):
    if osp.exists(output_dir) == False:
        os.mkdir(output_dir)
    out_nodes = []
    
    for i in range(len(h5_model.outputs)):
        out_nodes.append(out_prefix + str(i + 1))
        tf.identity(h5_model.output[i],out_prefix + str(i + 1))
    sess = K.get_session()
    from tensorflow.python.framework import graph_util,graph_io
    init_graph = sess.graph.as_graph_def()
    main_graph = graph_util.convert_variables_to_constants(sess,init_graph,out_nodes)
    graph_io.write_graph(main_graph,output_dir,name = model_name,as_text = False)
    if log_tensorboard:
        from tensorflow.python.tools import import_pb_to_tensorboard
        import_pb_to_tensorboard.import_to_tensorboard(osp.join(output_dir,model_name),output_dir)
    
    
if __name__ == '__main__':
    
    K.set_learning_phase(0)
    
    h5_model= load_model("./yourmodel.h5", compile=False)
    input = h5_model.input
    output = h5_model.output
    
    print('input', input)
    print('output', output)
    
    inputs=["one"]
    outputs=["two"]
    
    h5_to_pb(h5_model, './tflite_model', 'yourname.pb')

    #转换pb模型到tflite模型
    converter = tf.lite.TFLiteConverter.from_frozen_graph('./yourname.pb', inputs, outputs)
    converter.post_training_quantize = True
    converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops=True
    #converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
    #converter.supported_types = [tf.float16]
    
    
    tflite_model = converter.convert()
    open('./yourname.tflite', "wb").write(tflite_model)
    


有可能会报错,类似于:
ValueError: Input 0 of node batch_normalization_1/cond/ReadVariableOp/Switch was passed float from batch_normalization_1/gamma:0 incompatible with expected resource.

需要再loadmodel之前调用:
K.set_learning_phase(0)

 

关注它,获取更多干货:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值