_binary_crossentropy
binary_crossentropy
¶
Compute binary crossentropy.
This method is applicable when there are only two label classes (zero and one).
This method can be used with TensorFlow tensors:
true = tf.constant([[1], [0], [1], [0]])
pred = tf.constant([[0.9], [0.3], [0.8], [0.1]])
weights = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(tf.constant([1]), tf.constant([2.0])), default_value=1.0)
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true) # 0.197
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true, average_loss=False) # [0.105, 0.356, 0.223, 0.105]
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true, average_loss=False, class_weights=weights)
# [0.210, 0.356, 0.446, 0.105]
This method can be used with PyTorch tensors:
true = torch.tensor([[1], [0], [1], [0]])
pred = torch.tensor([[0.9], [0.3], [0.8], [0.1]])
weights = {1: 2.0}
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true) # 0.197
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true, average_loss=False) # [0.105, 0.356, 0.223, 0.105]
b = fe.backend.binary_crossentropy(y_pred=pred, y_true=true, average_loss=False, class_weights=weights)
# [0.210, 0.356, 0.446, 0.105]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y_pred |
Tensor
|
Prediction with a shape like (batch, ...). dtype: float32 or float16. |
required |
y_true |
Tensor
|
Ground truth class labels with the same shape as |
required |
from_logits |
bool
|
Whether y_pred is from logits. If True, a sigmoid will be applied to the prediction. |
False
|
average_loss |
bool
|
Whether to average the element-wise loss. |
True
|
class_weights |
Optional[Weight_Dict]
|
Mapping of class indices to a weight for weighting the loss function. Useful when you need to pay more attention to samples from an under-represented class. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
The binary crossentropy between |
Tensor
|
the same shape as |
Raises:
Type | Description |
---|---|
AssertionError
|
If |