mgcv::gam
には、predict.gam
メソッドとtype = "lpmatrix"
メソッドを使用して(Q2)これを行う方法があります。
library(mgcv)
n <- 200
sig <- 2
dat <- gamSim(1,n=n,scale=sig)
b <- gam(y ~ s(x0) + s(I(x1^2)) + s(x2) + offset(x3), data = dat)
newd <- data.frame(x0=(0:30)/30, x1=(0:30)/30, x2=(0:30)/30, x3=(0:30)/30)
Xp <- predict(b, newd, type="lpmatrix")
##################################################################
## The following shows how to use use an "lpmatrix" as a lookup
## table for approximate prediction. The idea is to create
## approximate prediction matrix rows by appropriate linear
## interpolation of an existing prediction matrix. The additivity
## of a GAM makes this possible.
## There is no reason to ever do this in R, but the following
## code provides a useful template for predicting from a fitted
## gam *outside* R: all that is needed is the coefficient vector
## and the prediction matrix. Use larger `Xp'/ smaller `dx' and/or
## higher order interpolation for higher accuracy.
###################################################################
xn <- c(.341,.122,.476,.981) ## want prediction at these values
x0 <- 1 ## intercept column
dx <- 1/30 ## covariate spacing in `newd'
for (j in 0:2) { ## loop through smooth terms
cols <- 1+j*9 +1:9 ## relevant cols of Xp
i <- floor(xn[j+1]*30) ## find relevant rows of Xp
w1 <- (xn[j+1]-i*dx)/dx ## interpolation weights
## find approx. predict matrix row portion, by interpolation
x0 <- c(x0,Xp[i+2,cols]*w1 + Xp[i+1,cols]*(1-w1))
}
dim(x0)<-c(1,28)
fv <- x0%*%coef(b) + xn[4];fv ## evaluate and add offset
se <- sqrt(x0%*%b$Vp%*%t(x0));se ## get standard error
## compare to normal prediction
predict(b,newdata=data.frame(x0=xn[1],x1=xn[2],
x2=xn[3],x3=xn[4]),se=TRUE)
R外またはGAMモデルの行われるであろうにも予測ステップ全体のプロセスを経る:
?predict.gam
も私は以下再現例を、有しています。この例を少し修正して、モデル内のすべての項を評価し、スプライン以外の2つの項を持つようにする必要があります。本質的に同じことをしますが、スプライン項についてのみです。スプライン用のXp
行列の関連する列と行を見つけることを含む。次に、スプラインが中央に配置されているので、元に戻すこともできないこともあります。
例では、xn
ベクトル/マトリックスに適切な値を選択してください。これらはモデルのn
番目の用語の値に対応します。固定したい値をある平均値に設定し、スプラインに関連付けられた値を変更します。
を Rで実行している場合、スプライン共変量の値でスプラインを評価するほうが、他のモデルに入っているデータがあることが容易になります。もし、値のデータフレームを作成することによってで予測するれることを行い、次いでmod
は(mgcv::gam
介して)取り付けられGAMモデルである
predict(mod, newdata = newdat, type = "terms")
を使用し、newdat
は、各変数の列を含むデータフレームでありますモデル(パラメトリック項を含む);変化したくない項をある一定の平均値[データセット内の変数の平均]または因子の場合はあるレベルに設定する。 type = "terms"
部分は、newdat
に各行の行列を返します。スプライン項を含め、モデル内の各項の適合値に「貢献」します。スプラインに対応するこの行列の列を取るだけで、再び中央に配置されます。
おそらく私はあなたのQ1を誤解しました。ノットを制御する場合は、の引数をmgcv::gam
にしてください。デフォルトでは、mgcv::gam
はデータの極端にノットを配置し、残りの「ノット」はその間隔で均等に分散されます。 mgcv::gam
ノットを見つける - それはあなたのために配置し、knots
引数でそれらを配置する場所を制御することができます。
"スプラインを抽出する"ことはあまり簡単ではありませんが、私は間違っていることが判明しました。目的は2)あなたはグリッド上で 'predict'を使うことができます。すべての操作を行うことができるので、package :: rmsを使用します。 –
rmsを使ってどうやったらいいでしょうか? – Tom
準備が整っています(3)+ rcs(birth_year、3)%ia%rcs(wealth2、3)+ sex + residence + maternal_educ + (母集団、3)+ +富2 +性別+住居+母性_出生+誕生_order(データ=コロンビア2));関数(フィット) ' –