2018年1月11日

数据分析流程

模型

  • 相关性
  • t检验
  • 方差分析
  • 线性回归
  • 广义线性回归
  • 主成分分析和因子分析
  • 逻辑回归
  • 决策树
  • 随机森林
  • 支持向量机

回归分析

回归分析是统计学中最常用的模型,是用一个或多个自变量(也称解释变量)来预测因变量(也称结果变量)的方法。
回归分析可以用来挑选与因变量相关的自变量,可以描述两者的关系,也可以生成一个等式,通过自变量来预测因变量。

简单的线性回归模型

在R中,拟合线性回归模型最基本的函数是lm(),形式为:
myfit <- lm(formula, data)
其中,formula指要拟合的模型形式,data是数据框,包含了用于拟合模型的数据。myfit为存储结果对象的列表,包含了所拟合模型的大量信息。
formula形式如下: Y ~ X1 + X2 + ... + Xk
~左边为因变量,右边为各个自变量,自变量之间用+符号分隔。

women数据集提供了15个年龄在30~39岁间女性的身高和体重,我们可以通过身高来预测体重,也可以分辨出过重或过轻的个体。

fit <- lm(weight ~ height, data = women)

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

可以看到height的回归系数3.45显著不为0(p < 0.001),表明身高每增高1英寸,体重将预期增加3.45磅。
R-squared为0.991表明模型可以解释体重99.1%的方差,它也是实际和预测值之间相关系数的平方,模型预测精度很高。
得到的模型为:
Weight = -87.52 + 3.45 * Height
进一步添加一个二次项(即X^2)提高预测精度。

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

得到的模型为:
Weight = 261.88 - 7.35 * Height + 0.083 * Height^2
模型的方差解释率已经增加到了99.9%。