r中的分段回归

时间:2018-03-06 18:51:17

标签: r regression piecewise

我有两个变量,A和B,如果在分段回归中建模,则显着相关。该模型有两个部分。问题在于,在情节中,两个部分不会按照它们应该的方式彼此连接:它们形成一个“鼻子”。在破发点。我在Stackoverflow的其他帖子中看到,正确绘制分段回归的问题似乎很普遍。 这是带有A和B的数据框:

dfrm <- read.table(text="   A   B
1  0.04545455 1.3
2  0.09090909 1.1
3  0.13636364 1.6
4  0.18181818 1.8
5  0.22727273 3.4
6  0.27272727 1.8
7  0.31818182 1.9
8  0.36363636 0.7
9  0.40909091 2.9
10 0.45454545 1.2
11 0.50000000 0.8
12 0.54545455 0.7
13 0.59090909 0.6
14 0.63636364 1.7
15 0.68181818 0.7
16 0.72727273 2.0
17 0.77272727 1.2
18 0.81818182 0.5
19 0.86363636 2.8
20 0.90909091 1.0
21 0.95454545 0.5
22 1.00000000 1.0
23 0.06666667 0.2
24 0.13333333 0.6
25 0.20000000 1.6
26 0.26666667 0.4
27 0.33333333 1.7
28 0.40000000 2.5
29 0.46666667 0.5
30 0.53333333 1.5
31 0.60000000 0.4
32 0.66666667 0.3
33 0.73333333 0.2
34 0.80000000 0.2
35 0.86666667 0.7
36 0.93333333 2.2
37 1.00000000 2.3
38 0.05882353 1.4
39 0.11764706 2.7
40 0.17647059 0.7
41 0.23529412 0.2
42 0.29411765 0.8
43 0.35294118 2.9
44 0.41176471 0.4
45 0.47058824 0.5
46 0.52941176 2.1
47 0.58823529 0.4
48 0.64705882 0.6
49 0.70588235 1.0
50 0.76470588 0.3
51 0.82352941 0.9
52 0.88235294 1.4
53 0.94117647 0.6
54 1.00000000 0.4
55 0.10000000 1.7
56 0.20000000 1.4
57 0.30000000 1.5
58 0.40000000 0.6
59 0.50000000 0.4
60 0.60000000 0.5
61 0.70000000 0.4
62 0.80000000 1.0
63 0.90000000 0.8
64 1.00000000 3.0
65 0.03846154 1.5
66 0.07692308 2.7
67 0.11538462 2.2
68 0.15384615 0.6
69 0.19230769 0.7
70 0.23076923 0.5
71 0.26923077 0.5
72 0.30769231 0.6
73 0.34615385 1.2
74 0.38461538 0.8
75 0.42307692 1.8
76 0.46153846 2.1
77 0.50000000 0.6
78 0.53846154 0.7
79 0.57692308 1.3
80 0.61538462 0.4
81 0.65384615 0.7
82 0.69230769 1.2
83 0.73076923 0.8
84 0.76923077 1.2
85 0.80769231 1.0
86 0.84615385 1.4
87 0.88461538 0.9
88 0.92307692 0.8
89 0.96153846 1.7
90 1.00000000 5.8", header=TRUE)

## attach(df) NO, don't use attach and mistrust anyone who tells you differently
model <- lm(B ~ (A < 0.89394)*A + (A >= 0.89394)*A, data=dfrm) # 0.89394 = breakpoint 
# Preparing the plot:
a <- sort(unique(dfrm$A))
# Plotting:
plot(B ~ A, data=dfrm)
lines(a, predict(model, list(A=a)), lwd=2, col="blue")

这是情节:Piecewise regression 如何在断点处干净地连接两个段?

2 个答案:

答案 0 :(得分:0)

使用GAM(广义加法模型)尝试此操作可能最容易,通过R中的GAM packagemgcv package应用。此技术允许您拟合非线性模型阶段,平滑功能之间的连接(或“结”)。作为奖励,GAM基本上都是GLM,所以学习曲线应该很容易。

答案 1 :(得分:0)

鼻子和节段之间的断开可能是由于确定断点的方式缺乏精确性。 根据Crawley(2007:427)中详述的方法重新确定数据的断点后,这两个段完美连接。

所涉及的步骤是:

  1. 定义一个向量&#34; break&#34;潜在的休息时间
  2. 针对所有潜在断点运行for循环以进行分段回归,并为每个模型挖出最小残差标准误差(mse):

    mse <- numeric(length(breaks))
      for(i in 1:length(breaks)){
      piecewise <- lm(V_indep ~ V_dep*(V_dep < breaks[i]) + V_dep*(V_dep>=breaks[i]))
    mse[i] <- summary(piecewise)[6]
    }
    mse <- numeric(length(breaks))
    
  3. 用最少的mse识别断点:

    breaks[which(mse==min(mse))]
    
  4. 使用此断点拟合模型。