R Keras 中的自定义损失函数

Custom Loss Function in R Keras

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

函数如下:

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))
  }

但是,我不确定如何将自定义函数传递给编译器。如果有人可以帮助我,那就太好了。谢谢你。

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

此致

我没有将 Keras 与 R 一起使用,但是按照 documentation 中的示例,这可能应该有效:

weighted_mse <- function(y_true, y_pred, weights){
    K        <- backend()
    weights  <- K$variable(weights)
    # calculate the metric
    loss <- K$sum(weights * (K$pow(y_true - y_pred, 2))) 
    loss
}

metric_weighted_mse <- custom_metric("weighted_mse", function(y_true, y_pred) {
    weighted_mse(y_true, y_pred, weights)
})

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

请注意,我正在为损失函数使用包装器,因为它有一个额外的参数。此外,损失函数将输入作为张量处理,这就是为什么您应该使用 K$variable(weights).

转换权重

你不能eval损失函数。这会破坏图形。

您应该只使用 fit 方法的 sample_weight 参数: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)

仅此而已(不要使用自定义损失)。


仅供参考 - 将损失函数传递给 compile

仅适用于采用 y_truey_pred 的函数。 (如果您使用 sample_weights 则不需要)

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

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

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