Thursday, 19 July 2018

Custom Loss Function in R Keras

I want to calculate weighted mean squared error, where weights is one vector in the data. I wrote a custom code based on the suggestions available on stack overflow.

The function is provided below:

weighted_mse <- function(y_true, y_pred,weights){
  # convert tensors to R objects
  K        <- backend()
  y_true   <- K$eval(y_true)
  y_pred   <- K$eval(y_pred)
  weights  <- K$eval(weights)

  # calculate the metric
  loss <- sum(weights*((y_true - y_pred)^2)) 

  # convert to tensor
  return(K$constant(loss))
  }

However, I am not sure how to pass the custom function to the compiler. It would be great if someone can help me. Thank you.

model      <- model %>% compile(
                loss = 'mse', 
                optimizer = 'rmsprop',
                metrics = 'mse')

Regards



from Custom Loss Function in R Keras

No comments:

Post a Comment