簡體   English   中英

lm() 中不一致的 R 平方值

[英]inconsistent R-squared values in lm()

我以兩種不同的方式擬合相同的線性 model,導致相同的參數估計值但不同的 R 平方值。 差異從何而來? 這是 R 中的錯誤嗎? 這是我的代碼:

m1 <- lm(stack.loss ~ ., data = stackloss)
summary(m1)

X <- model.matrix(m1)
y <- stackloss$stack.loss
m2 <- lm(y ~ 0 + X)
summary(m2)

m1的output如下(略短):

            Estimate Std. Error t value Pr(>|t|)    
(Intercept) -39.9197    11.8960  -3.356  0.00375 ** 
Air.Flow      0.7156     0.1349   5.307  5.8e-05 ***
Water.Temp    1.2953     0.3680   3.520  0.00263 ** 
Acid.Conc.   -0.1521     0.1563  -0.973  0.34405    

Residual standard error: 3.243 on 17 degrees of freedom
Multiple R-squared:  0.9136,    Adjusted R-squared:  0.8983 
F-statistic:  59.9 on 3 and 17 DF,  p-value: 3.016e-09

m2的 output 對系數和殘差標准誤差具有相同的估計值,但 R 平方值和 F 統計量不同:

             Estimate Std. Error t value Pr(>|t|)    
X(Intercept) -39.9197    11.8960  -3.356  0.00375 ** 
XAir.Flow      0.7156     0.1349   5.307  5.8e-05 ***
XWater.Temp    1.2953     0.3680   3.520  0.00263 ** 
XAcid.Conc.   -0.1521     0.1563  -0.973  0.34405    

Residual standard error: 3.243 on 17 degrees of freedom
Multiple R-squared:  0.979, Adjusted R-squared:  0.9741 
F-statistic: 198.2 on 4 and 17 DF,  p-value: 5.098e-14

為什么 R 平方值不同?

這在這篇文章這個中都有討論。 下面是對lm()源代碼中發生的事情的分解。 相關部分:

r <- z$residuals
f <- z$fitted.values
w <- z$weights
if (is.null(w)) {
        mss <- if (attr(z$terms, "intercept"))
            sum((f - mean(f))^2) else sum(f^2)
        rss <- sum(r^2)
}

盡管您包含了截距,但術語的屬性並未設置為包含截距,比較:

attr(m1$terms,"intercept")
[1] 1

attr(m2$terms,"intercept")
[1] 0

我不建議這樣做,因為您可以輕松地使用公式接口來擬合 model,而無需自己提供 model 矩陣。 但是你可以看到通過改變屬性,你可以得到summary.lm來使用正確的rss並得到正確的r-squared:

attr(m2$terms,"intercept") = 1
Call:
lm(formula = y ~ 0 + X)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.2377 -1.7117 -0.4551  2.3614  5.6978 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
X(Intercept) -39.9197    11.8960  -3.356  0.00375 ** 
XAir.Flow      0.7156     0.1349   5.307  5.8e-05 ***
XWater.Temp    1.2953     0.3680   3.520  0.00263 ** 
XAcid.Conc.   -0.1521     0.1563  -0.973  0.34405    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.243 on 17 degrees of freedom
Multiple R-squared:  0.9136,    Adjusted R-squared:  0.8983 
F-statistic:  59.9 on 3 and 17 DF,  p-value: 3.016e-09

StupidWolf 給了你答案。 您正在估計兩個不同的回歸模型。

因為您的第二個 model 規范 m2 <- lm(y ~ 0 + X)。 您沒有估計截距,並且您有一個額外的變量變量 X(intercept)。

要獲得相同的 R^2,只需更正 model

m1 <- lm(stack.loss ~ ., data = stackloss)
summary(m1)

X <- model.matrix(m1)
y <- stackloss$stack.loss
m2 <- lm(y ~ X)
summary(m2)

為您提供相同的 R^2,因為您回歸相同的 model。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM