加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – R Keras中的自定义丢失函数

发布时间:2020-12-16 22:27:07 所属栏目:Python 来源:网络整理
导读:我想计算加权均方误差,其中权重是数据中的一个向量.我根据堆栈溢出提供的建议编写了一个自定义代码. 该功能如下: weighted_mse 但是,我不知道如何将自定义函数传递给编译器.如果有人可以帮助我会很棒.谢谢. model 问候 最佳答案 你无法评估损失的功能.这将

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

该功能如下:

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

问候

最佳答案
你无法评估损失的功能.这将破坏图表.

您应该只使用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)

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

只是为了知识 – 传递损失函数进行编译

仅适用于采用y_true和y_pred的函数. (如果您使用的是sample_weights,则没有必要)

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

但这不起作用,你需要类似于@spadarian创建的包装器.

此外,保持数据和权重之间的相关性将非常复杂,因为Keras会分批分割您的数据,也因为数据会被洗牌.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读