【问题标题】:Calculate min/max slope of loess fitted curve with R?用R计算黄土拟合曲线的最小/最大斜率?
【发布时间】:2012-08-29 17:11:02
【问题描述】:

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

同样,这是一个 rbf 模型:

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

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

感谢您的任何建议。


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

【问题讨论】:

  • numericDeriv(my_loess$y) 够吗?
  • @CarlWitthoft:我对 R 不够熟悉,不知道 my_loess 会是什么。
  • @Hendy 抱歉:这是loess 返回的对象的简写,即my_loess &lt;- loess(rbf)
  • @CarlWitthoft 我需要传递更多选项吗?我用my_loess &lt;- loess(x~y, data=rbf)numericDeriv(my_loess$y) 做了你的建议,我得到一个错误:Error in length(theta) : 'theta' is missing。很抱歉让你引导我完成所有事情!

标签: r ggplot2 curve-fitting


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    我不熟悉R

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多