为什么Python中sklearn.preprocessing.StandardScaler
的标准化方法与Matlab中的zscore
不同?
Python中使用sklearn.preprocessing
的示例:
>>> from sklearn.preprocessing import StandardScaler>>> data = [[0, 0], [0, 0], [1, 1], [1, 1]]>>> scaler = StandardScaler()>>> scaler.fit(data)>>> print(scaler.mean_) [ 0.5 0.5]>>> print(scaler.var_) [0.25 0.25]>>> print(scaler.transform(data))[[-1. -1.][-1. -1.][ 1. 1.][ 1. 1.]]
Matlab中使用zscore
函数的相同示例:
>> data = [[0, 0]; [0, 0]; [1, 1]; [1, 1]];>> [Sd_data,mean,stdev] = zscore(data) Sd_data = -0.8660 -0.8660 -0.8660 -0.8660 0.8660 0.8660 0.8660 0.8660 mean = 0.5000 0.5000 stdev = 0.5774 0.5774
回答:
看起来问题出在自由度(ddof – 与标准差估计相关的校正因子),它在StandardScaler
中默认值为0。
作为替代方案,scipy.stats
中的zscore
函数允许你在缩放时控制这个参数:
from scipy.stats import zscorezscore(data, ddof=1)array([[-0.8660254, -0.8660254], [-0.8660254, -0.8660254], [ 0.8660254, 0.8660254], [ 0.8660254, 0.8660254]])
这样你得到的结果与Matlab函数相同。当你调用zscore
并设置ddof=0
时,你会得到与StandardScaler
相同的结果。