井出草平の研究ノート

区分線形回帰モデル

www.rdocumentation.org

区分線形回帰モデルは、データセットを複数の区間に分割し、それぞれの区間で線形回帰モデルを適用する手法である。これにより、データの局所的な傾向や非線形のパターンを捉えることができる。ここではsegmentedパッケージを使用する。

# 必要なパッケージをインストールしてロード
install.packages("segmented")
library(segmented)
# 仮想データの生成
set.seed(123) # 結果の再現性のため
x <- 1:100
y <- ifelse(x < 50, 2 * x + rnorm(100, sd = 5), -2 * x + rnorm(100, sd = 5))
plot(x,y)

モデルのフィット

# 基本の線形モデルのフィット
lm.model <- lm(y ~ x)

# Piecewise linear regressionモデルのフィット
pw.model <- segmented(lm.model, seg.Z = ~ x, psi = list(x = 50), control = seg.control(display = FALSE))

結果の表示

summary(pw.model)
plot(x, y)
lines(x, predict(pw.model), col = "red")
Estimated Break-Point(s):
        Est. St.Err
psi1.x   33   2.64

Meaningful coefficients of the linear terms:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)   1.0179    14.7908   0.069   0.9453  
x             1.9362     0.7591   2.551   0.0123 *
U1.x         -6.6143     0.8031  -8.236       NA  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 41.52 on 96 degrees of freedom
Multiple R-Squared: 0.8478,  Adjusted R-squared: 0.8431 

Boot restarting based on 6 samples. Last fit:
Convergence attained in 2 iterations (rel. change 3.422e-11)

2つの回帰式のブレイクポイント33であった。

フィットされたモデルの各「区分された」関係の傾きを計算する。

slope(pw.model)
$x
          Est. St.Err.  t value CI(95%).l CI(95%).u
slope1  1.9362 0.75909   2.5507   0.42942    3.4430
slope2 -4.6781 0.26230 -17.8350  -5.19870   -4.1574