用R计算黄土拟合曲线的最小/最大斜率?

时间:2012-08-29 17:11:03

标签: r ggplot2 curve-fitting

相关: R: Marking slope changes in LOESS curve using ggplot2
这个问题是试图找到最小/最大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)

例如,这是我的数据的训练神经网络的结果:

library(ggplot2)
ggplot(nn, aes(x=x, y=y, colour=factor(group))) + 
geom_point() + stat_smooth(method="loess", se=F)

nn

同样,这是一个rbf模型:

ggplot(rbf, aes(x=x, y=y, colour=factor(group))) + 
geom_point() + stat_smooth(method="loess", se=F)

rbf

RBF模型更好地拟合数据,并且与变量的背景知识更加一致。我想过尝试计算拟合线的最小/最大斜率,以便用陡峭的悬崖修剪出NN,而不是更柔和的曲线。识别交叉线将是另一种修剪方式,但这是一个不同的问题。

感谢您的任何建议。


注意:我在这里使用ggplot2并相应地标记了问题,但这并不意味着无法用其他功能完成。我只是想直观地说明我为什么要这样做。我想一个循环可以用y 1 -y 0 / x 1 -x 0 来做到这一点,但也许有更好的方法。?

2 个答案:

答案 0 :(得分:3)

我认为最简单的解决方案是使用第一个差异(使用函数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

答案 1 :(得分:2)

我正在为超快速交易编写一个神经网络。一开始我使用Loess或Lowess来拟合时间序列,但我想要的是光滑的衍生物,而Loess并不提供。甚至,如果你自己实现黄土并使用每个点的正交多项式来计算导数,你会得到奇怪的结果。这是有原因的。

你的问题的解决方案可以在Graciela Boente的论文中找到:回归函数的高阶导数的鲁棒估计。该公式在第3页。该论文可在互联网上免费获取。一旦获得了值和导数,就可以使用它来唯一地定义三次样条,这将给出连续的导数。

我不熟悉R