tf.keras.losses.CosineSimilarity     View source on GitHub    Computes the cosine similarity between labels and predictions. Inherits From: Loss  View aliases  Main aliases
tf.losses.CosineSimilarity Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.CosineSimilarity
tf.keras.losses.CosineSimilarity(
    axis=-1, reduction=losses_utils.ReductionV2.AUTO,
    name='cosine_similarity'
)
 Note that it is a number between -1 and 1. When it is a negative number between -1 and 0, 0 indicates orthogonality and values closer to -1 indicate greater similarity. The values closer to 1 indicate greater dissimilarity. This makes it usable as a loss function in a setting where you try to maximize the proximity between predictions and targets. If either y_true or y_pred is a zero vector, cosine similarity will be 0 regardless of the proximity between predictions and targets. loss = -sum(l2_norm(y_true) * l2_norm(y_pred)) Standalone usage:
y_true = [[0., 1.], [1., 1.]]
y_pred = [[1., 0.], [1., 1.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
cosine_loss = tf.keras.losses.CosineSimilarity(axis=1)
# l2_norm(y_true) = [[0., 1.], [1./1.414], 1./1.414]]]
# l2_norm(y_pred) = [[1., 0.], [1./1.414], 1./1.414]]]
# l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
# loss = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
#       = -((0. + 0.) +  (0.5 + 0.5)) / 2
cosine_loss(y_true, y_pred).numpy()
-0.5

# Calling with 'sample_weight'.
cosine_loss(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
-0.0999

# Using 'sum' reduction type.
cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
    reduction=tf.keras.losses.Reduction.SUM)
cosine_loss(y_true, y_pred).numpy()
-0.999

# Using 'none' reduction type.
cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
    reduction=tf.keras.losses.Reduction.NONE)
cosine_loss(y_true, y_pred).numpy()
array([-0., -0.999], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.CosineSimilarity(axis=1))

 Args
  axis   (Optional) Defaults to -1. The dimension along which the cosine similarity is computed.
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.cosine_similarity Computes the cosine similarity between labels and predictions.  View aliases  Main aliases
tf.losses.cosine_similarity Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.cosine, tf.compat.v1.keras.losses.cosine_proximity, tf.compat.v1.keras.losses.cosine_similarity, tf.compat.v1.keras.metrics.cosine, tf.compat.v1.keras.metrics.cosine_proximity
tf.keras.losses.cosine_similarity(
    y_true, y_pred, axis=-1
)
 Note that it is a number between -1 and 1. When it is a negative number between -1 and 0, 0 indicates orthogonality and values closer to -1 indicate greater similarity. The values closer to 1 indicate greater dissimilarity. This makes it usable as a loss function in a setting where you try to maximize the proximity between predictions and targets. If either y_true or y_pred is a zero vector, cosine similarity will be 0 regardless of the proximity between predictions and targets. loss = -sum(l2_norm(y_true) * l2_norm(y_pred)) Standalone usage:
y_true = [[0., 1.], [1., 1.], [1., 1.]]
y_pred = [[1., 0.], [1., 1.], [-1., -1.]]
loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1)
loss.numpy()
array([-0., -0.999, 0.999], dtype=float32)

 Args
  y_true   Tensor of true targets.
  y_pred   Tensor of predicted targets.
  axis   Axis along which to determine similarity.

 Returns   Cosine similarity tensor.


tf.keras.losses.deserialize     View source on GitHub    Deserializes a serialized loss class/function instance.  View aliases  Main aliases
tf.losses.deserialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.deserialize
tf.keras.losses.deserialize(
    name, custom_objects=None
)

 Arguments
  name   Loss configuration.
  custom_objects   Optional dictionary mapping names (strings) to custom objects (classes and functions) to be considered during deserialization.

 Returns   A Keras Loss instance or a loss function.


tf.keras.losses.get     View source on GitHub    Retrieves a Keras loss as a function/Loss class instance.  View aliases  Main aliases
tf.losses.get Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.get
tf.keras.losses.get(
    identifier
)
 The identifier may be the string name of a loss function or Loss class.
loss = tf.keras.losses.get("categorical_crossentropy")
type(loss)
<class 'function'>
loss = tf.keras.losses.get("CategoricalCrossentropy")
type(loss)
<class '...tensorflow.python.keras.losses.CategoricalCrossentropy'>
 You can also specify config of the loss to this function by passing dict containing class_name and config as an identifier. Also note that the class_name must map to a Loss class
identifier = {"class_name": "CategoricalCrossentropy",
              "config": {"from_logits": True} }
loss = tf.keras.losses.get(identifier)
type(loss)
<class '...tensorflow.python.keras.losses.CategoricalCrossentropy'>

 Arguments
  identifier   A loss identifier. One of None or string name of a loss function/class or loss configuration dictionary or a loss function or a loss class instance

 Returns   A Keras loss as a function/ Loss class instance.

 Raises
  ValueError   If identifier cannot be interpreted.


tf.keras.losses.Hinge     View source on GitHub    Computes the hinge loss between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.Hinge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.Hinge
tf.keras.losses.Hinge(
    reduction=losses_utils.ReductionV2.AUTO, name='hinge'
)
 loss = maximum(1 - y_true * y_pred, 0) y_true values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
h = tf.keras.losses.Hinge()
h(y_true, y_pred).numpy()
1.3

# Calling with 'sample_weight'.
h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.55

# Using 'sum' reduction type.
h = tf.keras.losses.Hinge(
    reduction=tf.keras.losses.Reduction.SUM)
h(y_true, y_pred).numpy()
2.6

# Using 'none' reduction type.
h = tf.keras.losses.Hinge(
    reduction=tf.keras.losses.Reduction.NONE)
h(y_true, y_pred).numpy()
array([1.1, 1.5], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.Hinge())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'hinge'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.Huber     View source on GitHub    Computes the Huber loss between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.Huber Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.Huber
tf.keras.losses.Huber(
    delta=1.0, reduction=losses_utils.ReductionV2.AUTO, name='huber_loss'
)
 For each value x in error = y_true - y_pred: loss = 0.5 * x^2                  if |x| <= d
loss = 0.5 * d^2 + d * (|x| - d)  if |x| > d
 where d is delta. See: https://en.wikipedia.org/wiki/Huber_loss Standalone usage:
y_true = [[0, 1], [0, 0]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
h = tf.keras.losses.Huber()
h(y_true, y_pred).numpy()
0.155

# Calling with 'sample_weight'.
h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.09

# Using 'sum' reduction type.
h = tf.keras.losses.Huber(
    reduction=tf.keras.losses.Reduction.SUM)
h(y_true, y_pred).numpy()
0.31

# Using 'none' reduction type.
h = tf.keras.losses.Huber(
    reduction=tf.keras.losses.Reduction.NONE)
h(y_true, y_pred).numpy()
array([0.18, 0.13], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.Huber())

 Args
  delta   A float, the point where the Huber loss function changes from a quadratic to linear.
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'huber_loss'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.KLD     View source on GitHub    Computes Kullback-Leibler divergence loss between y_true and y_pred.  View aliases  Main aliases
tf.keras.losses.kl_divergence, tf.keras.losses.kld, tf.keras.losses.kullback_leibler_divergence, tf.keras.metrics.KLD, tf.keras.metrics.kl_divergence, tf.keras.metrics.kld, tf.keras.metrics.kullback_leibler_divergence, tf.losses.KLD, tf.losses.kl_divergence, tf.losses.kld, tf.losses.kullback_leibler_divergence, tf.metrics.KLD, tf.metrics.kl_divergence, tf.metrics.kld, tf.metrics.kullback_leibler_divergence Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.KLD, tf.compat.v1.keras.losses.kl_divergence, tf.compat.v1.keras.losses.kld, tf.compat.v1.keras.losses.kullback_leibler_divergence, tf.compat.v1.keras.metrics.KLD, tf.compat.v1.keras.metrics.kl_divergence, tf.compat.v1.keras.metrics.kld, tf.compat.v1.keras.metrics.kullback_leibler_divergence
tf.keras.losses.KLD(
    y_true, y_pred
)
 loss = y_true * log(y_true / y_pred) See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence Standalone usage:
y_true = np.random.randint(0, 2, size=(2, 3)).astype(np.float64)
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.kullback_leibler_divergence(y_true, y_pred)
assert loss.shape == (2,)
y_true = tf.keras.backend.clip(y_true, 1e-7, 1)
y_pred = tf.keras.backend.clip(y_pred, 1e-7, 1)
assert np.array_equal(
    loss.numpy(), np.sum(y_true * np.log(y_true / y_pred), axis=-1))

 Args
  y_true   Tensor of true targets.
  y_pred   Tensor of predicted targets.

 Returns   A Tensor with loss.

 Raises
  TypeError   If y_true cannot be cast to the y_pred.dtype.


tf.keras.losses.KLDivergence     View source on GitHub    Computes Kullback-Leibler divergence loss between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.KLDivergence Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.KLDivergence
tf.keras.losses.KLDivergence(
    reduction=losses_utils.ReductionV2.AUTO, name='kl_divergence'
)
 loss = y_true * log(y_true / y_pred) See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence Standalone usage:
y_true = [[0, 1], [0, 0]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
kl = tf.keras.losses.KLDivergence()
kl(y_true, y_pred).numpy()
0.458

# Calling with 'sample_weight'.
kl(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
0.366

# Using 'sum' reduction type.
kl = tf.keras.losses.KLDivergence(
    reduction=tf.keras.losses.Reduction.SUM)
kl(y_true, y_pred).numpy()
0.916

# Using 'none' reduction type.
kl = tf.keras.losses.KLDivergence(
    reduction=tf.keras.losses.Reduction.NONE)
kl(y_true, y_pred).numpy()
array([0.916, -3.08e-06], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.KLDivergence())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'kl_divergence'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.LogCosh     View source on GitHub    Computes the logarithm of the hyperbolic cosine of the prediction error. Inherits From: Loss  View aliases  Main aliases
tf.losses.LogCosh Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.LogCosh
tf.keras.losses.LogCosh(
    reduction=losses_utils.ReductionV2.AUTO, name='log_cosh'
)
 logcosh = log((exp(x) + exp(-x))/2), where x is the error y_pred - y_true. Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[1., 1.], [0., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
l = tf.keras.losses.LogCosh()
l(y_true, y_pred).numpy()
0.108

# Calling with 'sample_weight'.
l(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
0.087

# Using 'sum' reduction type.
l = tf.keras.losses.LogCosh(
    reduction=tf.keras.losses.Reduction.SUM)
l(y_true, y_pred).numpy()
0.217

# Using 'none' reduction type.
l = tf.keras.losses.LogCosh(
    reduction=tf.keras.losses.Reduction.NONE)
l(y_true, y_pred).numpy()
array([0.217, 0.], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.LogCosh())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'log_cosh'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.log_cosh Logarithm of the hyperbolic cosine of the prediction error.  View aliases  Main aliases
tf.keras.losses.logcosh, tf.keras.metrics.log_cosh, tf.keras.metrics.logcosh, tf.losses.log_cosh, tf.losses.logcosh, tf.metrics.log_cosh, tf.metrics.logcosh Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.log_cosh, tf.compat.v1.keras.losses.logcosh, tf.compat.v1.keras.metrics.log_cosh, tf.compat.v1.keras.metrics.logcosh
tf.keras.losses.log_cosh(
    y_true, y_pred
)
 log(cosh(x)) is approximately equal to (x ** 2) / 2 for small x and to abs(x) - log(2) for large x. This means that 'logcosh' works mostly like the mean squared error, but will not be so strongly affected by the occasional wildly incorrect prediction. Standalone usage:
y_true = np.random.random(size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.logcosh(y_true, y_pred)
assert loss.shape == (2,)
x = y_pred - y_true
assert np.allclose(
    loss.numpy(),
    np.mean(x + np.log(np.exp(-2. * x) + 1.) - math_ops.log(2.), axis=-1),
    atol=1e-5)

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Logcosh error values. shape = [batch_size, d0, .. dN-1].


tf.keras.losses.Loss     View source on GitHub    Loss base class.  View aliases  Main aliases
tf.losses.Loss Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.Loss
tf.keras.losses.Loss(
    reduction=losses_utils.ReductionV2.AUTO, name=None
)
 To be implemented by subclasses:
call(): Contains the logic for loss calculation using y_true, y_pred.  Example subclass implementation: class MeanSquaredError(Loss):

  def call(self, y_true, y_pred):
    y_pred = tf.convert_to_tensor_v2(y_pred)
    y_true = tf.cast(y_true, y_pred.dtype)
    return tf.reduce_mean(math_ops.square(y_pred - y_true), axis=-1)
 When used with tf.distribute.Strategy, outside of built-in training loops such as tf.keras compile and fit, please use 'SUM' or 'NONE' reduction types, and reduce losses explicitly in your training loop. Using 'AUTO' or 'SUM_OVER_BATCH_SIZE' will raise an error. Please see this custom training tutorial for more details on this. You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: with strategy.scope():
  loss_obj = tf.keras.losses.CategoricalCrossentropy(
      reduction=tf.keras.losses.Reduction.NONE)
  ....
  loss = (tf.reduce_sum(loss_obj(labels, predictions)) *
          (1. / global_batch_size))

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op.    Methods call View source
@abc.abstractmethod
call(
    y_true, y_pred
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]

 Returns   Loss values with the shape [batch_size, d0, .. dN-1].
 from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.MAE     View source on GitHub    Computes the mean absolute error between labels and predictions.  View aliases  Main aliases
tf.keras.losses.mae, tf.keras.losses.mean_absolute_error, tf.keras.metrics.MAE, tf.keras.metrics.mae, tf.keras.metrics.mean_absolute_error, tf.losses.MAE, tf.losses.mae, tf.losses.mean_absolute_error, tf.metrics.MAE, tf.metrics.mae, tf.metrics.mean_absolute_error Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MAE, tf.compat.v1.keras.losses.mae, tf.compat.v1.keras.losses.mean_absolute_error, tf.compat.v1.keras.metrics.MAE, tf.compat.v1.keras.metrics.mae, tf.compat.v1.keras.metrics.mean_absolute_error
tf.keras.losses.MAE(
    y_true, y_pred
)
 loss = mean(abs(y_true - y_pred), axis=-1) Standalone usage:
y_true = np.random.randint(0, 2, size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.mean_absolute_error(y_true, y_pred)
assert loss.shape == (2,)
assert np.array_equal(
    loss.numpy(), np.mean(np.abs(y_true - y_pred), axis=-1))

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Mean absolute error values. shape = [batch_size, d0, .. dN-1].


tf.keras.losses.MAPE     View source on GitHub    Computes the mean absolute percentage error between y_true and y_pred.  View aliases  Main aliases
tf.keras.losses.mape, tf.keras.losses.mean_absolute_percentage_error, tf.keras.metrics.MAPE, tf.keras.metrics.mape, tf.keras.metrics.mean_absolute_percentage_error, tf.losses.MAPE, tf.losses.mape, tf.losses.mean_absolute_percentage_error, tf.metrics.MAPE, tf.metrics.mape, tf.metrics.mean_absolute_percentage_error Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MAPE, tf.compat.v1.keras.losses.mape, tf.compat.v1.keras.losses.mean_absolute_percentage_error, tf.compat.v1.keras.metrics.MAPE, tf.compat.v1.keras.metrics.mape, tf.compat.v1.keras.metrics.mean_absolute_percentage_error
tf.keras.losses.MAPE(
    y_true, y_pred
)
 loss = 100 * mean(abs((y_true - y_pred) / y_true), axis=-1) Standalone usage:
y_true = np.random.random(size=(2, 3))
y_true = np.maximum(y_true, 1e-7)  # Prevent division by zero
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.mean_absolute_percentage_error(y_true, y_pred)
assert loss.shape == (2,)
assert np.array_equal(
    loss.numpy(),
    100. * np.mean(np.abs((y_true - y_pred) / y_true), axis=-1))

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Mean absolute percentage error values. shape = [batch_size, d0, .. dN-1].


tf.keras.losses.MeanAbsoluteError     View source on GitHub    Computes the mean of absolute difference between labels and predictions. Inherits From: Loss  View aliases  Main aliases
tf.losses.MeanAbsoluteError Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MeanAbsoluteError
tf.keras.losses.MeanAbsoluteError(
    reduction=losses_utils.ReductionV2.AUTO, name='mean_absolute_error'
)
 loss = abs(y_true - y_pred) Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[1., 1.], [1., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
mae = tf.keras.losses.MeanAbsoluteError()
mae(y_true, y_pred).numpy()
0.5

# Calling with 'sample_weight'.
mae(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.25

# Using 'sum' reduction type.
mae = tf.keras.losses.MeanAbsoluteError(
    reduction=tf.keras.losses.Reduction.SUM)
mae(y_true, y_pred).numpy()
1.0

# Using 'none' reduction type.
mae = tf.keras.losses.MeanAbsoluteError(
    reduction=tf.keras.losses.Reduction.NONE)
mae(y_true, y_pred).numpy()
array([0.5, 0.5], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.MeanAbsoluteError())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'mean_absolute_error'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.MeanAbsolutePercentageError     View source on GitHub    Computes the mean absolute percentage error between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.MeanAbsolutePercentageError Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MeanAbsolutePercentageError
tf.keras.losses.MeanAbsolutePercentageError(
    reduction=losses_utils.ReductionV2.AUTO,
    name='mean_absolute_percentage_error'
)
 loss = 100 * abs(y_true - y_pred) / y_true Standalone usage:
y_true = [[2., 1.], [2., 3.]]
y_pred = [[1., 1.], [1., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
mape = tf.keras.losses.MeanAbsolutePercentageError()
mape(y_true, y_pred).numpy()
50.

# Calling with 'sample_weight'.
mape(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
20.

# Using 'sum' reduction type.
mape = tf.keras.losses.MeanAbsolutePercentageError(
    reduction=tf.keras.losses.Reduction.SUM)
mape(y_true, y_pred).numpy()
100.

# Using 'none' reduction type.
mape = tf.keras.losses.MeanAbsolutePercentageError(
    reduction=tf.keras.losses.Reduction.NONE)
mape(y_true, y_pred).numpy()
array([25., 75.], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd',
              loss=tf.keras.losses.MeanAbsolutePercentageError())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'mean_absolute_percentage_error'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.MeanSquaredError     View source on GitHub    Computes the mean of squares of errors between labels and predictions. Inherits From: Loss  View aliases  Main aliases
tf.losses.MeanSquaredError Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MeanSquaredError
tf.keras.losses.MeanSquaredError(
    reduction=losses_utils.ReductionV2.AUTO, name='mean_squared_error'
)
 loss = square(y_true - y_pred) Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[1., 1.], [1., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
mse = tf.keras.losses.MeanSquaredError()
mse(y_true, y_pred).numpy()
0.5

# Calling with 'sample_weight'.
mse(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.25

# Using 'sum' reduction type.
mse = tf.keras.losses.MeanSquaredError(
    reduction=tf.keras.losses.Reduction.SUM)
mse(y_true, y_pred).numpy()
1.0

# Using 'none' reduction type.
mse = tf.keras.losses.MeanSquaredError(
    reduction=tf.keras.losses.Reduction.NONE)
mse(y_true, y_pred).numpy()
array([0.5, 0.5], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.MeanSquaredError())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'mean_squared_error'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.MeanSquaredLogarithmicError     View source on GitHub    Computes the mean squared logarithmic error between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.MeanSquaredLogarithmicError Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MeanSquaredLogarithmicError
tf.keras.losses.MeanSquaredLogarithmicError(
    reduction=losses_utils.ReductionV2.AUTO,
    name='mean_squared_logarithmic_error'
)
 loss = square(log(y_true + 1.) - log(y_pred + 1.)) Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[1., 1.], [1., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
msle = tf.keras.losses.MeanSquaredLogarithmicError()
msle(y_true, y_pred).numpy()
0.240

# Calling with 'sample_weight'.
msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.120

# Using 'sum' reduction type.
msle = tf.keras.losses.MeanSquaredLogarithmicError(
    reduction=tf.keras.losses.Reduction.SUM)
msle(y_true, y_pred).numpy()
0.480

# Using 'none' reduction type.
msle = tf.keras.losses.MeanSquaredLogarithmicError(
    reduction=tf.keras.losses.Reduction.NONE)
msle(y_true, y_pred).numpy()
array([0.240, 0.240], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd',
              loss=tf.keras.losses.MeanSquaredLogarithmicError())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'mean_squared_logarithmic_error'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.MSE     View source on GitHub    Computes the mean squared error between labels and predictions.  View aliases  Main aliases
tf.keras.losses.mean_squared_error, tf.keras.losses.mse, tf.keras.metrics.MSE, tf.keras.metrics.mean_squared_error, tf.keras.metrics.mse, tf.losses.MSE, tf.losses.mean_squared_error, tf.losses.mse, tf.metrics.MSE, tf.metrics.mean_squared_error, tf.metrics.mse Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MSE, tf.compat.v1.keras.losses.mean_squared_error, tf.compat.v1.keras.losses.mse, tf.compat.v1.keras.metrics.MSE, tf.compat.v1.keras.metrics.mean_squared_error, tf.compat.v1.keras.metrics.mse
tf.keras.losses.MSE(
    y_true, y_pred
)
 After computing the squared distance between the inputs, the mean value over the last dimension is returned. loss = mean(square(y_true - y_pred), axis=-1) Standalone usage:
y_true = np.random.randint(0, 2, size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.mean_squared_error(y_true, y_pred)
assert loss.shape == (2,)
assert np.array_equal(
    loss.numpy(), np.mean(np.square(y_true - y_pred), axis=-1))

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Mean squared error values. shape = [batch_size, d0, .. dN-1].


tf.keras.losses.MSLE     View source on GitHub    Computes the mean squared logarithmic error between y_true and y_pred.  View aliases  Main aliases
tf.keras.losses.mean_squared_logarithmic_error, tf.keras.losses.msle, tf.keras.metrics.MSLE, tf.keras.metrics.mean_squared_logarithmic_error, tf.keras.metrics.msle, tf.losses.MSLE, tf.losses.mean_squared_logarithmic_error, tf.losses.msle, tf.metrics.MSLE, tf.metrics.mean_squared_logarithmic_error, tf.metrics.msle Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.MSLE, tf.compat.v1.keras.losses.mean_squared_logarithmic_error, tf.compat.v1.keras.losses.msle, tf.compat.v1.keras.metrics.MSLE, tf.compat.v1.keras.metrics.mean_squared_logarithmic_error, tf.compat.v1.keras.metrics.msle
tf.keras.losses.MSLE(
    y_true, y_pred
)
 loss = mean(square(log(y_true + 1) - log(y_pred + 1)), axis=-1) Standalone usage:
y_true = np.random.randint(0, 2, size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.mean_squared_logarithmic_error(y_true, y_pred)
assert loss.shape == (2,)
y_true = np.maximum(y_true, 1e-7)
y_pred = np.maximum(y_pred, 1e-7)
assert np.allclose(
    loss.numpy(),
    np.mean(
        np.square(np.log(y_true + 1.) - np.log(y_pred + 1.)), axis=-1))

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Mean squared logarithmic error values. shape = [batch_size, d0, .. dN-1].


tf.keras.losses.Poisson     View source on GitHub    Computes the Poisson loss between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.Poisson Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.Poisson
tf.keras.losses.Poisson(
    reduction=losses_utils.ReductionV2.AUTO, name='poisson'
)
 loss = y_pred - y_true * log(y_pred) Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[1., 1.], [0., 0.]]
# Using 'auto'/'sum_over_batch_size' reduction type.
p = tf.keras.losses.Poisson()
p(y_true, y_pred).numpy()
0.5

# Calling with 'sample_weight'.
p(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
0.4

# Using 'sum' reduction type.
p = tf.keras.losses.Poisson(
    reduction=tf.keras.losses.Reduction.SUM)
p(y_true, y_pred).numpy()
0.999

# Using 'none' reduction type.
p = tf.keras.losses.Poisson(
    reduction=tf.keras.losses.Reduction.NONE)
p(y_true, y_pred).numpy()
array([0.999, 0.], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.Poisson())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'poisson'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.Reduction Types of loss reduction.  View aliases  Main aliases
tf.losses.Reduction  Contains the following values:
AUTO: Indicates 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 tf.keras compile and fit, we expect reduction value to be SUM or NONE. Using AUTO in that case will raise an error.
NONE: Weighted losses with one dimension reduced (axis=-1, or axis specified by loss function). When this reduction type used with built-in Keras training loops like fit/evaluate, the unreduced vector loss is passed to the optimizer but the reported loss will be a scalar value.
SUM: Scalar sum of weighted losses.
SUM_OVER_BATCH_SIZE: Scalar SUM divided by number of elements in losses. This reduction type is not supported when used with tf.distribute.Strategy outside of built-in training loops like tf.keras compile/fit. You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: with strategy.scope():
  loss_obj = tf.keras.losses.CategoricalCrossentropy(
      reduction=tf.keras.losses.Reduction.NONE)
  ....
  loss = tf.reduce_sum(loss_obj(labels, predictions)) *
      (1. / global_batch_size)

  Please see the custom training guide for more details on this. Methods all View source
@classmethod
all()
 validate View source
@classmethod
validate(
    key
)

 Class Variables
  AUTO   'auto'
  NONE   'none'
  SUM   'sum'
  SUM_OVER_BATCH_SIZE   'sum_over_batch_size'


tf.keras.losses.serialize     View source on GitHub    Serializes loss function or Loss instance.  View aliases  Main aliases
tf.losses.serialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.serialize
tf.keras.losses.serialize(
    loss
)

 Arguments
  loss   A Keras Loss instance or a loss function.

 Returns   Loss configuration dictionary.


tf.keras.losses.SparseCategoricalCrossentropy     View source on GitHub    Computes the crossentropy loss between the labels and predictions. Inherits From: Loss  View aliases  Main aliases
tf.losses.SparseCategoricalCrossentropy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.SparseCategoricalCrossentropy
tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=False, reduction=losses_utils.ReductionV2.AUTO,
    name='sparse_categorical_crossentropy'
)
 Use this crossentropy loss function when there are two or more label classes. We expect labels to be provided as integers. If you want to provide labels using one-hot representation, please use CategoricalCrossentropy loss. There should be # classes floating point values per feature for y_pred and a single floating point value per feature for y_true. In the snippet below, there is a single floating point value per example for y_true and # classes floating pointing values per example for y_pred. The shape of y_true is [batch_size] and the shape of y_pred is [batch_size, num_classes]. Standalone usage:
y_true = [1, 2]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
# Using 'auto'/'sum_over_batch_size' reduction type.
scce = tf.keras.losses.SparseCategoricalCrossentropy()
scce(y_true, y_pred).numpy()
1.177

# Calling with 'sample_weight'.
scce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy()
0.814

# Using 'sum' reduction type.
scce = tf.keras.losses.SparseCategoricalCrossentropy(
    reduction=tf.keras.losses.Reduction.SUM)
scce(y_true, y_pred).numpy()
2.354

# Using 'none' reduction type.
scce = tf.keras.losses.SparseCategoricalCrossentropy(
    reduction=tf.keras.losses.Reduction.NONE)
scce(y_true, y_pred).numpy()
array([0.0513, 2.303], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd',
              loss=tf.keras.losses.SparseCategoricalCrossentropy())

 Args
  from_logits   Whether y_pred is expected to be a logits tensor. By default, we assume that y_pred encodes a probability distribution. **Note - Using from_logits=True may be more numerically stable.
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'sparse_categorical_crossentropy'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.sparse_categorical_crossentropy     View source on GitHub    Computes the sparse categorical crossentropy loss.  View aliases  Main aliases
tf.keras.metrics.sparse_categorical_crossentropy, tf.losses.sparse_categorical_crossentropy, tf.metrics.sparse_categorical_crossentropy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.sparse_categorical_crossentropy, tf.compat.v1.keras.metrics.sparse_categorical_crossentropy
tf.keras.losses.sparse_categorical_crossentropy(
    y_true, y_pred, from_logits=False, axis=-1
)
 Standalone usage:
y_true = [1, 2]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
assert loss.shape == (2,)
loss.numpy()
array([0.0513, 2.303], dtype=float32)

 Args
  y_true   Ground truth values.
  y_pred   The predicted values.
  from_logits   Whether y_pred is expected to be a logits tensor. By default, we assume that y_pred encodes a probability distribution.
  axis   (Optional) Defaults to -1. The dimension along which the entropy is computed.

 Returns   Sparse categorical crossentropy loss value.


tf.keras.losses.SquaredHinge     View source on GitHub    Computes the squared hinge loss between y_true and y_pred. Inherits From: Loss  View aliases  Main aliases
tf.losses.SquaredHinge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.SquaredHinge
tf.keras.losses.SquaredHinge(
    reduction=losses_utils.ReductionV2.AUTO, name='squared_hinge'
)
 loss = square(maximum(1 - y_true * y_pred, 0)) y_true values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. Standalone usage:
y_true = [[0., 1.], [0., 0.]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
h = tf.keras.losses.SquaredHinge()
h(y_true, y_pred).numpy()
1.86

# Calling with 'sample_weight'.
h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.73

# Using 'sum' reduction type.
h = tf.keras.losses.SquaredHinge(
    reduction=tf.keras.losses.Reduction.SUM)
h(y_true, y_pred).numpy()
3.72

# Using 'none' reduction type.
h = tf.keras.losses.SquaredHinge(
    reduction=tf.keras.losses.Reduction.NONE)
h(y_true, y_pred).numpy()
array([1.46, 2.26], dtype=float32)
 Usage with the compile() API: model.compile(optimizer='sgd', loss=tf.keras.losses.SquaredHinge())

 Args
  reduction   (Optional) Type of tf.keras.losses.Reduction to apply to loss. Default value is AUTO. AUTO indicates 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 tf.keras compile and fit, using AUTO or SUM_OVER_BATCH_SIZE will raise an error. Please see this custom training tutorial for more details.
  name   Optional name for the op. Defaults to 'squared_hinge'.    Methods from_config View source
@classmethod
from_config(
    config
)
 Instantiates a Loss from its config (output of get_config()).

 Args
  config   Output of get_config().

 Returns   A Loss instance.
 get_config View source
get_config()
 Returns the config dictionary for a Loss instance. __call__ View source
__call__(
    y_true, y_pred, sample_weight=None
)
 Invokes the Loss instance.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]
  y_pred   The predicted values. shape = [batch_size, d0, .. dN]
  sample_weight   Optional sample_weight acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If sample_weight is 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_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each loss element of y_pred is scaled by the corresponding value of sample_weight. (Note ondN-1: all loss functions reduce by 1 dimension, usually axis=-1.)

 Returns   Weighted loss float Tensor. If reduction is NONE, this has shape [batch_size, d0, .. dN-1]; otherwise, it is scalar. (Note dN-1 because all loss functions reduce by 1 dimension, usually axis=-1.)

 Raises
  ValueError   If the shape of sample_weight is invalid.


tf.keras.losses.squared_hinge     View source on GitHub    Computes the squared hinge loss between y_true and y_pred.  View aliases  Main aliases
tf.keras.metrics.squared_hinge, tf.losses.squared_hinge, tf.metrics.squared_hinge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.losses.squared_hinge, tf.compat.v1.keras.metrics.squared_hinge
tf.keras.losses.squared_hinge(
    y_true, y_pred
)
 loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1) Standalone usage:
y_true = np.random.choice([-1, 1], size=(2, 3))
y_pred = np.random.random(size=(2, 3))
loss = tf.keras.losses.squared_hinge(y_true, y_pred)
assert loss.shape == (2,)
assert np.array_equal(
    loss.numpy(),
    np.mean(np.square(np.maximum(1. - y_true * y_pred, 0.)), axis=-1))

 Args
  y_true   The ground truth values. y_true values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].

 Returns   Squared hinge loss values. shape = [batch_size, d0, .. dN-1].


Module: tf.keras.metrics Built-in metrics.  View aliases  Main aliases
tf.metrics  Classes class AUC: Computes the approximate AUC (Area under the curve) via a Riemann sum. class Accuracy: Calculates how often predictions equal labels. class BinaryAccuracy: Calculates how often predictions match binary labels. class BinaryCrossentropy: Computes the crossentropy metric between the labels and predictions. class CategoricalAccuracy: Calculates how often predictions matches one-hot labels. class CategoricalCrossentropy: Computes the crossentropy metric between the labels and predictions. class CategoricalHinge: Computes the categorical hinge metric between y_true and y_pred. class CosineSimilarity: Computes the cosine similarity between the labels and predictions. class FalseNegatives: Calculates the number of false negatives. class FalsePositives: Calculates the number of false positives. class Hinge: Computes the hinge metric between y_true and y_pred. class KLDivergence: Computes Kullback-Leibler divergence metric between y_true and y_pred. class LogCoshError: Computes the logarithm of the hyperbolic cosine of the prediction error. class Mean: Computes the (weighted) mean of the given values. class MeanAbsoluteError: Computes the mean absolute error between the labels and predictions. class MeanAbsolutePercentageError: Computes the mean absolute percentage error between y_true and y_pred. class MeanIoU: Computes the mean Intersection-Over-Union metric. class MeanRelativeError: Computes the mean relative error by normalizing with the given values. class MeanSquaredError: Computes the mean squared error between y_true and y_pred. class MeanSquaredLogarithmicError: Computes the mean squared logarithmic error between y_true and y_pred. class MeanTensor: Computes the element-wise (weighted) mean of the given tensors. class Metric: Encapsulates metric logic and state. class Poisson: Computes the Poisson metric between y_true and y_pred. class Precision: Computes the precision of the predictions with respect to the labels. class PrecisionAtRecall: Computes best precision where recall is >= specified value. class Recall: Computes the recall of the predictions with respect to the labels. class RecallAtPrecision: Computes best recall where precision is >= specified value. class RootMeanSquaredError: Computes root mean squared error metric between y_true and y_pred. class SensitivityAtSpecificity: Computes best sensitivity where specificity is >= specified value. class SparseCategoricalAccuracy: Calculates how often predictions matches integer labels. class SparseCategoricalCrossentropy: Computes the crossentropy metric between the labels and predictions. class SparseTopKCategoricalAccuracy: Computes how often integer targets are in the top K predictions. class SpecificityAtSensitivity: Computes best specificity where sensitivity is >= specified value. class SquaredHinge: Computes the squared hinge metric between y_true and y_pred. class Sum: Computes the (weighted) sum of the given values. class TopKCategoricalAccuracy: Computes how often targets are in the top K predictions. class TrueNegatives: Calculates the number of true negatives. class TruePositives: Calculates the number of true positives. Functions KLD(...): Computes Kullback-Leibler divergence loss between y_true and y_pred. MAE(...): Computes the mean absolute error between labels and predictions. MAPE(...): Computes the mean absolute percentage error between y_true and y_pred. MSE(...): Computes the mean squared error between labels and predictions. MSLE(...): Computes the mean squared logarithmic error between y_true and y_pred. binary_accuracy(...): Calculates how often predictions matches binary labels. binary_crossentropy(...): Computes the binary crossentropy loss. categorical_accuracy(...): Calculates how often predictions matches one-hot labels. categorical_crossentropy(...): Computes the categorical crossentropy loss. deserialize(...): Deserializes a serialized metric class/function instance. get(...): Retrieves a Keras metric as a function/Metric class instance. hinge(...): Computes the hinge loss between y_true and y_pred. kl_divergence(...): Computes Kullback-Leibler divergence loss between y_true and y_pred. kld(...): Computes Kullback-Leibler divergence loss between y_true and y_pred. kullback_leibler_divergence(...): Computes Kullback-Leibler divergence loss between y_true and y_pred. log_cosh(...): Logarithm of the hyperbolic cosine of the prediction error. logcosh(...): Logarithm of the hyperbolic cosine of the prediction error. mae(...): Computes the mean absolute error between labels and predictions. mape(...): Computes the mean absolute percentage error between y_true and y_pred. mean_absolute_error(...): Computes the mean absolute error between labels and predictions. mean_absolute_percentage_error(...): Computes the mean absolute percentage error between y_true and y_pred. mean_squared_error(...): Computes the mean squared error between labels and predictions. mean_squared_logarithmic_error(...): Computes the mean squared logarithmic error between y_true and y_pred. mse(...): Computes the mean squared error between labels and predictions. msle(...): Computes the mean squared logarithmic error between y_true and y_pred. poisson(...): Computes the Poisson loss between y_true and y_pred. serialize(...): Serializes metric function or Metric instance. sparse_categorical_accuracy(...): Calculates how often predictions matches integer labels. sparse_categorical_crossentropy(...): Computes the sparse categorical crossentropy loss. sparse_top_k_categorical_accuracy(...): Computes how often integer targets are in the top K predictions. squared_hinge(...): Computes the squared hinge loss between y_true and y_pred. top_k_categorical_accuracy(...): Computes how often targets are in the top K predictions.


tf.keras.metrics.Accuracy     View source on GitHub    Calculates how often predictions equal labels. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.Accuracy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.Accuracy
tf.keras.metrics.Accuracy(
    name='accuracy', dtype=None
)
 This metric creates two local variables, total and count that are used to compute the frequency with which y_pred matches y_true. This frequency is ultimately returned as binary accuracy: an idempotent operation that simply divides total by count. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.    Standalone usage:
m = tf.keras.metrics.Accuracy()
m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]])
m.result().numpy()
0.75

m.reset_states()
m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]],
               sample_weight=[1, 1, 0, 0])
m.result().numpy()
0.5
 Usage with compile() API: model.compile(optimizer='sgd',
              loss='mse',
              metrics=[tf.keras.metrics.Accuracy()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.AUC     View source on GitHub    Computes the approximate AUC (Area under the curve) via a Riemann sum. Inherits From: Metric, Layer, Module  View aliases  Main aliases
tf.metrics.AUC Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.AUC
tf.keras.metrics.AUC(
    num_thresholds=200, curve='ROC',
    summation_method='interpolation', name=None, dtype=None,
    thresholds=None, multi_label=False, label_weights=None
)
 This metric creates four local variables, true_positives, true_negatives, false_positives and false_negatives that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall. This value is ultimately returned as auc, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The num_thresholds variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. The quality of the approximation may vary dramatically depending on num_thresholds. The thresholds parameter can be used to manually specify thresholds which split the predictions more evenly. For best results, predictions should be distributed approximately uniformly in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC approximation may be poor if this is not the case. Setting summation_method to 'minoring' or 'majoring' can help quantify the error in the approximation by providing lower or upper bound estimate of the AUC. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  num_thresholds   (Optional) Defaults to 200. The number of thresholds to use when discretizing the roc curve. Values must be > 1.
  curve   (Optional) Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve.
  summation_method   (Optional) Specifies the Riemann summation method used. 'interpolation' (default) applies mid-point summation scheme for ROC. For PR-AUC, interpolates (true/false) positives but not the ratio that is precision (see Davis & Goadrich 2006 for details); 'minoring' applies left summation for increasing intervals and right summation for decreasing intervals; 'majoring' does the opposite.
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.
  thresholds   (Optional) A list of floating point values to use as the thresholds for discretizing the curve. If set, the num_thresholds parameter is ignored. Values should be in [0, 1]. Endpoint thresholds equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be automatically included with these to correctly handle predictions equal to exactly 0 or 1.
  multi_label   boolean indicating whether multilabel data should be treated as such, wherein AUC is computed separately for each label and then averaged across labels, or (when False) if the data should be flattened into a single label before AUC computation. In the latter case, when multilabel data is passed to AUC, each label-prediction pair is treated as an individual data point. Should be set to False for multi-class data.
  label_weights   (optional) list, array, or tensor of non-negative weights used to compute AUCs for multilabel data. When multi_label is True, the weights are applied to the individual label AUCs when they are averaged to produce the multi-label AUC. When it's False, they are used to weight the individual label predictions in computing the confusion matrix on the flattened data. Note that this is unlike class_weights in that class_weights weights the example depending on the value of its label, whereas label_weights depends only on the index of that label before flattening; therefore label_weights should not be used for multi-class data.    Standalone usage:
m = tf.keras.metrics.AUC(num_thresholds=3)
m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
# threshold values are [0 - 1e-7, 0.5, 1 + 1e-7]
# tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2]
# recall = [1, 0.5, 0], fp_rate = [1, 0, 0]
# auc = ((((1+0.5)/2)*(1-0))+ (((0.5+0)/2)*(0-0))) = 0.75
m.result().numpy()
0.75

m.reset_states()
m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9],
               sample_weight=[1, 0, 0, 1])
m.result().numpy()
1.0
 Usage with compile() API: model.compile(optimizer='sgd', loss='mse', metrics=[tf.keras.metrics.AUC()])

 Attributes
  thresholds   The thresholds used for evaluating AUC.    Methods interpolate_pr_auc View source
interpolate_pr_auc()
 Interpolation formula inspired by section 4 of Davis & Goadrich 2006. https://www.biostat.wisc.edu/~page/rocpr.pdf Note here we derive & use a closed formula not present in the paper as follows: Precision = TP / (TP + FP) = TP / P Modeling all of TP (true positive), FP (false positive) and their sum P = TP + FP (predicted positive) as varying linearly within each interval [A, B] between successive thresholds, we get Precision slope = dTP / dP = (TP_B - TP_A) / (P_B - P_A) = (TP - TP_A) / (P - P_A) Precision = (TP_A + slope * (P - P_A)) / P The area within the interval is (slope / total_pos_weight) times int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P} int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P} where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A) Bringing back the factor (slope / total_pos_weight) we'd put aside, we get slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight where dTP == TP_B - TP_A. Note that when P_A == 0 the above calculation simplifies into int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A) which is really equivalent to imputing constant precision throughout the first bucket having >0 true positives.

 Returns
  pr_auc   an approximation of the area under the P-R curve.    reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates confusion matrix statistics.

 Args
  y_true   The ground truth values.
  y_pred   The predicted values.
  sample_weight   Optional weighting of each example. Defaults to 1. Can be a Tensor whose rank is either 0, or the same rank as y_true, and must be broadcastable to y_true.

 Returns   Update op.


tf.keras.metrics.BinaryAccuracy     View source on GitHub    Calculates how often predictions match binary labels. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.BinaryAccuracy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.BinaryAccuracy
tf.keras.metrics.BinaryAccuracy(
    name='binary_accuracy', dtype=None, threshold=0.5
)
 This metric creates two local variables, total and count that are used to compute the frequency with which y_pred matches y_true. This frequency is ultimately returned as binary accuracy: an idempotent operation that simply divides total by count. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.
  threshold   (Optional) Float representing the threshold for deciding whether prediction values are 1 or 0.    Standalone usage:
m = tf.keras.metrics.BinaryAccuracy()
m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]])
m.result().numpy()
0.75

m.reset_states()
m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]],
               sample_weight=[1, 0, 0, 1])
m.result().numpy()
0.5
 Usage with compile() API: model.compile(optimizer='sgd',
              loss='mse',
              metrics=[tf.keras.metrics.BinaryAccuracy()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.BinaryCrossentropy     View source on GitHub    Computes the crossentropy metric between the labels and predictions. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.BinaryCrossentropy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.BinaryCrossentropy
tf.keras.metrics.BinaryCrossentropy(
    name='binary_crossentropy', dtype=None, from_logits=False,
    label_smoothing=0
)
 This is the crossentropy metric class to be used when there are only two label classes (0 and 1).

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.
  from_logits   (Optional )Whether output is expected to be a logits tensor. By default, we consider that output encodes a probability distribution.
  label_smoothing   (Optional) Float in [0, 1]. When > 0, label values are smoothed, meaning the confidence on label values are relaxed. e.g. label_smoothing=0.2 means that we will use a value of 0.1 for label 0 and 0.9 for label 1".    Standalone usage:
m = tf.keras.metrics.BinaryCrossentropy()
m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
m.result().numpy()
0.81492424

m.reset_states()
m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
               sample_weight=[1, 0])
m.result().numpy()
0.9162905
 Usage with compile() API: model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.BinaryCrossentropy()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.binary_accuracy     View source on GitHub    Calculates how often predictions matches binary labels.  View aliases  Main aliases
tf.metrics.binary_accuracy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.binary_accuracy
tf.keras.metrics.binary_accuracy(
    y_true, y_pred, threshold=0.5
)
 Standalone usage:
y_true = [[1], [1], [0], [0]]
y_pred = [[1], [1], [0], [0]]
m = tf.keras.metrics.binary_accuracy(y_true, y_pred)
assert m.shape == (4,)
m.numpy()
array([1., 1., 1., 1.], dtype=float32)

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  threshold   (Optional) Float representing the threshold for deciding whether prediction values are 1 or 0.

 Returns   Binary accuracy values. shape = [batch_size, d0, .. dN-1]


tf.keras.metrics.CategoricalAccuracy     View source on GitHub    Calculates how often predictions matches one-hot labels. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.CategoricalAccuracy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.CategoricalAccuracy
tf.keras.metrics.CategoricalAccuracy(
    name='categorical_accuracy', dtype=None
)
 You can provide logits of classes as y_pred, since argmax of logits and probabilities are same. This metric creates two local variables, total and count that are used to compute the frequency with which y_pred matches y_true. This frequency is ultimately returned as categorical accuracy: an idempotent operation that simply divides total by count. y_pred and y_true should be passed in as vectors of probabilities, rather than as labels. If necessary, use tf.one_hot to expand y_true as a vector. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.    Standalone usage:
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
                [0.05, 0.95, 0]])
m.result().numpy()
0.5

m.reset_states()
m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
                [0.05, 0.95, 0]],
               sample_weight=[0.7, 0.3])
