Module: tf.losses

Module: tf.losses

  • Function: Loss operation for neural network
  • Note: By default, all losses are added to the GraphKeys.losses collection.

1. tf.losses.add_loss

  • Add externally defined losses to the loss collection
# 官方接口
tf.losses.add_loss(
    loss, loss_collection=tf.GraphKeys.LOSSES
)
'''
loss: Tensor张量
loss_collection: 可将损失添加到指定集合。 默认为GraphKeys.losses集合
'''

2. tf.losses.get_losses

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

3. tf.losses.get_total_loss

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

Code example:

# 创建两个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.]
'''

Guess you like

Origin blog.csdn.net/yewumeng123/article/details/131351079