我在 R 中对一些数据集进行了回归分析,并尝试预测数据集中每行的每个自变量对因变量的贡献。
所以像这样:
set.seed(123)
y <- rnorm(10)
m <- data.frame(v1=rnorm(10), v2=rnorm(10), v3=rnorm(10))
regr <- lm(formula=y~v1+v2+v3, data=m)
summary(regr)
terms <- predict.lm(regr,m, type="terms")
简而言之:运行回归并使用预测函数计算数据集 m 中 v1、v2 和 v3 的项。但我很难理解预测函数正在计算什么。我希望它将回归结果的系数与变量数据相乘。 v1 是这样的:
coefficients(regr)[2]*m$v1
但是与预测函数相比,这给出了不同的结果。
自己计算:
0.55293884 0.16253411 0.18103537 0.04999729 -0.25108302 0.80717945 0.22488764 -0.88835486 0.31681455 -0.21356803
预测函数计算:
0.45870070 0.06829597 0.08679724 -0.04424084 -0.34532115 0.71294132 0.13064950 -0.98259299 0.22257641 -0.30780616
预测函数的误差为 0.1 左右。此外,如果将预测函数中的所有项与常量相加,它不会合计到总预测值(使用 type=”response”)。预测函数在这里计算什么以及如何告诉它计算我对coefficients(regr)[2]*m$v1 所做的事情?
最佳答案
以下所有行都会产生相同的预测:
# our computed predictions
coefficients(regr)[1] + coefficients(regr)[2]*m$v1 +
coefficients(regr)[3]*m$v2 + coefficients(regr)[4]*m$v3
# prediction using predict function
predict.lm(regr,m)
# prediction using terms matrix, note that we have to add the constant.
terms_predict = predict.lm(regr,m, type="terms")
terms_predict[,1]+terms_predict[,2]+terms_predict[,3]+attr(terms_predict,'constant')
您可以阅读有关使用 type="terms"
here 的更多信息.
您自己的计算(coefficients(regr)[2]*m$v1
)和预测函数计算(terms_predict[,1]
)不同的原因是因为项矩阵中的列以平均值为中心,因此它们的平均值为零:
# this is equal to terms_predict[,1]
coefficients(regr)[2]*m$v1-mean(coefficients(regr)[2]*m$v1)
# indeed, all columns are centered; i.e. have a mean of 0.
round(sapply(as.data.frame(terms_predict),mean),10)
希望这有帮助。
关于r - 线性回归预测中的个别项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853831/