作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要将样条曲线拟合到一组数据,并且需要使结果函数单调递减和凸出。我传递给splinefun的数据可以保证具有这些属性,但这不能保证结果函数是凸的。有什么方法可以将样条曲线拟合到一组数据,并要求结果函数为凸函数?
最佳答案
首先提供一些示例数据:
x = c(0,1,2,3,4,5,6)
y = c(2,1, 0.59, 0.27, 0.25, -0.23, -0.45)
dat <- data.frame(x=x,y=y)
splinefun(x,y,"monoH.FC")
来完成单调样条,如@fang所示。
# Setting up Monotonic Spline
MonoSpline = splinefun(x,y,"monoH.FC")
#Getting Ready for plotting Monotonic Spline
xArray = seq(0,6,0.01)
MonoResult = MonoSpline(xArray)
scam
包。然后,我们可以:
# Setting up Monotonic Convex Spline
# install.packages("scam")
require(scam)
MonoConvexSpline <- scam(y~s(x,k=4,bs="mdcx",m=1),data=dat)
MonoConvexSplinePredict =function(Test){
predict.scam(MonoConvexSpline,data.frame(x = Test))
}
#Getting Ready for plotting Monotonic Convex Spline
MonoConvexSplineResult = MonoConvexSplinePredict(xArray)
bs="mdcx"
表示我们希望减少凸的样条曲线。如果要增加凸面,减少凹面等,请查找适当的bs
值here。 splinefun(x,y,"monoH.FC")
函数中,则会出现错误。 scam
函数中,则仍然会得到样条曲线。数据被改变,使得小的凸面被改变为凸面。对此没有警告,但是请小心,因为您的数据看起来可能完全不同。例如,下面的绘图是使用与上面相同的代码制作的,不同的是我们使用bs="mdcv"
来减少凹面函数:# Convex Cobs Spline
library(cobs)
spCobs = cobs(x , y, constraint = c("decrease", "convex"), nknots = 8)
spCobsResults = predict(spCobs, xArray)[,2]
Plot = qplot(xlab = "x", ylab = "y")
Plot = Plot + geom_line(aes(xArray,MonoResult , colour = "Monotonic Spline" ))
Plot = Plot + geom_line(aes(xArray,MonoConvexSplineResult, colour = "Monotonic Convex scam Spline"))
Plot = Plot + geom_line(aes(xArray,spCobsResults , colour = "Monotonic Convex cobs Spline"))
Plot
scam
函数预测点所花的时间要长于# Prediction
library(microbenchmark)
microbenchmark(
MonoSpline(xArray),
predict.scam(MonoConvexSpline,data.frame(x = xArray)),
predict(spCobs, xArray)[,2]
)
Unit: microseconds
expr min lq mean median uq max neval
MonoSpline(xArray) 141.540 147.8175 223.3695 156.9490 167.9830 1593.456 100
predict.scam(MonoConvexSpline, data.frame(x = xArray)) 2778.655 2838.0095 3161.2282 2914.8665 3153.4285 6168.741 100
predict(spCobs, xArray)[, 2] 125.179 133.1690 155.1226 145.1535 162.2755 366.784 100
# Calculating Spline
library(microbenchmark)
microbenchmark(
splinefun(x,y,"monoH.FC"),
scam(y~s(x,k=4,bs="mdcx",m=1),data=dat),
cobs(x , y, constraint = c("decrease", "convex"), nknots = 8)
)
Unit: microseconds
expr min lq mean median uq max neval
splinefun(x, y, "monoH.FC") 90.175 127.462 411.6407 153.7155 198.993 24877.47 100
scam(y ~ s(x, k = 4, bs = "mdcx", m = 1), data = dat) 166769.270 196719.139 231631.5321 224372.7940 265074.525 355734.37 100
cobs(x, y, constraint = c("decrease", "convex"), nknots = 8) 145511.335 172887.618 203786.0940 202997.4795 228688.607 347661.29 100
关于要求花键凸出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109086/
我是一名优秀的程序员,十分优秀!