如何使用smooth.spline()函数制作单调(增加)平滑样条曲线?

Mic*_*ton 9 r spline

我有严格增加的数据,并且smooth.spline()由于易于使用此功能,因此如果可能的话,还希望适应单调增加的平滑样条函数.

例如,我可以使用以下示例有效地复制我的数据:

testx <- 1:100
testy <- abs(rnorm(length(testx)))^3
testy <- cumsum(testy)
plot(testx,testy)
sspl <- smooth.spline(testx,testy)
lines(sspl,col="blue")
Run Code Online (Sandbox Code Playgroud)

这不一定随处可见.有什么建议?

Nic*_*ich 10

这不会使用,smooth.spline()但是splinefun(..., method="hyman")它将适合单调增加的样条并且也易于使用.例如:

testx <- 1:100
testy <- abs(rnorm(length(testx)))^3
testy <- cumsum(testy)
plot(testx,testy)
sspl <- smooth.spline(testx,testy)
lines(sspl,col="blue")
tmp <- splinefun(x=testx, y=cumsum(testy), method="hyman")
lines(testx[-1], diff(tmp(testx)), col="red")
Run Code Online (Sandbox Code Playgroud)

得到下图(红色是单调递增样条的值) 在此输入图像描述

从帮助文件splinefun:"方法"hyman"计算单调三次样条使用Hyman过滤方法="fmm"适合严格单调输入.(在R 2.15.2中添加.)"

  • `splinefun`正是我所需要的.对于未来的读者:`splinefun`返回一个你可以直接调用的新函数,并且不返回传统R意义上的拟合模型.要使用此拟合样条函数预测新值,请调用新创建的函数并传入新数据.这取代了你习惯使用传统模型拟合的`predict`.Eg,`MonotonicSpline < - splinefun(x = toFit $ x,y = toFit $ y,method ="hyman"); monotonicFit < - MonotonicSpline(inputVector)` (2认同)
  • 仅当所有原始数据实际上单调递增时,即数据中没有噪声时,这才有效(否则 splinefun 将返回错误)。如果有,那么您可以在骗局或 cob 包中使用形状约束样条线,如下所述...... (2认同)

Tom*_*ers 6

您可以为此使用形状约束样条,例如使用scam包:

require(scam)
fit = scam(testy~s(testx, k=100, bs="mpi", m=5), 
            family=gaussian(link="identity"))
plot(testx,testy)
lines(testx,predict(fit),col="red")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或者,如果您想使用 L1 损失而不是 L2 损失,后者对异常值不太敏感,您也可以使用该cobs包...

与上述解决方案相比,此方法的优点在于,如果由于存在噪声,原始数据可能不是 100% 单调,它也可以工作......