tensorflow - 使用指数移动平均线冻结 TensorFlow 模型会给出不同的推断概率
问题描述
我正在尝试冻结基于 inception-v3 的模型并运行推理。但是,与原始模型相比,使用冻结模型得到的推断概率不一致。
我发现差异来自训练和推理中的指数移动平均线 (EMA)。当我在两个模型中关闭 EMA 时,我得到相同的概率(差异 < 1e-5)。
我正在使用的冻结代码:
from __future__ import print_function
import tensorflow as tf
from nets.inception_v3 import inception_v3, inception_v3_arg_scope
from tensorflow.python.framework import graph_util
import sys
slim = tf.contrib.slim
checkpoint_file = '/my/model'
with tf.Graph().as_default() as graph:
images = tf.placeholder(shape=[None, 100, 221, 6], dtype=tf.float32, name = 'input')
with slim.arg_scope(inception_v3_arg_scope()):
logits, end_points = inception_v3(images, num_classes = 3, create_aux_logits = False, is_training = False)
variables_to_restore = slim.get_variables_to_restore()
MOVING_AVERAGE_DECAY = 0.9999
variable_averages = tf.train.ExponentialMovingAverage(
MOVING_AVERAGE_DECAY)
for var in variables_to_restore:
tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, var)
variables_to_restore = variable_averages.variables_to_restore() #This line is commented if EMA is turned off
saver = tf.train.Saver(variables_to_restore)
#Setup graph def
input_graph_def = graph.as_graph_def()
output_node_names = "InceptionV3/Predictions/Reshape_1"
output_graph_name = "./frozen_inception_v3_new_100_221_ema.pb"
with tf.Session() as sess:
saver.restore(sess, checkpoint_file)
#Exporting the graph
print ("Exporting graph...")
output_graph_def = graph_util.convert_variables_to_constants(
sess,
input_graph_def,
output_node_names.split(","))
with tf.gfile.GFile(output_graph_name, "wb") as f:
f.write(output_graph_def.SerializeToString())
EMA 部分与原始模型的代码相同。
我是否错误地冻结了 EMA 推理图?
解决方案
问题解决了。我使用的 EMA 部分
MOVING_AVERAGE_DECAY = 0.9999
variable_averages = tf.train.ExponentialMovingAverage(
MOVING_AVERAGE_DECAY)
for var in variables_to_restore:
tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, var)
variables_to_restore = variable_averages.variables_to_restore()
是不正确的。如果我删除
for var in variables_to_restore:
tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, var)
现在结果很好。
推荐阅读
- javascript - Vue中的动态最小长度和最大长度
- php - 删除具有重复值的数组记录
- php - 在 PHP 中通过 d-link GSM 调制解调器发送短信
- c# - Xamarin 按钮在第二次单击时起作用
- node.js - 如何公开托管 OHIF 查看器
- python-3.x - 如何使用 Python 将提取的电子邮件 ID 保存在 Excel 工作表中,也可以连续保存?
- cors - CORS – 跨域请求被阻止 – 'Access-Control-Allow-Origin' 标头包含无效值
- memory - Fortran 90:信号 SIGSEGV:分段错误 - 无效的内存引用
- android - 是否可以在达到某个值(0:00)后停止通知计时器?
- windows-10 - 如何在 Windows 10 中将分区完全备份到 Microsoft OneDrive?