我正在尝试使用R包神经网络中预先实现的“logistic”和“tanh”之外的激活函数。具体来说,我想使用整流线性单位(ReLU)f(x)= max {x,0}。请参阅下面的代码。
我相信如果由(例如)
定义,我可以使用自定义函数custom <- function(a) {x*2}
但如果我设置max(x,0)而不是x * 2,则R告诉我'max不在衍生表中',并且'&gt;'相同运营商。所以我正在寻找一个明智的解决方法,因为我认为在这种情况下max的数值积分不会成为问题。
nn <- neuralnet(
as.formula(paste("X",paste(names(Z[,2:10]), collapse="+"),sep="~")),
data=Z[,1:10], hidden=5, err.fct="sse",
act.fct="logistic", rep=1,
linear.output=TRUE)
有什么想法吗?我有点困惑,因为我认为neuralnet
包不会进行分析区分。
答案 0 :(得分:13)
neuralnet
包的内部将尝试区分提供给act.fct
的任何功能。您可以看到源代码here。
在第211行,您将找到以下代码块:
if (is.function(act.fct)) {
act.deriv.fct <- differentiate(act.fct)
attr(act.fct, "type") <- "function"
}
differentiate
函数是deriv
函数的更复杂用法,您也可以在上面的源代码中看到它。因此,目前无法向max(0,x)
提供act.fct
。它需要在代码中放置一个例外来识别ReLU并且知道派生词。获取源代码,添加它并提交给维护者进行扩展(但这可能有点多)将是一个很好的练习。
但是,关于明智的解决方法,您可以使用softplus function,这是ReLU的平滑近似值。您的自定义函数如下所示:
custom <- function(x) {log(1+exp(x))}
您也可以在R中查看此近似值:
softplus <- function(x) log(1+exp(x))
relu <- function(x) sapply(x, function(z) max(0,z))
x <- seq(from=-5, to=5, by=0.1)
library(ggplot2)
library(reshape2)
fits <- data.frame(x=x, softplus = softplus(x), relu = relu(x))
long <- melt(fits, id.vars="x")
ggplot(data=long, aes(x=x, y=value, group=variable, colour=variable))+
geom_line(size=1) +
ggtitle("ReLU & Softplus") +
theme(plot.title = element_text(size = 26)) +
theme(legend.title = element_blank()) +
theme(legend.text = element_text(size = 18))
答案 1 :(得分:3)
您可以使用可微函数来近似最大函数,例如:
custom <- function(x) {x/(1+exp(-2*k*x))}
变量k确定近似的精度。
其他近似值可以从第34节中的方程得出;解析近似值&#34;:https://en.wikipedia.org/wiki/Heaviside_step_function