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 框架图
随机推荐
- mybatis-generator扩展教程系列 -- 自定义generatorConfig.xml参数
http://blog.csdn.net/shadowsick/article/details/53413235
- 笔记:IIFE 立即执行的函数表达式 +function ($) { }(window.jQuery);
在Bootstrap源码(具体请看<Bootstrap源码解析1>)和其他jQuery插件经常看到如下的写法: +function ($) { }(window.jQuery); 这种写法 ...
- Update Node.js Package.json
Update the latest package while using node.js, follow the command as following. npm i -g npm-check-u ...
- 记一次spring里bean无法注入的历程
应用启动的时候失败,看了下异常,是这个---NoUniqueBeanDefinitionException. 大家都知道,这是因为有俩个类型相同的实例,在被注入的时候,spring不知道该用哪个. 但 ...
- python操作Hbase
本地操作 启动thrift服务:./bin/hbase-daemon.sh start thrift hbase模块产生: 下载thrfit源码包:thrift-0.8.0.tar.gz 解压安装 . ...
- python之函数2
Python 函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.你已经知道Python提供了许多内建函数,比如print().但你也 ...
- Excel函数vlookup
最近整理业务文档,需要用到excel,按照教程,操作了20来分钟,却得不到结果. 看了视频,才知道,vlookup仅限关联选中区域的第一列关联,把要关联的行拷贝到第一列,解决. https://www ...
- cxgrid显示海量数据
cxgrid显示海量数据 在默认情况下,cxgrid显示几万条以上的数据会很慢.怎么办? 交下面的属性设为TRUE以后,速度飞快. 但速度是快了,自动计算列的合计值这些功能却失效了,正所谓有得必有失!
- 在mac下配置Andriod环境 包括eclipse和andriod studio
1 前提 已经配置好了java的环境,课上要使用andriod开发. 2 步骤 2.1 eclipse 2.1.1先安装adt,adt是一个在eclipse中开发andriod的插件.由于墙,我是从其 ...
- 设计模式:visitor
拜访者模式(visitor)适用于对复杂结构体进行解析的场景. 所谓复杂结构体,是指包含多个子元素的对象,比如集合,树,图,或者组合对象--.结构体中的每个元素,包括结构体本身实现接口: Elemen ...