读书wordpress,安徽关键词seo,2008服务器网站,闵行区seo快速排名优化哪里好摘要基于tensorflow训练的模型一般被保存为ckpt形式的文件#xff0c;随着当前深度学习模型网络越来越大#xff0c;对应模型也会非常大。当对外提供服务的时候#xff0c;如果采用ckpt的形式#xff0c;服务进程被调起来非常困难#xff0c;且推理服务一般速度也较慢(会达…摘要基于tensorflow训练的模型一般被保存为ckpt形式的文件随着当前深度学习模型网络越来越大对应模型也会非常大。当对外提供服务的时候如果采用ckpt的形式服务进程被调起来非常困难且推理服务一般速度也较慢(会达到100ms以上一次推理)。所以使用固化后的模型进行推理服务非常必要模型大小得到压缩服务时耗也得到大幅度降低。本文介绍几种常见的模型固化方法。1 session模式的模型先行训练好check point形式的模型文件之所以这里区分session模式因为这种模式使用者比较容易设置name_scope以及Tensor的命名特别是输入、输出节点的名称这样对于后面的固化非常重要。代码如下#!/usr/bin/env python# codingutf-8from __future__ import print_functionimport ossystimeimport numpy as npimport tensorflow as tfos.environ[CUDA_DEVICE_ORDER] PCI_BUS_IDos.environ[CUDA_VISIBLE_DEVICES] 7import tensorflow.contrib.slim as slimfrom tensorflow.python.framework import graph_util#此文件可以把ckpt模型转为pb模型def freeze_graph(input_checkpoint,output_graph): # checkpoint tf.train.get_checkpoint_state(model_folder) # # input_checkpoint checkpoint.model_checkpoint_path # output_node_names score_student/output_student saver tf.train.import_meta_graph(input_checkpoint .meta, clear_devicesTrue) graph tf.get_default_graph()# input_graph_def graph.as_graph_def()# with tf.Session() as sess: saver.restore(sess, input_checkpoint) output_graph_def graph_util.convert_variables_to_constants( sesssess, input_graph_definput_graph_def,# :sess.graph_def output_node_namesoutput_node_names.split(,), variable_names_whitelistNone,variable_names_blacklistNone)# with tf.gfile.GFile(output_graph, wb) as f: # f.write(output_graph_def.SerializeToString()) # print(%d ops in the final graph. % len(output_graph_def.node))#input_checkpoint/data/.../best_validationout_pb_path/data/.../pbmodel/frozen_model_for_best_validation20190821.pbfreeze_graph(input_checkpoint, out_pb_path)2 estimator形式的模型包括TPUEstimator形式最常见的就是BERT模型[1]了你很难去找里面的各种tensor的变量本人亲自尝试使用tensorboard进行查找。【当然使用一次迁移学习转换一下形式也是可以解决这个问题的】这里提供另外一种简单的解决方法代码如下【相关表达方式还有好几种】首先使用正常模型训练一个ckpt形式的模型然后进行转化pb格式固化。在bert代码中注释掉原来的train步骤#estimator.train(input_fntrain_input_fn, max_stepsnum_train_steps)#定义里面的输入数据名称及shapefeature_spec { input_ids: tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64), input_mask: tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64), segment_ids: tf.FixedLenFeature([FLAGS.max_seq_length], tf.int64), start_ps: tf.FixedLenFeature([], tf.int64),#debuluoyi end_ps: tf.FixedLenFeature([], tf.int64),#debuluoyi label_ids: tf.FixedLenFeature([], tf.int64), }#固化转换 receiver_fntf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)estimator._export_to_tpu Falseprint(begin to export_savedmodel el model.pb) estimator.export_savedmodel(/data/.../pbmodel/bert_el_model20191023_2_pbmodel,serving_input_receiver_fn receiver_fn)3 小结模型固化对于对外提供服务很重要另外还有一个很重要的点就是接下来进行压缩压缩很多基于pb固化模型进行也有多种方便由此体现模型固化在实际算法工程中是非常重要且常见的技术点一般能够将模型大小压缩数倍服务调起更加轻便基于GPU的推理时间也能节约数倍。参考文献[1] https://github.com/google-research/bertgoogle-research/bertgithub.com[2] 本人GitHubdebuluoyi - Overviewgithub.com