[英]How to extract the underlying coefficients from fitting a linear b spline regression in R?
例如,以下一級結,樣條曲線:
library(splines)
library(ISLR)
age.grid = seq(range(Wage$age)[1], range(Wage$age)[2])
fit.spline = lm(wage~bs(age, knots=c(30), degree=1), data=Wage)
pred.spline = predict(fit.spline, newdata=list(age=age.grid), se=T)
plot(Wage$age, Wage$wage, col="gray")
lines(age.grid, pred.spline$fit, col="red")
# NOTE: This is **NOT** the same as fitting two piece-wise linear models becase
# the spline will add the contraint that the function is continuous at age=30
# fit.1 = lm(wage~age, data=subset(Wage,age<30))
# fit.2 = lm(wage~age, data=subset(Wage,age>=30))
有沒有一種方法可以提取結之前和之后的線性模型(及其系數)? 也就是說,如何在age=30
切入點age=30
之前和之后提取兩個線性模型?
使用summary(fit.spline)
產生系數,但是(據我所知)它們對於解釋沒有意義。
您可以像這樣從fit.spline
手動提取系數
summary(fit.spline)
Call:
lm(formula = wage ~ bs(age, knots = 30, degree = 1), data = Wage)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 54.19 4.05 13.4 <2e-16 ***
bs(age, knots = 30, degree = 1)1 58.43 4.61 12.7 <2e-16 ***
bs(age, knots = 30, degree = 1)2 68.73 4.54 15.1 <2e-16 ***
---
range(Wage$age)
## [1] 18 80
## coefficients of the first model
a1 <- seq(18, 30, length.out = 10)
b1 <- seq(54.19, 58.43+54.19, length.out = 10)
## coefficients of the second model
a2 <- seq(30, 80, length.out = 10)
b2 <- seq(54.19 + 58.43, 54.19 + 68.73, length.out = 10)
plot(Wage$age, Wage$wage, col="gray", xlim = c(0, 90))
lines(x = a1, y = b1, col = "blue" )
lines(x = a2, y = b2, col = "red")
如果您想要像線性模型一樣的斜率系數,則可以簡單地使用
b1 <- (58.43)/(30 - 18)
b2 <- (68.73 - 58.43)/(80 - 30)
請注意,在fit.spline
,截距是指age = 18
時的wage
值,而在線性模型中,截距是指age = 0
時的wage
值。
當您在bspline回歸中預先指定自由度時,主要是完成提取結的操作。 例:
fit.spline = lm(工資〜bs(年齡,df = 5),數據=工資)
attr(bs(age,df = 5),“結”)
33.33333%66.66667%
37 48
可以在第293頁的ISLR書(您似乎正在使用)中找到一個示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.