Search code examples
rtensorflowkerasrstudioimage-classification

Keras in R - full list of metrics using compile()


I am using Keras in RStudio for binary image classification, but am having trouble trying to access the full list of in-built metrics available in the package when compiling my model. I know that Keras has in built metrics like True Positive, True Negative, etc.

model1 %>% compile(loss = "binary_crossentropy",
                   optimizer = "rmsprop",
                   metrics = "accuracy")

There's a lot of information online on how to access these using Python, but I cannot find any instruction with R.

?compile only gives mean squared error (mse) and accuracy as examples of what I can input under metrics. I'd rather avoid having to write a custom metric if I can (partly also because I don't know how to produce a confusional matrix from my model in R to write my own custom metric).

Any help would be appreciated.


Solution

  • Have a look here: https://keras.posit.co/reference/Metric.html

    Scroll down to the heading saying "See also". There you'll find available metrics on top of those used in the example.

    Given the reference above, the following approach should work for calling other metrics:

    #------
    # Load keras
    #------
    library(keras3)
    
    #------
    # prepare data - define your training and test datasets 
    #------
    yourtraindata
    yourtestdata
    
    #------
    # compile model with loss function, optimizer, and metrics after sequential setup
    # included exemplary metrics: TP, TN, FP, FN
    #------
    model |> compile(
    loss = "binary_crossentropy", 
    optimizer = "rmsprop", 
    metrics = c(metric_true_positives(), metric_true_negatives(), metric_false_negatives(), metric_false_positives())
    )