MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / compute_weighted_loss

Function compute_weighted_loss

tensorflow/python/keras/utils/losses_utils.py:70–112  ·  view source on GitHub ↗

Computes the weighted loss. Args: losses: `Tensor` of shape `[batch_size, d1, ... dN]`. sample_weight: Optional `Tensor` whose rank is either 0, or the same rank as `losses`, or be broadcastable to `losses`. reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to l

(losses,
                          sample_weight=None,
                          reduction=ReductionV2.SUM_OVER_BATCH_SIZE,
                          name=None)

Source from the content-addressed store, hash-verified

68
69
70def compute_weighted_loss(losses,
71 sample_weight=None,
72 reduction=ReductionV2.SUM_OVER_BATCH_SIZE,
73 name=None):
74 """Computes the weighted loss.
75
76 Args:
77 losses: `Tensor` of shape `[batch_size, d1, ... dN]`.
78 sample_weight: Optional `Tensor` whose rank is either 0, or the same rank as
79 `losses`, or be broadcastable to `losses`.
80 reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to loss.
81 Default value is `SUM_OVER_BATCH_SIZE`.
82 name: Optional name for the op.
83
84 Raises:
85 ValueError: If the shape of `sample_weight` is not compatible with `losses`.
86
87 Returns:
88 Weighted loss `Tensor` of the same type as `losses`. If `reduction` is
89 `NONE`, this has the same shape as `losses`; otherwise, it is scalar.
90 """
91 ReductionV2.validate(reduction)
92
93 # If this function is called directly, then we just default 'AUTO' to
94 # 'SUM_OVER_BATCH_SIZE'. Eg. Canned estimator use cases.
95 if reduction == ReductionV2.AUTO:
96 reduction = ReductionV2.SUM_OVER_BATCH_SIZE
97 if sample_weight is None:
98 sample_weight = 1.0
99 with K.name_scope(name or 'weighted_loss'):
100 # Save the `reduction` argument for loss normalization when distributing
101 # to multiple replicas. Used only for estimator + v1 optimizer flow.
102 ops.get_default_graph()._last_loss_reduction = reduction # pylint: disable=protected-access
103
104 losses = ops.convert_to_tensor(losses)
105 input_dtype = losses.dtype
106 weighted_losses = tf_losses_utils.scale_losses_by_sample_weight(
107 losses, sample_weight)
108 # Apply reduction function to the individual weighted losses.
109 loss = reduce_weighted_loss(weighted_losses, reduction)
110 # Convert the result back to the input type.
111 loss = math_ops.cast(loss, input_dtype)
112 return loss
113
114
115def scale_loss_for_distribution(loss_value):

Callers

nothing calls this directly

Calls 4

reduce_weighted_lossFunction · 0.85
validateMethod · 0.45
name_scopeMethod · 0.45
castMethod · 0.45

Tested by

no test coverage detected