R中的Box-Cox变换

来源:互联网 发布:淘宝附近的人取消了吗 编辑:程序博客网 时间:2024/06/03 17:45

        在许多情况下,为了满足经典线性模型的正态性假设,常常需要使用指数变换或者对数转化,使其转换后的数据接近正态,比如数据是非单峰分布的,或者各种混合分布,虽然不一定起作用,但是不妨试试。

       我们使用平日最常见的box-cox转换,因为之前看到有人问到如何使用spss进行转换,到网上找了资料,是需要语法的,在spss中进行语法指令,显然相比较用R,还是很不方便。

分两步,第一步需要计算出,lambda值,然后把转化后的lambda值带入方程中,同时对于转换后的数据拟合出来的方程依然进行正态性的检验

第一步:

语句如下:

library(MASS)

D=read.csv("/Users/hjs/Documents/train_test_model/ridgereg1.csv",sep=",") # 加载数据

#2拟合BOXCOX 模型
b=boxcox(y~., data=D) # 定义函数类型和数据
I=which(b$y==max(b$y))
b$x[I]#lambda=0.83 

#得到0.828就是下图的最高点



第二步:

依据上一步boxcox转化的lambda值,即0.83次方,代入模型
c=lm(y^0.83 ~ long + touwei + weight,data=D) # 定义一个多元回归,同理y x1 x2 x3 是cvs文件中,带变量名的字母
d=step(c) # 使用逐步法,进入多个自变量
summary(d) # 模型汇总
anova(d) #  用方差分析法对拟合的模型进行检验
shapiro.test(d$res) # 用残差对boxcox变化后的这个逐步回归方程 正态性进行检验

结果如下

Start:  AIC=-21.51y^0.83 ~ long + touwei + weight         Df Sum of Sq     RSS      AIC<none>                 5.7518 -21.5136- touwei  1    4.7894 10.5412 -10.1865- long    1    6.5893 12.3411  -6.7184- weight  1   11.3733 17.1251   0.4891
Call:lm(formula = y^0.83 ~ long + touwei + weight, data = D)Residuals:     Min       1Q   Median       3Q      Max -0.88677 -0.36357 -0.05594  0.38686  1.33507 Coefficients:              Estimate Std. Error t value Pr(>|t|)    (Intercept)  7.1472866  0.8353396   8.556 9.29e-08 ***long         0.8158515  0.1796633   4.541 0.000253 ***touwei      -1.0078211  0.2603217  -3.871 0.001118 ** weight       0.0033182  0.0005562   5.966 1.21e-05 ***---Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 0.5653 on 18 degrees of freedomMultiple R-squared:  0.9753,Adjusted R-squared:  0.9712 F-statistic: 237.4 on 3 and 18 DF,  p-value: 1.173e-14
 DfSum SqMean SqF valuePr(>F)long1 213.896784 213.8967840 669.377918 1.086794e-15touwei1 2.271354 2.2713536 7.108073 1.574365e-02weight1 11.373302 11.3733018 35.592106 1.208578e-05Residuals18 5.751821 0.3195456 NA NA
Shapiro-Wilk normality testdata:  d$resW = 0.96598, p-value = 0.6184
可以看到Shapiro-Wilk normality test是通过的,也就是说,本次box-cox转换是成功的。