R Keras中的自定义丢失功能

Sum*_*mit 6 python r keras loss-function

我想计算加权均方误差,其中权重是数据中的一个向量.我根据堆栈溢出提供的建议编写了一个自定义代码.

该功能如下:

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))
  }
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何将自定义函数传递给编译器.如果有人可以帮助我会很棒.谢谢.

model      <- model %>% compile(
                loss = 'mse', 
                optimizer = 'rmsprop',
                metrics = 'mse')
Run Code Online (Sandbox Code Playgroud)

问候

Dan*_*ler 7

你不能eval在损失函数中。这将破坏图形。

您应该只使用sample_weightfit方法的参数:https : //keras.rstudio.com/reference/fit.html

##not sure if this is valid R, but 
##at some point you will call `fit` for training with `X_train` and `Y_train`, 
##so, just add the weights.
history <- model$fit(X_train, Y_train, ..., sample_weight = weights)
Run Code Online (Sandbox Code Playgroud)

这就是全部(不要使用自定义损失)。


只是为了知识 - 将损失函数传递给 compile

仅适用于采用y_true和 的函数y_pred。(如果您正在使用则不需要sample_weights

model      <- model %>% compile(
            loss = weighted_mse, 
            optimizer = 'rmsprop',
            metrics = 'mse')
Run Code Online (Sandbox Code Playgroud)

但这不起作用,您需要类似于@spadarian 创建的包装器的东西。

此外,保持数据和权重之间的相关性将非常复杂,因为 Keras 会分批划分您的数据,也因为数据会被打乱。