kernel_regularizerand Activity regularizers

本文介绍了深度学习中正则化的概念,特别是TensorFlow库中的kernel_regularizer、bias_regularizer和activity_regularizer。通过实例展示了如何在Dense层中应用L1_L2正则化,并解释了它们分别作用于权重、偏置和输出的效果。正则化有助于防止过拟合,保持模型的泛化能力。
  • kernel_regularizer: Regularizer to apply a penalty on the layer’s
  • kernel bias_regularizer: Regularizer to apply a penalty on the
  • layer’s bias activity_regularizer: Regularizer to apply a penalty on the layer’s output
#coding=utf-8

import tensorflow as tf

layer = tf.keras.layers.Dense(units=5,
                              kernel_initializer='ones',
                              kernel_regularizer=tf.keras.regularizers.l1_l2(l1=0.01, l2=0.01))

tensor = tf.ones(shape=(5, 5)) * 2.0
# print("tensor:", tensor)
out = layer(tensor)
print("out:", out)
print("----start----")
print("trainable_variables:", layer.trainable_variables)
print("----end------")
# The kernel regularization term is 0.25 0.25
print(tf.math.reduce_sum(layer.losses))  # 0.5 (= 0.25 + 0.25)
out: tf.Tensor(
[[10. 10. 10. 10. 10.]
 [10. 10. 10. 10. 10.]
 [10. 10. 10. 10. 10.]
 [10. 10. 10. 10. 10.]
 [10. 10. 10. 10. 10.]], shape=(5, 5), dtype=float32)
----start----
trainable_variables: [<tf.Variable 'dense/kernel:0' shape=(5, 5) dtype=float32, numpy=
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]], dtype=float32)>, <tf.Variable 'dense/bias:0' shape=(5,) dtype=float32, numpy=array([0., 0., 0., 0., 0.], dtype=float32)>]
----end------
tf.Tensor(0.5, shape=(), dtype=float32)

The activity regularizer works as a function of the output of the net, and is mostly used to regularize hidden units, while weight_regularizer, as the name says, works on the weights (e.g. making them decay). Basically you can express the regularization loss as a function of the output (activity_regularizer) or of the weights (weight_regularizer).

Keras: Difference between Kernel and Activity regularizers
正则化器的使用
Layer weight regularizers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值