tf.layers.batch_normalization 大测试错误
Posted
技术标签:
【中文标题】tf.layers.batch_normalization 大测试错误【英文标题】:tf.layers.batch_normalization large test error 【发布时间】:2017-08-31 06:33:30 【问题描述】:我正在尝试使用批量标准化。我尝试在 mnist 的简单卷积网络上使用 tf.layers.batch_normalization。
我的训练步精度很高 (>98%),但测试精度非常低 (
我的代码
# Input placeholders
x = tf.placeholder(tf.float32, [None, 784], name='x-input')
y_ = tf.placeholder(tf.float32, [None, 10], name='y-input')
is_training = tf.placeholder(tf.bool)
# inut layer
input_layer = tf.reshape(x, [-1, 28, 28, 1])
with tf.name_scope('conv1'):
#Convlution #1 ([5,5] : [28x28x1]->[28x28x6])
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=6,
kernel_size=[5, 5],
padding="same",
activation=None
)
#Batch Norm #1
conv1_bn = tf.layers.batch_normalization(
inputs=conv1,
axis=-1,
momentum=0.9,
epsilon=0.001,
center=True,
scale=True,
training = is_training,
name='conv1_bn'
)
#apply relu
conv1_bn_relu = tf.nn.relu(conv1_bn)
#apply pool ([2,2] : [28x28x6]->[14X14X6])
maxpool1=tf.layers.max_pooling2d(
inputs=conv1_bn_relu,
pool_size=[2,2],
strides=2,
padding="valid"
)
with tf.name_scope('conv2'):
#convolution #2 ([5x5] : [14x14x6]->[14x14x16]
conv2 = tf.layers.conv2d(
inputs=maxpool1,
filters=16,
kernel_size=[5, 5],
padding="same",
activation=None
)
#Batch Norm #2
conv2_bn = tf.layers.batch_normalization(
inputs=conv2,
axis=-1,
momentum=0.999,
epsilon=0.001,
center=True,
scale=True,
training = is_training
)
#apply relu
conv2_bn_relu = tf.nn.relu(conv2_bn)
#maxpool2 ([2,2] : [14x14x16]->[7x7x16]
maxpool2=tf.layers.max_pooling2d(
inputs=conv2_bn_relu,
pool_size=[2,2],
strides=2,
padding="valid"
)
#fully connected 1 [7*7*16 = 784 -> 120]
maxpool2_flat=tf.reshape(maxpool2,[-1,7*7*16])
fc1 = tf.layers.dense(
inputs=maxpool2_flat,
units=120,
activation=None
)
#Batch Norm #2
fc1_bn = tf.layers.batch_normalization(
inputs=fc1,
axis=-1,
momentum=0.999,
epsilon=0.001,
center=True,
scale=True,
training = is_training
)
#apply reliu
fc1_bn_relu = tf.nn.relu(fc1_bn)
#fully connected 2 [120-> 84]
fc2 = tf.layers.dense(
inputs=fc1_bn_relu,
units=84,
activation=None
)
#apply relu
fc2_bn_relu = tf.nn.relu(fc2)
#fully connected 3 [84->10]. Output layer with softmax
y = tf.layers.dense(
inputs=fc2_bn_relu,
units=10,
activation=None
)
#loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
tf.summary.scalar('cross entropy', cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy',accuracy)
#merge summaries and init train writer
sess = tf.Session()
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(log_dir + '/train' ,sess.graph)
test_writer = tf.summary.FileWriter(log_dir + '/test')
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess.run(init)
with sess.as_default():
def get_variables_values():
variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
values =
for variable in variables:
values[variable.name[:-2]] = sess.run(variable, feed_dict=
x:batch[0], y_:batch[1], is_training:True
)
return values
for i in range(t_iter):
batch = mnist.train.next_batch(batch_size)
if i%100 == 0: #test-set summary
print('####################################')
values = get_variables_values()
print('moving variance is:')
print(values["conv1_bn/moving_variance"])
print('moving mean is:')
print(values["conv1_bn/moving_mean"])
print('gamma is:')
print(values["conv1_bn/gamma/Adam"])
print('beta is:')
print(values["conv1_bn/beta/Adam"])
summary, acc = sess.run([merged,accuracy], feed_dict=
x:mnist.test.images, y_:mnist.test.labels, is_training:False
)
else:
summary, _ = sess.run([merged,train_step], feed_dict=
x:batch[0], y_:batch[1], is_training:True
)
if i%10 == 0:
train_writer.add_summary(summary,i)
我认为问题在于moving_mean/var 没有被更新。 我在运行期间打印了moving_mean/var,我得到: 移动方差为: [ 1. 1. 1. 1. 1. 1.] 移动均值是: [ 0. 0. 0. 0. 0. 0.] 伽玛是: [-0.00055969 0.00164391 0.00163301 -0.00206227 -0.00011434 -0.00070161] 贝塔是: [-0.00232835 -0.00040769 0.00114277 -0.0025414 -0.00049697 0.00221556]
有人知道我做错了什么吗?
【问题讨论】:
嗨,MrG,你能告诉我你的测试代码吗?我和你有同样的问题,总是使用 tf.layers.batch_normalization 预测常数。 【参考方案1】:tf.layers.batch_normalization
添加到更新均值和方差的操作不会自动添加为火车操作的依赖项 - 因此,如果您不做任何额外的操作,它们将永远不会运行。
(不幸的是,文档目前没有提到这一点。我正在打开一个关于它的问题。)
幸运的是,更新操作很容易进行,因为它们已添加到 tf.GraphKeys.UPDATE_OPS
集合中。然后你可以手动运行额外的操作:
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
sess.run([train_op, extra_update_ops], ...)
或者将它们添加为您的训练操作的依赖项,然后正常运行您的训练操作:
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(extra_update_ops):
train_op = optimizer.minimize(loss)
...
sess.run([train_op], ...)
【讨论】:
感谢您的帮助.. 我看到帖子详细说明了批处理规范仍在 contrib 中时的类似方法——当他们迁移到 tf.layers 时,我错误地认为它是“固定的”有什么理由不让更新均值和方差成为默认行为? 我同意,这有点不方便。我怀疑这可能与汇总操作的情况类似:通过图流向损失函数的数据根本不依赖于这些操作,因此必须单独调用它们。 谢谢!如果 TF 文档注意到这一点,将会非常有帮助。 在保存和恢复模型的时候需要做一些特别的事情吗?我有一个模型,一旦保存并在恢复后进行评估,它的性能就会差得多。以上是关于tf.layers.batch_normalization 大测试错误的主要内容,如果未能解决你的问题,请参考以下文章