tensorflow的loss损失函数tf.nn.l2_loss

Loss

损失运算 用于测量两个张量之间或张量与0之间的误差。 这些可以用于测量回归任务中的网络的精确度,或用于正则化的目的(权重衰减)。 

L2正则化(regularization)

loss0表示原始的损失函数,后面的部分为L2正则化,通过加入一个正则项来防止过拟合(data overfitting)

                                                                                 loss = loss0 +\frac{\lambda }{2}\sum w^{2}

因此tf.nn.l2_loss可以作为一个正则项

tf.nn.l2_loss(t, name=None)

tf.nn.l2_loss形如1/2Σw2,一般用于优化的目标函数中的正则项,防止参数太多复杂容易过拟合。

解释:这个函数的作用是利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半,具体如下:

output = sum(t ** 2) / 2

输入参数:

  • t: 一个Tensor。数据类型必须是一下之一:float32,float64,int64,int32,uint8,int16,int8,complex64,qint8,quint8,qint32。虽然一般情况下,数据维度是二维的。但是,数据维度可以取任意维度。
  • name: 为这个操作取个名字。

输出参数:

一个 Tensor ,数据类型和 t 相同,是一个标量。

例如:
import tensorflow as tf

a=tf.constant([1,2,3],dtype=tf.float32)
b=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)

with tf.Session() as sess:
    print('a:')
    print(sess.run(tf.nn.l2_loss(a)))
    print('b:')
    print(sess.run(tf.nn.l2_loss(b)))
    sess.close()
那么打印出来为:

a:
7.0
b:
14.0
计算的是每一个元素的平方之后相加最后除以2

猜你喜欢

转载自blog.csdn.net/zz2230633069/article/details/81413138