Skip to contents

Custom metric function

Usage

custom_metric(name, metric_fn)

Arguments

name

name used to show training progress output

metric_fn

An R function with signature function(y_true, y_pred) that accepts tensors.

Value

A callable function with a __name__ attribute.

Details

You can provide an arbitrary R function as a custom metric. Note that the y_true and y_pred parameters are tensors, so computations on them should use op_* tensor functions.

Use the custom_metric() function to define a custom metric. Note that a name ('mean_pred') is provided for the custom metric function: this name is used within training progress output.

If you want to save and load a model with custom metrics, you should also call register_keras_serializable(), or specify the metric in the call the load_model(). For example: load_model("my_model.keras", c('mean_pred' = metric_mean_pred)).

Alternatively, you can wrap all of your code in a call to with_custom_object_scope() which will allow you to refer to the metric by name just like you do with built in keras metrics.

Alternative ways of supplying custom metrics:

  • custom_metric(): Arbitrary R function.

  • metric_mean_wrapper(): Wrap an arbitrary R function in a Metric instance.

  • Create a custom Metric() subclass.