tensorflow 优化图
当我们把训练好的tensorflow训练图拿来进行预测时,会有多个训练时生成的节点,这些节点是不必要的,我们需要在预测的时候进行删除。
下面以bert的图为例,进行优化
def optimize_graph(self, checkpoint_file, model_config):
import json
tf = self.import_tf()
from tensorflow.python.tools.optimize_for_inference_lib import optimize_for_inference config = tf.ConfigProto(device_count={'GPU': 0}, allow_soft_placement=True) init_checkpoint = checkpoint_file with tf.gfile.GFile(model_config, 'r') as f:
bert_config = modeling.BertConfig.from_dict(json.load(f)) input_ids = tf.placeholder(tf.int32, (None, MAX_SEQ_LENGTH), 'input_ids')
input_mask = tf.placeholder(tf.int32, (None, MAX_SEQ_LENGTH), 'input_mask')
input_type_ids = tf.placeholder(tf.int32, (None, MAX_SEQ_LENGTH), 'input_type_ids') import contextlib
jit_scope = contextlib.suppress with jit_scope():
input_tensors = [input_ids, input_mask, input_type_ids]
model = modeling.BertModel(
config=bert_config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=input_type_ids,
use_one_hot_embeddings=False) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) # get output tensor
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
reader = tf.train.NewCheckpointReader(init_checkpoint)
output_weights = reader.get_tensor('output_weights')
output_bias = reader.get_tensor('output_bias')
output_layers = model.get_pooled_output()
pooled = tf.nn.softmax(tf.nn.bias_add(tf.matmul(output_layers, output_weights, transpose_b=True),
output_bias))
pooled = tf.identity(pooled, 'final_encodes') output_tensors = [pooled]
tmp_g = tf.get_default_graph().as_graph_def() # write graph to file
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
tmp_g = tf.graph_util.convert_variables_to_constants(sess, tmp_g, [n.name[:-2] for n in output_tensors])
dtypes = [n.dtype for n in input_tensors]
tmp_g = optimize_for_inference(
tmp_g,
[n.name[:-2] for n in input_tensors],
[n.name[:-2] for n in output_tensors],
[dtype.as_datatype_enum for dtype in dtypes],
False) import tempfile
tmp_file = tempfile.NamedTemporaryFile('w', delete=False, dir=r'optimize').name
with tf.gfile.GFile(tmp_file, 'wb') as f:
f.write(tmp_g.SerializeToString()) return tmp_file
返回一个gfile类型的文件,我们可以像原来导入模型文件时,恢复图,不过这个图是优化过的。
tensorflow 优化图的更多相关文章
- TensorFlow的图切割模块——Graph Partitioner
背景 [作者:DeepLearningStack,阿里巴巴算法工程师,开源TensorFlow Contributor] 在经过TensorFlow的Placer策略模块调整之后,下一步就是根据Pla ...
- 现代英特尔® 架构上的 TensorFlow* 优化——正如去年参加Intel AI会议一样,Intel自己提供了对接自己AI CPU优化版本的Tensorflow,下载链接见后,同时可以基于谷歌官方的tf版本直接编译生成安装包
现代英特尔® 架构上的 TensorFlow* 优化 转自:https://software.intel.com/zh-cn/articles/tensorflow-optimizations-on- ...
- TensorFlow从0到1之TensorFlow优化器(13)
高中数学学过,函数在一阶导数为零的地方达到其最大值和最小值.梯度下降算法基于相同的原理,即调整系数(权重和偏置)使损失函数的梯度下降. 在回归中,使用梯度下降来优化损失函数并获得系数.本节将介绍如何使 ...
- TensorFlow优化器及用法
TensorFlow优化器及用法 函数在一阶导数为零的地方达到其最大值和最小值.梯度下降算法基于相同的原理,即调整系数(权重和偏置)使损失函数的梯度下降. 在回归中,使用梯度下降来优化损失函数并获得系 ...
- TensorFlow优化器浅析
本文基于tensorflow-v1.15分支,简单分析下TensorFlow中的优化器. optimizer = tf.train.GradientDescentOptimizer(learning_ ...
- tensorflow优化器-【老鱼学tensorflow】
tensorflow中的优化器主要是各种求解方程的方法,我们知道求解非线性方程有各种方法,比如二分法.牛顿法.割线法等,类似的,tensorflow中的优化器也只是在求解方程时的各种方法. 比较常用的 ...
- tensorflow:图(Graph)的核心数据结构与通用函数(Utility function)
Tensorflow一些常用基本概念与函数(2) 1. 图(Graph)的核心数据结构 tf.Graph.__init__:建立一个空图: tf.Graph.as_default():一个将某图设置为 ...
- Tensorflow 优化学习
# coding: utf-8 import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data pr ...
- tensorflow 框架图
随机推荐
- js基础学习笔记(零七)
indexOf() 方法 返回某个指定的字符串值在字符串中首次出现的位置. 语法: stringObject.indexOf(substring, startpos) 参数说明: 注意:如果要检索的字 ...
- classmethod,staticmethod
'''1 绑定方法: 在类内部定义的函数,默认就是给对象来用,而且是绑定给对象用的,称为对象的绑定方法 绑定对象的方法特殊之处: 应该由对象来调用,对象来调用,会自动将对象当作第一个参数传入 绑定到类 ...
- 可以替代alert 的漂亮的Js弹框
1 基本弹框 2确认框 3又一种确认框 4带返回的弹框 5带返回的探矿 6 6 一切尽在 http://t4t5.github.io/sweetalert/
- Lib作为“静态库”与“动态库”中的区别
Lib作为“静态库”与“动态库”中的区别 0. 前言: 什么是静态连接库: 静态库在链接阶段,会将汇编生成的目标文件.o与引用到的库一起链接打包到可执行文件中.因此对应的链接方式称为静态链接. 为什么 ...
- 关于QT建立项目中遇到的相关问题的处理办法
关于QT建立项目中遇到的相关问题的处理办法 1.在QTCreater中新建一个空的工程时,第一次运行会抱一个错误,如下: -1: error: LNK1123: 转换到 COFF 期间失败: 文件无效 ...
- 将一个浮点数转换成人民币读法字符串(java)
public class Num2Rmb { private String[] hanArr = {"零" , "壹" , "贰&qu ...
- AngularJS $observe $watch
$observe $watch都可以用来监听值的变化,但是他们有显著的区别.$observe是用来监视DOM属性值的变化,而 $watch监视scope属性值的变化.AngularJS中的监听,都知道 ...
- unity 人工智能AI,装备解锁临时笔记
A*算法的一种改进设想:1.如何让角色到达目标点的过程中更加平滑:获取一串到达目标点的网格串之后,就实时用带形状的物理射线检测能否直接到达下一个目标点的再下一个目标点,如果能到达,那么直接朝该方向运动 ...
- .net4.0 请求HTTPS出错:未能创建 SSL/TLS 安全通道
两种方法: 1.在代码中修改 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocol ...
- 深入解析SQL Server高可用镜像实现原理
本文来自网易云社区 SQL Server 是windows平台.NET架构下标配数据库解决方案,与Oracle.MySQL共同构成了DB-Engines Ranking的第一阵营,在国内外企业市场中有 ...