m.result().numpy()
0.3
 Usage with compile() API: model.compile(
  optimizer='sgd',
  loss='mse',
  metrics=[tf.keras.metrics.CategoricalAccuracy()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.CategoricalCrossentropy     View source on GitHub    Computes the crossentropy metric between the labels and predictions. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.CategoricalCrossentropy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.CategoricalCrossentropy
tf.keras.metrics.CategoricalCrossentropy(
    name='categorical_crossentropy', dtype=None, from_logits=False,
    label_smoothing=0
)
 This is the crossentropy metric class to be used when there are multiple label classes (2 or more). Here we assume that labels are given as a one_hot representation. eg., When labels values are [2, 0, 1], y_true = [[0, 0, 1], [1, 0, 0], [0, 1, 0]].

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.
  from_logits   (Optional) Whether output is expected to be a logits tensor. By default, we consider that output encodes a probability distribution.
  label_smoothing   (Optional) Float in [0, 1]. When > 0, label values are smoothed, meaning the confidence on label values are relaxed. e.g. label_smoothing=0.2 means that we will use a value of 0.1 for label 0 and 0.9 for label 1"    Standalone usage:
# EPSILON = 1e-7, y = y_true, y` = y_pred
# y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON)
# y` = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]]
# xent = -sum(y * log(y'), axis = -1)
#      = -((log 0.95), (log 0.1))
#      = [0.051, 2.302]
# Reduced xent = (0.051 + 2.302) / 2
m = tf.keras.metrics.CategoricalCrossentropy()
m.update_state([[0, 1, 0], [0, 0, 1]],
               [[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
m.result().numpy()
1.1769392

m.reset_states()
m.update_state([[0, 1, 0], [0, 0, 1]],
               [[0.05, 0.95, 0], [0.1, 0.8, 0.1]],
               sample_weight=tf.constant([0.3, 0.7]))
m.result().numpy()
1.6271976
 Usage with compile() API: model.compile(
  optimizer='sgd',
  loss='mse',
  metrics=[tf.keras.metrics.CategoricalCrossentropy()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.CategoricalHinge     View source on GitHub    Computes the categorical hinge metric between y_true and y_pred. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.CategoricalHinge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.CategoricalHinge
tf.keras.metrics.CategoricalHinge(
    name='categorical_hinge', dtype=None
)

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.    Standalone usage:
m = tf.keras.metrics.CategoricalHinge()
m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
m.result().numpy()
1.4000001

m.reset_states()
m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
               sample_weight=[1, 0])
m.result().numpy()
1.2
 Usage with compile() API: model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.CategoricalHinge()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.categorical_accuracy     View source on GitHub    Calculates how often predictions matches one-hot labels.  View aliases  Main aliases
tf.metrics.categorical_accuracy Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.categorical_accuracy
tf.keras.metrics.categorical_accuracy(
    y_true, y_pred
)
 Standalone usage:
y_true = [[0, 0, 1], [0, 1, 0]]
y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
m = tf.keras.metrics.categorical_accuracy(y_true, y_pred)
assert m.shape == (2,)
m.numpy()
array([0., 1.], dtype=float32)
 You can provide logits of classes as y_pred, since argmax of logits and probabilities are same.

 Args
  y_true   One-hot ground truth values.
  y_pred   The prediction values.

 Returns   Categorical accuracy values.


tf.keras.metrics.CosineSimilarity     View source on GitHub    Computes the cosine similarity between the labels and predictions. Inherits From: Mean, Metric, Layer, Module  View aliases  Main aliases
tf.metrics.CosineSimilarity Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.CosineSimilarity
tf.keras.metrics.CosineSimilarity(
    name='cosine_similarity', dtype=None, axis=-1
)
 cosine similarity = (a . b) / ||a|| ||b|| See: Cosine Similarity. This metric keeps the average cosine similarity between predictions and labels over a stream of data.

 Args
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.
  axis   (Optional) Defaults to -1. The dimension along which the cosine similarity is computed.    Standalone usage:
# l2_norm(y_true) = [[0., 1.], [1./1.414], 1./1.414]]]
# l2_norm(y_pred) = [[1., 0.], [1./1.414], 1./1.414]]]
# l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
# result = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
#        = ((0. + 0.) +  (0.5 + 0.5)) / 2
m = tf.keras.metrics.CosineSimilarity(axis=1)
m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]])
m.result().numpy()
0.49999997

m.reset_states()
m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]],
               sample_weight=[0.3, 0.7])
