拓端tecdat|基於R統計軟件的三次樣條和平滑樣條模型數據擬合及預測


原文鏈接:http://tecdat.cn/?p=9670

樣條線是擬合非線性模型並從數據中學習非線性相互作用的一種方法。 

三次樣條

 三次樣條 具有連續的一階和二階導數。 我們通過應用基礎函數來變換變量  並使用這些變換后的變量擬合模型, 向模型添加非線性, 使樣條曲線能夠擬合更平滑 。

 

#loading the Splines Packages
require(splines)
#ISLR contains the Dataset
require(ISLR)
attach(Wage) #attaching Wage dataset
?Wage #for more details on the dataset
agelims<-range(age)
#Generating Test Data
age.grid<-seq(from=agelims[1], to = agelims[2])

 三次樣條 
  R中使用函數擬合三次樣條。

#3 cutpoints at ages 25 ,50 ,60
fit<-lm(wage ~ bs(age,knots = c(25,40,60)),data = Wage )
summary(fit)
## 
## Call:
## lm(formula = wage ~ bs(age, knots = c(25, 40, 60)), data = Wage)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -98.832 -24.537  -5.049  15.209 203.207 
## 
## Coefficients:
##                                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                       60.494      9.460   6.394 1.86e-10 ***
## bs(age, knots = c(25, 40, 60))1    3.980     12.538   0.317 0.750899    
## bs(age, knots = c(25, 40, 60))2   44.631      9.626   4.636 3.70e-06 ***
## bs(age, knots = c(25, 40, 60))3   62.839     10.755   5.843 5.69e-09 ***
## bs(age, knots = c(25, 40, 60))4   55.991     10.706   5.230 1.81e-07 ***
## bs(age, knots = c(25, 40, 60))5   50.688     14.402   3.520 0.000439 ***
## bs(age, knots = c(25, 40, 60))6   16.606     19.126   0.868 0.385338    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 39.92 on 2993 degrees of freedom
## Multiple R-squared:  0.08642,    Adjusted R-squared:  0.08459 
## F-statistic: 47.19 on 6 and 2993 DF,  p-value: < 2.2e-16

 繪制回歸線

 

 上圖顯示了三次樣條曲線的平滑和局部效果。

平滑樣條線

 我們在平滑樣條曲線中的目的是通過添加粗糙度最小化誤差函數 。

 

 
        


現在我們可以注意到,紅線(即“平滑樣條線”)更加搖擺不定,並且更靈活地擬合數據。這可能是由於高度的自由度所致。選擇的價值,最好的辦法  λ λ和DF是交叉驗證。 

實施交叉驗證以選擇λ值並實施平滑樣條線:

fit2
## Call:
## smooth.spline(x = age, y = wage, cv = TRUE)
## 
## Smoothing Parameter  spar= 0.6988943  lambda= 0.02792303 (12 iterations)
## Equivalent Degrees of Freedom (Df): 6.794596
## Penalized Criterion: 75215.9
## PRESS: 1593.383
#It selects $\lambda=0.0279$ and df = 6.794596 as it is a Heuristic and can take various 


該模型也非常平滑,可以很好地擬合數據。

結論

因此, 我們需要對數據或變量進行一些轉換,以使模型在學習輸入X i Xi和輸出  Y之間的非線性相互作用時更靈活,更強大。 

 

 

如果您有任何疑問,請在下面發表評論。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM