Module: tf.losses

Module: tf.losses

  • 作用: 用于神经网络的损失运算
  • 注意点: 默认情况下,所有损失都会添加到GraphKeys.losses集合中。

1. tf.losses.add_loss

  • 将外部定义的损失添加到损失集合中
# 官方接口
tf.losses.add_loss(
    loss, loss_collection=tf.GraphKeys.LOSSES
)
'''
loss: Tensor张量
loss_collection: 可将损失添加到指定集合。 默认为GraphKeys.losses集合
'''

2. tf.losses.get_losses

  • 从loss_collection中获取损失列表
tf.losses.get_losses(
    scope=None, loss_collection=tf.GraphKeys.LOSSES
)
'''
scope: 指定作用域名称,从而过滤损失列表
loss_collection: 损失集合
'''

3. tf.losses.get_total_loss

  • 返回一个Tensor张量, 对所有损失求和
tf.losses.get_total_loss(
    add_regularization_losses=True, name='total_loss', scope=None
)
'''
参数:
	add_regularization_losses: bool类型,是否在损失加和过程中使用正则化损失
	name: 返回的Tensor张量的名称
	scope: 指定作用域名称,从而过滤损失列表
返回值:
	返回一个Tensor张量, 其值可代表所有的损失
'''

代码示例:

# 创建两个Tensor张量,添加到默认的损失集合中
loss1 = tf.constant(1, shape=[1], dtype=tf.float32)
loss2 = tf.constant(10, shape=[1], dtype=tf.float32)
tf.losses.add_loss(loss1)
tf.losses.add_loss(loss2)
# 打印损失集合中的元素
print(tf.losses.get_losses())
'''
[<tf.Tensor 'Const:0' shape=(1,) dtype=float32>, <tf.Tensor 'Const_1:0' shape=(1,) dtype=float32>]
'''
with tf.Session() as sess:
   print("totol loss:", sess.run(tf.losses.get_total_loss()))
'''
totol loss: [11.]
'''

猜你喜欢

转载自blog.csdn.net/yewumeng123/article/details/131351079