m.result().numpy()
0.6999999
 Usage with compile() API: model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.CosineSimilarity(axis=1)])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates metric statistics. y_true and y_pred should have the same shape.

 Args
  y_true   Ground truth values. shape = [batch_size, d0, .. dN].
  y_pred   The predicted values. shape = [batch_size, d0, .. dN].
  sample_weight   Optional sample_weight acts as a coefficient for the metric. If a scalar is provided, then the metric is simply scaled by the given value. If sample_weight is a tensor of size [batch_size], then the metric for each sample of the batch is rescaled by the corresponding element in the sample_weight vector. If the shape of sample_weight is [batch_size, d0, .. dN-1] (or can be broadcasted to this shape), then each metric element of y_pred is scaled by the corresponding value of sample_weight. (Note on dN-1: all metric functions reduce by 1 dimension, usually the last axis (-1)).

 Returns   Update op.


tf.keras.metrics.deserialize     View source on GitHub    Deserializes a serialized metric class/function instance.  View aliases  Main aliases
tf.metrics.deserialize Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.deserialize
tf.keras.metrics.deserialize(
    config, custom_objects=None
)

 Arguments
  config   Metric configuration.
  custom_objects   Optional dictionary mapping names (strings) to custom objects (classes and functions) to be considered during deserialization.

 Returns   A Keras Metric instance or a metric function.


