在渴望执行中,有两种方法。
- 用
tf.add_n([tf.square(i) for i in layer.variables]) * l2_coef
。
- 使用
layer.losses
创建layer.losses
时使用kernel_regularizer
。
如官方示例所示: densitynet_test.py
rand_input = tf.random_uniform((10, 3, 32, 32))
weight_decay = 1e-4
conv = tf.keras.layers.Conv2D(
3, (3, 3),
padding='same',
use_bias=False,
kernel_regularizer=tf.keras.regularizers.l2(weight_decay))
optimizer = tf.train.GradientDescentOptimizer(0.1)
conv(rand_input) # Initialize the variables in the layer
def compute_true_l2(vs, wd):
return tf.reduce_sum(tf.square(vs)) * wd
true_l2 = compute_true_l2(conv.variables, weight_decay)
keras_l2 = tf.add_n(conv.losses)
self.assertAllClose(true_l2, keras_l2)
with tf.GradientTape() as tape_true, tf.GradientTape() as tape_keras:
loss = tf.reduce_sum(conv(rand_input))
loss_with_true_l2 = loss + compute_true_l2(conv.variables, weight_decay)
loss_with_keras_l2 = loss + tf.add_n(conv.losses)
true_grads = tape_true.gradient(loss_with_true_l2, conv.variables)
keras_grads = tape_keras.gradient(loss_with_keras_l2, conv.variables)
self.assertAllClose(true_grads, keras_grads)
0
使用tf.layers中定义的层时,是否可以添加L2正则化?
在我看来,由于tf.layers是高级包装程序,因此没有简单的方法可以访问过滤器权重。
使用tf.nn.conv2d
现在,使用tf.layers.conv2d会是什么样?
谢谢!