接上一篇:
1.box-cox变换是什么?
Box-Cox变换是Box和Cox在1964年提出的一种广义幂变换方法,是统计建模中常用的一种数据变换,用于连续的响应变量不满足正态分布的情况。Box-Cox变换之后,可以一定程度上减小不可观测的误差和预测变量的相关性。Box-Cox变换的主要特点是引入一个参数,通过数据本身估计该参数进而确定应采取的数据变换形式,Box-Cox变换可以明显地改善数据的正态性、对称性和方差相等性,对许多实际数据都是行之有效的。
通俗来讲,Box-Cox变换就是来修正偏态和峰度以使得原始分布接近正态分布。Box-Cox变换的一个显著优点是通过求变换参数来确定变换形式,而这个过程完全基于数据本身而无须任何先验信息,这无疑比凭经验或通过尝试而选用对数、平方根等变换方式要客观和精确。
Box-Cox变换的目的是为了让数据满足线性模型的基本假定,即线性、正态性及方差齐性,然而经Box-Cox变换后数据是否同时满足了以上假定,仍需要考察验证
2.python实现
scipy.special.boxcox1p是Box-Cox变换的函数。scipy.stats.boxcox_normmax是用来计算输入数据的最佳Box-Cox变换参数,即scipy.special.boxcox1p函数中的lamda。
scipy.special.boxcox1p(x, lmbda)
## Import necessary modules
from scipy.special import boxcox1p
from scipy.stats import boxcox_normmax
def fixing_skewness(df):
"""
This function takes in a dataframe and return fixed skewed dataframe
"""
## Getting all the data that are not of "object" type.
numeric_feats = df.dtypes[df.dtypes != "object"].index
# Check the skew of all numerical features
skewed_feats = df[numeric_feats].apply(lambda x: x.skew()).sort_values(ascending=False)
high_skew = skewed_feats[abs(skewed_feats) > 0.5]
skewed_features = high_skew.index
# 修正
for feat in skewed_features:
# 这里是+1是保证数据非负,没有其他含义,不会影响对偏态的修正
df[feat] = boxcox1p(df[feat], boxcox_normmax(df[feat] + 1))
举例:
修正前:
修正后:
参考: