所用数据集women提供了15个年龄在30~39岁间女性的身高和体重信息,想通过身高预测体重。
简单线性回归
结果数据分析: 回归系数(3.45)显著不为0(p<0.001),表明身高每增高1英寸,体重将预期增加3.45英镑。 R平方项(0.991)表明模型可以解释体重99.1%的方差,它也是实际和预测值之间相关系数的平方。
残差标准误(1.525lbs)则可认为是模型用身高预测体重的平均误差。
之后进行输出了真实值、预测值和残差值。显然残差值最大的在身高最矮和最高的地方出现,表明可以用含一个弯曲的曲线来提高预测精度。
拟合效果图: 代码运行:
>
>
> women
height weight
1 58 115
2 59 117
3 60 120
4 61 123
5 62 126
6 63 129
7 64 132
8 65 135
9 66 139
10 67 142
11 68 146
12 69 150
13 70 154
14 71 159
15 72 164
> fit <- lm(weight ~ height , data = women)
> fit
Call:
lm(formula = weight ~ height, data = women)
Coefficients:
(Intercept) height
-87.52 3.45
> summary(fit)
Call:
lm(formula = weight ~ height, data = women)
Residuals:
Min 1Q Median 3Q Max
-1.7333 -1.1333 -0.3833 0.7417 3.1167
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -87.51667 5.93694 -14.74 1.71e-09 ***
height 3.45000 0.09114 37.85 1.09e-14 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.525 on 13 degrees of freedom
Multiple R-squared: 0.991, Adjusted R-squared: 0.9903
F-statistic: 1433 on 1 and 13 DF, p-value: 1.091e-14
> women$weight
[1] 115 117 120 123 126 129 132 135 139 142 146 150 154 159 164
> fitted(fit)
1 2 3 4 5 6 7 8 9 10
112.5833 116.0333 119.4833 122.9333 126.3833 129.8333 133.2833 136.7333 140.1833 143.6333
11 12 13 14 15
147.0833 150.5333 153.9833 157.4333 160.8833
> residuals(fit)
1 2 3 4 5 6 7 8
2.41666667 0.96666667 0.51666667 0.06666667 -0.38333333 -0.83333333 -1.28333333 -1.73333333
9 10 11 12 13 14 15
-1.18333333 -1.63333333 -1.08333333 -0.53333333 0.01666667 1.56666667 3.11666667
> plot(women$height,women$weight,
+ xlab = "Height (in inches)",
+ ylab = "Weight (in pounds)")
> abline(fit)
多项式回归
二次项的显著性(t=13.89,p<0.001)表明包含二次项提高了模型的拟合度。
模型的方差解释率已经增加到了99.9%。 回归中,决定系数也可以称为方差解释率,它代表了总方差被预测变量所解释或决定的比率,决定系数越逼近1,拟合效果和解释效果越好。
拟合效果图:
>
>
> fit2 <- lm(weight ~ height + I(height^2) , data = women)
> summary(fit2)
Call:
lm(formula = weight ~ height + I(height^2), data = women)
Residuals:
Min 1Q Median 3Q Max
-0.50941 -0.29611 -0.00941 0.28615 0.59706
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 261.87818 25.19677 10.393 2.36e-07 ***
height -7.34832 0.77769 -9.449 6.58e-07 ***
I(height^2) 0.08306 0.00598 13.891 9.32e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.3841 on 12 degrees of freedom
Multiple R-squared: 0.9995, Adjusted R-squared: 0.9994
F-statistic: 1.139e+04 on 2 and 12 DF, p-value: < 2.2e-16
> plot(women$height,women$weight,
+ xlab = "Height (in inches)",
+ ylab = "Weight (in lbs)")
> lines(women$height,fitted(fit2))
二元关系图
>
> library(car)
> scatterplot(weight ~ height , data = women,
+ spread=FALSE , smoother.args=list(lty=2),pch=19,
+ main="Women Age 30-39",
+ .... [TRUNCATED]
There were 12 warnings (use warnings() to see them)
|