一、基础正则化函数
tf.contrib.layers.l1_regularizer(scale, scope=None)
返回一个用来执行L1
正则化的函数,函数的签名是func(weights)
.
参数:
tf.contrib.layers.l2_regularizer(scale, scope=None)
先看看tf.contrib.layers.l2_regularizer(weight_decay)都执行了什么:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
我们很容易可以模拟出tf.contrib.layers.l2_regularizer都做了什么,不过会让代码变丑。
以下比较完整实现L2 正则化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
二、添加正则化方法
a、原始办法
正则化常用到集合,下面是最原始的添加正则办法(直接在变量声明后将之添加进'losses'集合或tf.GraphKeys.LOESSES也行):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
b、tf.contrib.layers.apply_regularization(regularizer, weights_list=None)
先看参数
- regularizer:就是我们上一步创建的正则化方法
- weights_list: 想要执行正则化方法的参数列表,如果为
None
的话,就取GraphKeys.WEIGHTS
中的weights
.
函数返回一个标量Tensor
,同时,这个标量Tensor
也会保存到GraphKeys.REGULARIZATION_LOSSES
中.这个Tensor
保存了计算正则项损失的方法.
tensorflow
中的Tensor
是保存了计算这个值的路径(方法),当我们run的时候,tensorflow
后端就通过路径计算出Tensor
对应的值
现在,我们只需将这个正则项损失加到我们的损失函数上就可以了.
如果是自己手动定义
weight
的话,需要手动将weight
保存到GraphKeys.WEIGHTS
中,但是如果使用layer
的话,就不用这么麻烦了,别人已经帮你考虑好了.(最好自己验证一下tf.GraphKeys.WEIGHTS
中是否包含了所有的weights
,防止被坑)
c、使用slim
使用slim会简单很多:
1 2 3 4 |
|
此时添加集合为tf.GraphKeys.REGULARIZATION_LOSSES。