mgcv::pcls()
文档中,提供以下代码提供单调增加的GAM模型的一个示例:
set.seed(1234) # added for reproducibility in this post only
x <- runif(100)*4-1;x <- sort(x);
f <- exp(4*x)/(1+exp(4*x)); y <- f+rnorm(100)*0.1; plot(x,y)
dat <- data.frame(x=x,y=y)
# Show regular spline fit (and save fitted object)
f.ug <- gam(y~s(x,k=10,bs="cr")); lines(x,fitted(f.ug))
# Create Design matrix, constraints etc. for monotonic spline....
sm <- smoothCon(s(x,k=10,bs="cr"),dat,knots=NULL)[[1]]
F <- mono.con(sm$xp); # get constraints
G <- list(X=sm$X,C=matrix(0,0,0),sp=f.ug$sp,p=sm$xp,y=y,w=y*0+1)
G$Ain <- F$A;G$bin <- F$b;G$S <- sm$S;G$off <- 0
p <- pcls(G); # fit spline (using s.p. from unconstrained fit)
fv<-Predict.matrix(sm,data.frame(x=x))%*%p
lines(x,fv,col=2)
这将产生以下图(如果使用set.seed(1234)
使用):问题:
lower
中的
upper
和
mono.con
界值。 例如
F<-mono.com(sm$xp, lower=0.1, upper=1.0)
,但这将返回以下值:
F$b
:
[1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
[25] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 -1.0
(即已将附加到lower
(和
-1*upper
同样增加2),但呼叫
F$b
返回以下几点:
dim(F$A)[1]
是否有一个修改示例代码,可以将单调增加的gam限制为以下图片中的蓝线之间:
相关代码是:
Error in pcls(G) : initial parameters not feasible
在构造不等式矩阵时,有一个错误,因为下限约束变为[0 0 0 0 0 ...] x> = 0.1而不是[1 0 0 0 0 0] x> = 0.1。我认为问题是
,?pcls
F<-mono.con(sm$xp, lower=0.1,upper=1)
F$A[4*(10-1)+1,1] <- 1
G <- list(X=sm$X,C=matrix(0,0,0),sp=f.ug$sp,p=scales::rescale(sm$xp,to=c(0.4,0.7)),y=y,w=y*0+1)
G$Ain <- F$A;G$bin <- F$b;G$S <- sm$S;G$off <- 0
p <- pcls(G)
> p
[1] 0.1000000 0.1346833 0.2752035 0.5562702 0.7425019 0.9762224 0.9891460 1.0000000 1.0000000 1.0000000
。这就是为什么我暂时添加
G$p
。