将batchnorm(TensorFlow)的is_training转为False

时间:2017-09-30 00:14:49

标签: python machine-learning tensorflow deep-learning conv-neural-network

我希望在训练后将模型的is_training状态转换为False,我该怎么做?

net = tf.layers.conv2d(inputs = features, filters = 64, kernel_size = [3, 3], strides = (2, 2), padding = 'same')
net = tf.contrib.layers.batch_norm(net, is_training = True)
net = tf.nn.relu(net)
net = tf.reshape(net, [-1, 64 * 7 * 7]) #
net = tf.layers.dense(inputs = net, units = class_num, kernel_initializer = tf.contrib.layers.xavier_initializer(), name = 'regression_output')

#......
#after training

saver = tf.train.Saver()
saver.save(sess, 'reshape_final.ckpt')
tf.train.write_graph(sess.graph.as_graph_def(), "", 'graph_final.pb')

我保存后如何将警报的is_training变为False

我尝试过像 tensorflow batchnorm turn of training tensorflow change state 这样的关键字,但是找不到怎么做。

编辑1:

感谢@Maxim解决方案,它可以工作,但是当我尝试冻结图表时,会出现另一个问题。

命令:

python3 ~/.keras2/lib/python3.5/site-packages/tensorflow/python/tools/freeze_graph.py --input_graph=graph_final.pb --input_checkpoint=reshape_final.ckpt --output_graph=frozen_graph.pb --output_node_names=regression_output/BiasAdd

python3 ~/.keras2/lib/python3.5/site-packages/tensorflow/python/tools/optimize_for_inference.py --input frozen_graph.pb --output opt_graph.pb --frozen_graph True --input_names input --output_names regression_output/BiasAdd

~/Qt/3rdLibs/tensorflow/bazel-bin/tensorflow/tools/graph_transforms/transform_graph --in_graph=opt_graph.pb --out_graph=fused_graph.pb --inputs=input --outputs=regression_output/BiasAdd --transforms="fold_constants sort_by_execution_order fold_batch_norms fold_old_batch_norms"

执行transform_graph后,会弹出错误消息

"您必须为占位符张量'培训'提供一个值。用dtype bool"

我通过以下代码保存图表:

sess.run(loss, feed_dict={features : train_imgs, x : real_delta, training : False})
saver = tf.train.Saver()
saver.save(sess, 'reshape_final.ckpt')
tf.train.write_graph(sess.graph.as_graph_def(), "", 'graph_final.pb')

编辑2:

将占位符更改为“变量”,但转换后的图形无法由opencv dnn加载。

更改

training = tf.placeholder(tf.bool, name='training')

training = tf.Variable(False, name='training', trainable=False)

1 个答案:

答案 0 :(得分:2)

您应该为模式定义placeholder变量(可以是布尔值或字符串),并在训练和测试期间将不同的值传递给session.run。示例代码:

x = tf.placeholder('float32', (None, 784), name='x')
y = tf.placeholder('float32', (None, 10), name='y')
phase = tf.placeholder(tf.bool, name='phase')
...

# training (phase = 1)
sess.run([loss, accuracy], 
         feed_dict={'x:0': mnist.train.images,
                    'y:0': mnist.train.labels,
                    'phase:0': 1})
...

# testing (phase = 0)
sess.run([loss, accuracy],
         feed_dict={'x:0': mnist.test.images,
                    'y:0': mnist.test.labels,
                    'phase:0': 0})

您可以在this post中找到完整的代码。