|TensorFlow 1 version||View source on GitHub|
Computes the cross-entropy loss between true labels and predicted labels.
Used in the tutorials:
- Transfer learning with a pretrained ConvNet
- Deep Convolutional Generative Adversarial Network
- Classification on imbalanced data
Use this cross-entropy loss when there are only two label classes (assumed to be 0 and 1). For each example, there should be a single floating-point value per prediction.
In the snippet below, each of the four examples has only a single
floating-pointing value, and both
y_true have the shape
bce = tf.keras.losses.BinaryCrossentropy() loss = bce([0., 0., 1., 1.], [1., 1., 1., 0.]) print('Loss: ', loss.numpy()) # Loss: 11.522857
Usage with the
model = tf.keras.Model(inputs, outputs) model.compile('sgd', loss=tf.keras.losses.BinaryCrossentropy())
from_logits: Whether to interpret
y_predas a tensor of logit values. By default, we assume that
y_predcontains probabilities (i.e., values in [0, 1]). Note: Using from_logits=True may be more numerically stable.
label_smoothing: Float in [0, 1]. When 0, no smoothing occurs. When > 0, we compute the loss between the predicted labels and a smoothed version of the true labels, where the smoothing squeezes the labels towards 0.5. Larger values of
label_smoothingcorrespond to heavier smoothing.
reduction: (Optional) Type of
tf.keras.losses.Reductionto apply to loss. Default value is
AUTOindicates that the reduction option will be determined by the usage context. For almost all cases this defaults to
SUM_OVER_BATCH_SIZE. When used with
tf.distribute.Strategy, outside of built-in training loops such as
SUM_OVER_BATCH_SIZEwill raise an error. Please see https://www.tensorflow.org/tutorials/distribute/custom_training for more details on this.
name: (Optional) Name for the op.
__init__( from_logits=False, label_smoothing=0, reduction=losses_utils.ReductionV2.AUTO, name='binary_crossentropy' )
Initialize self. See help(type(self)) for accurate signature.
__call__( y_true, y_pred, sample_weight=None )
y_true: Ground truth values. shape =
[batch_size, d0, .. dN]
y_pred: The predicted values. shape =
[batch_size, d0, .. dN]
sample_weightacts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If
sample_weightis a tensor of size
[batch_size], then the total loss for each sample of the batch is rescaled by the corresponding element in the
sample_weightvector. If the shape of
[batch_size, d0, .. dN-1](or can be broadcasted to this shape), then each loss element of
y_predis scaled by the corresponding value of
sample_weight. (Note on
dN-1: all loss functions reduce by 1 dimension, usually axis=-1.)
Weighted loss float
NONE, this has
[batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note
because all loss functions reduce by 1 dimension, usually axis=-1.)
ValueError: If the shape of
@classmethod from_config( cls, config )
Loss from its config (output of
config: Output of