您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:21:32 python 字数 2632 阅读 524 来源 www.jb51.cc/python

我想计算加权均方误差,其中权重是数据中的一个向量.我根据堆栈溢出提供的建议编写了一个自定义代码.该功能如下:weighted_mse <- function(y_true, y_pred,weights){ # convert tensors to R objects K <- backend() y_true &l

概述

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

功能如下:

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会分批分割您的数据,也因为数据会被洗牌.

总结

以上是编程之家为你收集整理的python – R Keras中的自定义丢失函数全部内容,希望文章能够帮你解决python – R Keras中的自定义丢失函数所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