如何从R中的lm()函数中提取RMSE

477 阅读1分钟

你可以使用以下语法从R中的lm()函数中提取均方根误差(RMSE)

sqrt(mean(model$residuals^2))

下面的例子展示了如何在实践中使用这种语法。

例子:从R语言的lm()中提取RMSE

假设我们在R中拟合了以下的多元线性回归模型:

#create data frame
df <- data.frame(rating=c(67, 75, 79, 85, 90, 96, 97),
                 points=c(8, 12, 16, 15, 22, 28, 24),
                 assists=c(4, 6, 6, 5, 3, 8, 7),
                 rebounds=c(1, 4, 3, 3, 2, 6, 7))

#fit multiple linear regression model
model <- lm(rating ~ points + assists + rebounds, data=df)

我们可以使用**summary()**函数来查看回归模型的整个摘要:

#view model summary
summary(model)

Call:
lm(formula = rating ~ points + assists + rebounds, data = df)

Residuals:
      1       2       3       4       5       6       7 
-1.5902 -1.7181  0.2413  4.8597 -1.0201 -0.6082 -0.1644 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)   
(Intercept)  66.4355     6.6932   9.926  0.00218 **
points        1.2152     0.2788   4.359  0.02232 * 
assists      -2.5968     1.6263  -1.597  0.20860   
rebounds      2.8202     1.6118   1.750  0.17847   
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.193 on 3 degrees of freedom
Multiple R-squared:  0.9589,	Adjusted R-squared:  0.9179 
F-statistic: 23.35 on 3 and 3 DF,  p-value: 0.01396

为了只提取模型的均方根误差(RMSE),我们可以使用以下语法:

#extract RMSE of regression model
sqrt(mean(model$residuals^2))

[1] 2.090564

该模型的RMSE是2.090564

这表示模型的预测值与数据集中的实际值之间的平均距离。

请注意,RMSE越低,一个给定的模型就越能 "适应 "数据集。

当比较几个不同的回归模型时,具有最低RMSE的模型被认为是最 "适合 "数据集的模型。