我想在训练后将模型的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')
保存后,如何将batchnorm的
is_training
转换为False
?我尝试了诸如tensorflow batchnorm轮训,tensorflow更改状态之类的关键字,但找不到解决方法。
编辑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输入占位符张量'training'的值”
我通过以下代码保存图形:
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:
将占位符更改为Variable可以使用,但是转换后的图形无法由opencv dnn加载。
更改
training = tf.placeholder(tf.bool, name='training')
至
training = tf.Variable(False, name='training', trainable=False)
最佳答案
您应该为模式定义一个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中找到完整的代码。