使用固定效应进行预测

Prediction using Fixed Effects

我有一个简单的数据集,我为其应用了一个简单的线性回归模型。现在我想使用固定效应对模型做出更好的预测。我知道我也可以考虑制作虚拟变量,但我的真实数据集包含更多年份和更多变量,所以我想避免制作虚拟变量。

我的数据和代码是这样的:

data <- read.table(header = TRUE, 
                   stringsAsFactors = FALSE, 
                   text="CompanyNumber ResponseVariable Year ExplanatoryVariable1 ExplanatoryVariable2
                   1 2.5 2000 1 2
                   1 4 2001 3 1
                   1 3 2002 5 7
                   2 1 2000 3 2
                   2 2.4 2001 0 4
                   2 6 2002 2 9
                   3 10 2000 8 3")

library(lfe)
library(caret)
fe <- getfe(felm(data = data, ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2 | Year))
fe
lm.1<-lm(ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2, data=data)                                   


prediction<- predict(lm.1, data) 
prediction

check_model=postResample(pred = prediction, obs = data$ResponseVariable)
check_model

对于我的真实数据集,我将根据我的测试集进行预测,但为了简单起见,我也在这里使用训练集。

我想借助我找到的固定效应做一个预测。但是好像和固定效果不匹配吧,谁知道怎么用这个fe$effects?

prediction_fe<- predict(lm.1, data) + fe$effect

这里有一些关于您的设置和您运行正在使用的模型的额外评论。

您正在拟合的主要模型是

lm.1<-lm(ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2, data=data) 

产生

> lm.1
Call:
lm(formula = ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2, 
    data = data)

Coefficients:
         (Intercept)  ExplanatoryVariable1  ExplanatoryVariable2  
              0.8901                0.7857                0.1923  

当你运行这个模型上的predict函数时你得到

> predict(lm.1)
       1        2        3        4        5        6        7 
2.060385 3.439410 6.164590 3.631718 1.659333 4.192205 7.752359 

对应于计算(对于观察 1):0.8901 + 1*0.7857 + 2*0.1923 因此在预测中使用估计的固定效应。 felm 模型稍微复杂一些,因为它 "factors out" 年份部分。此处显示模型拟合

> felm(data = data, ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2 | Year)
ExplanatoryVariable1 ExplanatoryVariable2 
              0.9726               1.3262 

现在这对应于 "correcting for" 或条件 Year 所以如果你适合

你会得到相同的结果
> lm(data = data, ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2 + factor(Year))

Call:
lm(formula = ResponseVariable ~ ExplanatoryVariable1 + ExplanatoryVariable2 + 
    factor(Year), data = data)

Coefficients:
         (Intercept)  ExplanatoryVariable1  ExplanatoryVariable2      factor(Year)2001  
             -2.4848                0.9726                1.3262                0.9105  
    factor(Year)2002  
             -7.0286  

然后只剩下解释变量的系数。因此,您不能从 felm 中提取的固定效应并获得预测(因为您缺少截距和全年效应)——您只能看到效应大小。

希望对您有所帮助。