具有导入图定义和指数移动平均值的Tensorflow Colorate问题
我对GraphDef中的colocate信息有疑问 以下是我遵循的高级步骤具有导入图定义和指数移动平均值的Tensorflow Colorate问题,tensorflow,Tensorflow,我对GraphDef中的colocate信息有疑问 以下是我遵循的高级步骤 使用tf.Train.ExponentialMovingAverage训练估计器,并将EMA预测用于预测模式 导出到SavedModel 从SavedModel重新加载GraphDef,并使用extract\u sub\u graph 使用Freeze\u graph\u with_def_protos 在步骤4。我得到一个错误ValueError:节点'layer/kernel/ExponentialMovingAve
tf.Train.ExponentialMovingAverage
训练估计器
,并将EMA预测用于预测模式SavedModel
SavedModel
重新加载GraphDef
,并使用extract\u sub\u graph
Freeze\u graph\u with_def_protos
ValueError:节点'layer/kernel/ExponentialMovingAverage'期望与未知节点'layer/kernel'共定位。
下面是我用来训练模型的代码
#train.py
导入日志记录
从pathlib导入路径
导入系统
导入tensorflow作为tf
def ema_getter(ema):
def_ema_getter(getter,name,*args,**kwargs):
var=getter(名称,*args,**kwargs)
均线风险=均线平均值(风险值)
如果ema\U var else var返回ema\U var
返回(ema)getter
def型号(特征、标签、模式、参数):
#pylint:disable=未使用的参数
“”“虚拟模型\u fn”“”
如果存在(功能、指令):#用于服务
特征=特征['feature']
预测=tf.layers.dense(特征,1,name=“层”)
预测=tf.identity(预测,name=“预测”)
ema=tf.训练指数移动平均值(1.0)
变量=tf.get\u集合(
tf.GraphKeys.TRAINABLE_VARIABLES,tf.get_variable_scope().name)
ema_op=ema.apply(变量)
使用tf.variable\u scope(tf.get\u variable\u scope(),reuse=True,custom\u getter=ema\u getter(ema)):
预测\u ema=tf.layers.dense(特征,1,name=“层”)
预测值=tf.identity(预测值,name=“预测值”)
如果mode==tf.estimator.ModeKeys.PREDICT:
preds={
“预测”:预测
}
返回tf.estimator.EstimatorSpec(模式,预测=预测)
其他:
损失=tf.nn.l2_损失(预测-标签)
如果模式==tf.estimator.ModeKeys.EVAL:
返回tf.estimator.estimator规范(
模式,损耗=损耗)
elif模式==tf.estimator.ModeKeys.TRAIN:
训练op=tf.train.AdamOptimizer(学习率=0.5)。最小化(
丢失,全局步骤=tf.train.get\u全局步骤()
返回tf.estimator.estimator规范(
模式,损失=损失,列车运行=tf.组([列车运行,ema运行])
其他:
引发未实现的错误()
def传动系_发电机_fn():
对于范围(100)内的数字:
产量[数量,数量],[2*数量]
def序列输入\ U fn():
形状,类型=(2,1),(tf.float32,tf.float32)
dataset=tf.data.dataset.from_生成器(
列车发电机,输出类型=类型,输出形状=形状)
数据集=数据集。批处理(20)。重复(200)
返回数据集
def服务_输入_接收器_fn():
“”“为输入提供服务\fn从占位符生成功能”
退换商品
-------
tf.estimator.export.ServingingInputReceiver
"""
number=tf.placeholder(dtype=tf.float32,shape=[None,1],name='number')
接收器\张量={'number':number}
features=tf.tile(数字,倍数=[1,2])
返回tf.estimator.export.ServingInputReceiver(特征、接收器张量)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#伐木
路径('model').mkdir(exist\u ok=True)
tf.logging.set_详细信息(logging.INFO)
处理程序=[
logging.FileHandler('model/train.log'),
logging.StreamHandler(sys.stdout)
]
logging.getLogger('tensorflow')。handlers=handlers
#训练估计器
估计量=tf.estimator.estimator(模型_fn,'model',params={})
列车估计器(列车输入)
#出口
估算器。导出保存的模型(“保存的模型”,服务于输入接收器)
以及我用来优化图形的代码
#optimize.py
从pathlib导入路径
导入tensorflow作为tf
从tensorflow.python.tools.freeze_graph导入带有def_protos的freeze_graph_
从tensorflow.python.framework.graph\u util导入提取子图
从tensorflow.core.framework.graph_pb2导入GraphDef
def优化和导出(导出目录:str,输出:str):
使用tf.Session()作为sess:
g=tf.saved_model.loader.load(sess,[“service”]、export_dir)
推理图=提取子图(g.graph\u def,[“预测图”])
g=冻结图(带定义协议)(
推理图,
没有一个
没有一个
"预测",,
没有一个
没有一个
没有一个
没有一个
没有一个
输入\保存\模型\目录=导出\目录,
已保存的_模型_标记=[“服务”],
)
写入图(g,logdir=str(Path(output).parent),name=Path(output).name,as_text=False)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
export_dir=str(已排序(路径('saved_model').glob('*'))[0])
打印(f“从{export_dir}重新加载”)
优化和导出(导出目录“保存的模型/最终版”)
我的理解是tf.train.ExponentialMovingAverage
在节点(原始版本和EMA版本)之间添加了托管信息
注意:共定位似乎意味着“这些变量应该位于同一个设备上”
这个冒号信息出现在图形protobuf(SavedModel导出)中
提取子图时,仅保留变量的EMA版本,但保留了托管信息,这在创建图时会导致问题,该图尝试查找原始的托管变量(不再存在)
我找到了一种方法,手动修改protobuf并用
def优化和导出(导出目录:str,输出:str):
使用tf.Session()作为sess:
g=tf.saved_model.loader.load(sess,[“service”]、export_dir)
在里面