Custom metric function

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.

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 backend 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 specify the metric in the call the load_model_hdf5(). For example: load_model_hdf5("my_model.h5", 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.

Documentation on the available backend tensor functions can be found at https://keras.rstudio.com/articles/backend.html#backend-functions.

Alternative ways of supplying custom metrics:

  • custom_metric(): Arbitrary R function.

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

  • subclass keras$metrics$Metric: see ?Metric for example.

See also