使用 Keras 在 R studio 中编写损失函数

Writing a loss function in R studio using Keras

所以我想在 Keras 的 Rstudio 中编写自定义损失函数。当函数产生被低估的预测时,我基本上想惩罚更多。但是我不知道如何访问张量的成员。

到目前为止,这是我尝试过的:

myloss <- function(y_true, y_pred){

    penalize = k_flatten(y_pred) - k_flatten(y_true);
    penalize_pos = penalize >= 0
    penalize_neg = penalize < 0
    # I cannot find a mask function to turn penalize_pos into actual indecies
    #tried this but did not work
    A = penalize$eval()[penalize_pos$eval()]
    B = penalize$eval()[penalize_neg$eval()]

    return(sum(abs(A) + abs(B)*10))

}

我想知道你有什么建议。谢谢

我遇到了同样的问题。我知道已经晚了,但这是我在搜索时找到的解决方案。 This website 有一个很好的教程,我觉得很有用。

Like the Python functions, the custom loss functions for R need to operate on tensor objects rather than R primitives. In order to perform these operations, you need to get a reference to the backend using backend(). In my system configuration, this returns a reference to tensorflow.

它还包括以下代码片段:

# Mean Log Absolute Error
MLAE <- function( y_true, y_pred ) {
  K <- backend()
  K$mean( K$abs( K$log( K$relu(y_true *1000 ) + 1 ) - 
      K$log( K$relu(y_pred*1000 ) + 1)))
}
# Mean Squared Log Absolute Error
MSLAE <- function( y_true, y_pred ) {
  K <- backend()
  K$mean( K$pow( K$abs( K$log( K$relu(y_true *1000 ) + 1 ) - 
    K$log( K$relu(y_pred*1000 ) + 1)), 2))
}

注意 K <- backend() 调用,它允许您对张量对象进行操作。