tf.keras.metrics.FalseNegatives     View source on GitHub    Calculates the number of false negatives. Inherits From: Metric, Layer, Module  View aliases  Main aliases
tf.metrics.FalseNegatives Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.FalseNegatives
tf.keras.metrics.FalseNegatives(
    thresholds=None, name=None, dtype=None
)
 If sample_weight is given, calculates the sum of the weights of false negatives. This metric creates one local variable, accumulator that is used to keep track of the number of false negatives. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  thresholds   (Optional) Defaults to 0.5. A float value or a python list/tuple of float threshold values in [0, 1]. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is true, below is false). One metric value is generated for each threshold value.
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.    Standalone usage:
m = tf.keras.metrics.FalseNegatives()
m.update_state([0, 1, 1, 1], [0, 1, 0, 0])
m.result().numpy()
2.0

m.reset_states()
m.update_state([0, 1, 1, 1], [0, 1, 0, 0], sample_weight=[0, 0, 1, 0])
m.result().numpy()
1.0
 Usage with compile() API: model.compile(optimizer='sgd',
              loss='mse',
              metrics=[tf.keras.metrics.FalseNegatives()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates the metric statistics.

 Args
  y_true   The ground truth values.
  y_pred   The predicted values.
  sample_weight   Optional weighting of each example. Defaults to 1. Can be a Tensor whose rank is either 0, or the same rank as y_true, and must be broadcastable to y_true.

 Returns   Update op.


tf.keras.metrics.FalsePositives     View source on GitHub    Calculates the number of false positives. Inherits From: Metric, Layer, Module  View aliases  Main aliases
tf.metrics.FalsePositives Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.FalsePositives
tf.keras.metrics.FalsePositives(
    thresholds=None, name=None, dtype=None
)
 If sample_weight is given, calculates the sum of the weights of false positives. This metric creates one local variable, accumulator that is used to keep track of the number of false positives. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values.

 Args
  thresholds   (Optional) Defaults to 0.5. A float value or a python list/tuple of float threshold values in [0, 1]. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is true, below is false). One metric value is generated for each threshold value.
  name   (Optional) string name of the metric instance.
  dtype   (Optional) data type of the metric result.    Standalone usage:
m = tf.keras.metrics.FalsePositives()
m.update_state([0, 1, 0, 0], [0, 0, 1, 1])
m.result().numpy()
2.0

m.reset_states()
m.update_state([0, 1, 0, 0], [0, 0, 1, 1], sample_weight=[0, 0, 1, 0])
m.result().numpy()
1.0
 Usage with compile() API: model.compile(optimizer='sgd',
              loss='mse',
              metrics=[tf.keras.metrics.FalsePositives()])
 Methods reset_states View source
reset_states()
 Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
 Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
    y_true, y_pred, sample_weight=None
)
 Accumulates the metric statistics.

 Args
  y_true   The ground truth values.
  y_pred   The predicted values.
  sample_weight   Optional weighting of each example. Defaults to 1. Can be a Tensor whose rank is either 0, or the same rank as y_true, and must be broadcastable to y_true.

 Returns   Update op.