Hen*_*ndy 5 r curve-fitting ggplot2
相关: R:使用ggplot2在LOESS曲线中标记斜率变化
此问题试图找到最小值/最大值y(斜率= 0); 我想找到最小值/最大值
对于背景,我正在进行一些不同的建模技术,并且我认为在迭代神经网络结果时我可能会使用斜率来衡量随机种子产生的最佳模型.
获取数据:
nn <- read.csv("http://pastebin.com/raw.php?i=6SSCb3QR", header=T)
rbf <- read.csv("http://pastebin.com/raw.php?i=hfmY1g46", header=T)
Run Code Online (Sandbox Code Playgroud)
举个例子,这是我的数据的训练神经网络的结果:
library(ggplot2)
ggplot(nn, aes(x=x, y=y, colour=factor(group))) +
geom_point() + stat_smooth(method="loess", se=F)
Run Code Online (Sandbox Code Playgroud)

同样,这是一个rbf模型:
ggplot(rbf, aes(x=x, y=y, colour=factor(group))) +
geom_point() + stat_smooth(method="loess", se=F)
Run Code Online (Sandbox Code Playgroud)

RBF模型更好地拟合数据,并且与变量的背景知识更加一致.我想过尝试计算拟合线的最小/最大斜率,以便用陡峭的悬崖修剪出NN,而不是更柔和的曲线.识别交叉线将是另一种修剪方式,但这是一个不同的问题.
谢谢你的任何建议.
注意:我ggplot2在这里使用并相应地标记了问题,但这并不意味着它无法用其他功能完成.我只是想直观地说明我为什么要这样做.我想一个循环可以用y 1 -y 0/x 1 -x 0来做到这一点,但也许有更好的方法.
我认为最简单的解决方案是使用一阶差分(使用函数diff)作为一阶导数的近似值。
slope.loess <-function(X, data){
# First your loess function:
my_loess <- loess(y~x, data=data, subset=data$group==X, degree=2)
# Then the first difference
first_diff <- diff(my_loess$fitted)
# Then the corresponding x and y values for the minima and maxima
res <- cbind(my_loess$x[c(which.min(first_diff), which.max(first_diff))],
my_loess$fitted[c(which.min(first_diff), which.max(first_diff))])
colnames(res) <- c("x", "y")
rownames(res) <- c("min", "max")
res
}
#Then apply the function to each group
slope.rbf <- lapply(levels(rbf$group), FUN=slope.loess, data=rbf)
names(slope.rbf) <- levels(rbf$group)
slope.rbf
$A
x y
min 3.310345 20.30981
max 7.724138 18.47787
$B
x y
min 3.310345 21.75368
max 7.724138 20.06883
$C
x y
min 3.310345 23.53051
max 7.724138 21.47636
$D
x y
min 4.413793 25.02747
max 0.000000 26.22230
$E
x y
min 4.413793 27.45100
max 0.000000 27.39809
Run Code Online (Sandbox Code Playgroud)