首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

统计学习简单线性回归实战

本文距离上次更新拖了很久,主要是白天太忙了。另外排版被老婆大人嫌弃了,用图片太不清楚太不好看太不方便了,因此,我决定浪费一点时间,再再网页上简单排版一下,因为微信本身是不适合编辑代码和偏学术风格的文章的,尽管不情愿,我还是尽量多花点时间照顾下老婆的感受吧。本文是简单线性回归实战的 R 版本部分,下一篇为 python 部分,R 部分相信都很熟悉了,或者资料比较好找,我就 不写太详细了。

# 线性回归实战

在 R 语言的实战中,主要用到了 MASS 和 ISLR 两个软件包,其中数据也来源于这两个软件包。

## 简单线性回归 R 版

Boston 数据集来自于 MASS,主要数据如下:

各表头的意义如下:

This data frame contains the following columns:

* crim: per capita crime rate by town.

* zn: proportion of residential land zoned for lots over 25,000 sq.ft.

* indus: proportion of non-retail business acres per town.

* chas: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).

* nox: nitrogen oxides concentration (parts per 10 million).

* rm: average number of rooms per dwelling.

* age: proportion of owner-occupied units built prior to 1940.

* dis: weighted mean of distances to five Boston employment centres.

* rad: index of accessibility to radial highways.

* tax: full-value property-tax rate per $10,000.

* ptratio: pupil-teacher ratio by town.

* black: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.

* lstat: lower status of the population (percent).

* medv: median value of owner-occupied homes in $1000s.

我们将 medv 作为响应变量,lstat 作为预测变量来进行线性回归分析。

对于线性回归其实很简单,也不需要多讲:

Call:

lm(formula = medv ~ lstat, data = Boston)

Residuals:

Min 1Q Median 3Q Max

-15.168 -3.990 -1.318 2.034 24.500

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 34.55384 0.56263 61.41

lstat -0.95005 0.03873 -24.53

---

Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 6.216 on 504 degrees of freedom

Multiple R-squared: 0.5441,Adjusted R-squared: 0.5432

F-statistic: 601.6 on 1 and 504 DF, p-value:

另一个比较有用的函数为 `predict`,用于给定 lstat 值预测 mdev 值,并可以显示置信区间和预测区间。

对于置信区间和预测区间,以lstat = 6 为例,他们的中位数是重合的,但后者的范围更广:

对 medv 和 lstat 做散点图,并画出他们的最小二乘法拟合的直线来可以直观的看出拟合的情况来:

此外,对模型判定有重要意义的残差、Q-Q 图等可以直接对拟合结果作图得到:

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180701G17XZG00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券
http://www.vxiaotou.com