tf.contrib.layers.l2_regularizer
import tensorflow as tf
import tensorflow.contrib as contrib
weight = tf.constant([[1.0, -2.0], [-3.0, 4.0]])
with tf.Session() as sess:
# 输出为(|1|+|-2|+|-3|+|4|)*0.5=5
print(sess.run(contrib.layers.l1_regularizer(0.5)(weight)))
# 输出为(1²+(-2)²+(-3)²+4²)/2*0.5=7.5
# TensorFlow会将L2的正则化损失值除以2使得求导得到的结果更加简洁
print(sess.run(contrib.layers.l2_regularizer(0.5)(weight)))
# l1_regularizer+l2_regularizer
print(sess.run(contrib.layers.l1_l2_regularizer(0.5, 0.5)(weight)))
规则化可以帮助防止过度配合,提高模型的适用性。(让模型无法完美匹配所有的训练项。)(使用规则来使用尽量少的变量去拟合数据)
规则化就是说给需要训练的目标函数加上一些规则(限制),让他们不要自我膨胀。
损失通常被添加到 tf.GraphKeys.REGULARIZATION_LOSSES
。
-
tf.contrib.layers.apply_regularization
-
tf.contrib.layers.l1_regularizer
-
tf.contrib.layers.l2_regularizer
-
tf.contrib.layers.sum_regularizer