【问题标题】:how to implement own error function while using neuralnet package in R?在 R 中使用神经网络包时如何实现自己的误差函数?
【发布时间】:2014-10-20 01:58:24
【问题描述】:

我正在尝试在 R 中的神经网络包中实现自定义错误函数。

通常'sse'和'ce'代表误差平方和,交叉熵用于计算误差。谁能提供有关如何实现自己的误差函数的详细信息。虽然包装上说我们可以使用自定义的错误功能,但用户 Manuel 对此没有任何帮助。

【问题讨论】:

    标签: r function neural-network implementation


    【解决方案1】:

    我遇到了同样的问题。这是我收到的解决方案/帮助。 您可以使用 R 函数的通常定义 (function(x,y){...})。因此,误差函数必须是 function(x,y) 类型,其中 x 是拟合值,y 是真实值。

    请参考以下示例。

    library(neuralnet)
    
    AND <- c(rep(0,7),1)
    OR <- c(0,rep(1,7))
    binary.data <- data.frame(expand.grid(c(0,1), c(0,1), c(0,1)), AND, OR)
    set.seed(3)
    print(net <- neuralnet(AND+OR~Var1+Var2+Var3,  binary.data, hidden=0, rep=10, err.fct="sse", linear.output=FALSE))
    
    #Call: neuralnet(formula = AND + OR ~ Var1 + Var2 + Var3, data = binary.data,     hidden = 0, rep = 10, err.fct = "sse", linear.output = FALSE)
    #
    #10 repetitions were calculated.
    #
    #Error Reached Threshold Steps
    #7  0.04043122185    0.008248439644   116
    #5  0.04426319054    0.009619409680   124
    #8  0.04698485282    0.007947430014   117
    #2  0.04931335384    0.008792873261    88
    #1  0.04965332555    0.009631079320    89
    #4  0.05396400022    0.009092193542    96
    #6  0.05488395412    0.009990028287   124
    #3  0.06383087672    0.009964206587    94
    #10 0.51657348285    0.008602371325    51
    #9  0.52514202592    0.007890927099    40
    
    
    set.seed(3)
    custom <- function(x,y){1/2*(y-x)^2}
    print(net <- neuralnet(AND+OR~Var1+Var2+Var3,  binary.data, hidden=0, rep=10, linear.output=FALSE, err.fct=custom))
    
    #Call: neuralnet(formula = AND + OR ~ Var1 + Var2 + Var3, data = binary.data,     hidden = 0, rep = 10, err.fct = custom, linear.output = FALSE)
    #
    #10 repetitions were calculated.
    #
    #Error Reached Threshold Steps
    #7  0.04043122185    0.008248439644   116
    #5  0.04426319054    0.009619409680   124
    #8  0.04698485282    0.007947430014   117
    #2  0.04931335384    0.008792873261    88
    #1  0.04965332555    0.009631079320    89
    #4  0.05396400022    0.009092193542    96
    #6  0.05488395412    0.009990028287   124
    #3  0.06383087672    0.009964206587    94
    #10 0.51657348285    0.008602371325    51
    #9  0.52514202592    0.007890927099    40
    

    您基本上可以使用所有可以区分的误差函数。

    【讨论】:

    • 好点。但是,当将交叉熵写为 sum (...) 时,R 抱怨无法区分。如何解决?
    • @FilippoMazza:查看源代码似乎不需要 sum() 函数,因为它自动包裹在 err.fct 周围。交叉熵是 err.fct
    • 当我尝试运行第二个:neuralnet 命令时,我收到以下错误:Error in calculate.gradients(weights = weights, length.weights = length.weights, dims [product 16] do not match the length of object [32]。这是我的sessionInfoi.ibb.co/r6hvvTm/image.png
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2011-10-31
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    相关资源
    最近更新 更多