tfm.uplift.metrics.poisson_metrics.LogLoss

Computes the (weighted) poisson log loss sliced by treatment group.

Inherits From: LossMetric

Given labels y and the model's predictions x, the loss is computed as: loss = x - y * log(x) + [y * log(y) - y + 0.5 * log(2 * pi * y)]

Note that from a numerical perspective it is preferred to compute the loss from the model's logits as opposed to directly using its predictions, where logits = log(x) = log(prediction). In this case the loss is computed as: loss = exp(logits) - y * logits + [y * log(y) - y + 0.5 * log(2 * pi * y)]

Example standalone usage:

poisson_loss = poisson_metrics.LogLoss()
y_true = tf.constant([[1.0], [0.0]])
y_pred = types.TwoTowerTrainingOutputs(
    true_logits=tf.constant([[1.0], [0.0]]),
    is_treatment=tf.constant([[1], [0]]),
)
poisson_loss(y_true=y_true, y_pred=y_pred)
{
    "poisson_log_loss/treatment": 1.7182817  # exp(1) - 1 * 1
    "poisson_log_loss/control": 1.0  # exp(0) - 0 * 0
    "poisson_log_loss": 1.3591409  # (1.7182817 + 1.0) / 2
}

Example usage with the model.compile() API:

model.compile(
    optimizer="sgd",
    loss=TrueLogitsLoss(tf.nn.log_poisson_loss),
    metrics=[poisson_metrics.LogLoss()]
)

from_logits When y_pred is of type tf.Tensor, specifies whether y_pred represents the model's logits or predictions. Otherwise, when y_pred is of type TwoTowerTrainingOutputs, set this to True in order to compute the loss using the true logits.
compute_full_loss Specifies whether the full log loss will be computed. If True, the expression `[y_true * log(y_true) - y_true + 0.5 * log(2

  • pi * y_true)]will be added to the loss, otherwise the loss will be computed solely by the expression[y_pred - y_true * log(y_pred)]. </td> </tr><tr> <td>slice_by_treatment<a id="slice_by_treatment"></a> </td> <td> Specifies whether the loss should be sliced by the treatment indicator tensor. IfTrue, the metric's result will return the loss values sliced by the treatment group. Note that this can only be set toTruewheny_predis of typeTwoTowerTrainingOutputs. </td> </tr><tr> <td>name<a id="name"></a> </td> <td> Optional name for the instance. </td> </tr><tr> <td>dtype`
Optional data type for the instance.

Methods

call

This is where the layer's logic lives.

The call() method may not create state (except in its first invocation, wrapping the creation of variables or other resources in tf.init_scope()). It is recommended to create state, including tf.Variable instances and nested Layer instances, in __init__(), or in the build() method that is called automatically before call() executes for the first time.

Args
inputs Input tensor, or dict/list/tuple of input tensors. The first positional inputs argument is subject to special rules:

  • inputs must be explicitly passed. A layer cannot have zero arguments, and inputs cannot be provided via the default value of a keyword argument.
  • NumPy array or Python scalar values in inputs get cast as tensors.
  • TF-Keras mask metadata is only collected from inputs.
  • Layers are built (build(input_shape) method) using shape info from inputs only.
  • input_spec compatibility is only checked against inputs.
  • Mixed precision input casting is only applied to inputs. If a layer has tensor arguments in *args or **kwargs, their casting behavior in mixed precision should be handled manually.
  • The SavedModel input specification is generated using inputs only.
  • Integration with various ecosystem packages like TFMOT, TFLite, TF.js, etc is only supported for inputs and not for tensors in positional and keyword arguments.
*args Additional positional arguments. May contain tensors, although this is not recommended, for the reasons above.
**kwargs Additional keyword arguments. May contain tensors, although this is not recommended, for the reasons above. The following optional keyword arguments are reserved:
  • training: Boolean scalar tensor of Python boolean indicating whether the call is meant for training or inference.
  • mask: Boolean input mask. If the layer's call() method takes a mask argument, its default value will be set to the mask generated for inputs by the previous layer (if input did come from a layer that generated a corresponding mask, i.e. if it came from a TF-Keras layer with masking support).
  • Returns
    A tensor or list/tuple of tensors.

    merge_state

    Merges the state from one or more metrics.

    This method can be used by distributed systems to merge the state computed by different metric instances. Typically the state will be stored in the form of the metric's weights. For example, a tf.keras.metrics.Mean metric contains a list of two weight values: a total and a count. If there were two instances of a tf.keras.metrics.Accuracy that each independently aggregated partial state for an overall accuracy calculation, these two metric's states could be combined as follows:

    m1 = tf.keras.metrics.Accuracy()
    _ = m1.update_state([[1], [2]], [[0], [2]])
    m2 = tf.keras.metrics.Accuracy()
    _ = m2.update_state([[3], [4]], [[3], [4]])
    m2.merge_state([m1])
    m2.result().numpy()
    0.75

    Args
    metrics an iterable of metrics. The metrics must have compatible state.

    Raises
    ValueError If the provided iterable does not contain metrics matching the metric's required specifications.

    reset_state

    View source

    Resets all of the metric state variables.

    This function is called between epochs/steps, when a metric is evaluated during training.

    result

    View source

    Computes and returns the scalar metric value tensor or a dict of scalars.

    Result computation is an idempotent operation that simply calculates the metric value using the state variables.

    Returns
    A scalar tensor, or a dictionary of scalar tensors.

    update_state

    View source

    Updates the overall, control and treatment losses.

    Args
    y_true A tf.Tensor with the targets.
    y_pred Model outputs. If of type TwoTowerTrainingOutputs, the treatment indicator tensor is used to slice the true logits or true predictions into control and treatment losses.
    sample_weight Optional sample weight to compute weighted losses. If given, the sample weight will also be sliced by the treatment indicator tensor to compute the weighted control and treatment losses.

    Raises
    TypeError if y_pred is not of type TwoTowerTrainingOutputs.