简介
本实验展示了如何通过 PowerTransformer 使用 Box-Cox 和 Yeo-Johnson 变换,将来自各种分布的数据映射到正态分布。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。
导入库
首先,我们需要导入必要的库:numpy、matplotlib、PowerTransformer、QuantileTransformer 和 train_test_split。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PowerTransformer
from sklearn.preprocessing import QuantileTransformer
from sklearn.model_selection import train_test_split
设置常量
我们将设置样本数量、字体大小和 bins 的常量。
N_SAMPLES = 1000
FONT_SIZE = 6
BINS = 30
创建随机分布
我们将生成六种不同的概率分布:对数正态分布、卡方分布、威布尔分布、高斯分布、均匀分布和双峰分布。
rng = np.random.RandomState(304)
bc = PowerTransformer(method="box-cox")
yj = PowerTransformer(method="yeo-johnson")
qt = QuantileTransformer(n_quantiles=500, output_distribution="normal", random_state=rng)
size = (N_SAMPLES, 1)
## 对数正态分布
X_lognormal = rng.lognormal(size=size)
## 卡方分布
df = 3
X_chisq = rng.chisquare(df=df, size=size)
## 威布尔分布
a = 50
X_weibull = rng.weibull(a=a, size=size)
## 高斯分布
loc = 100
X_gaussian = rng.normal(loc=loc, size=size)
## 均匀分布
X_uniform = rng.uniform(low=0, high=1, size=size)
## 双峰分布
loc_a, loc_b = 100, 105
X_a, X_b = rng.normal(loc=loc_a, size=size), rng.normal(loc=loc_b, size=size)
X_bimodal = np.concatenate([X_a, X_b], axis=0)
创建图表
现在,我们将为这六种分布中的每一种创建图表,展示原始分布以及使用 Box-Cox、Yeo-Johnson 和分位数变换器进行变换后的分布。
distributions = [
("Lognormal", X_lognormal),
("Chi-squared", X_chisq),
("Weibull", X_weibull),
("Gaussian", X_gaussian),
("Uniform", X_uniform),
("Bimodal", X_bimodal),
]
colors = ["#D81B60", "#0188FF", "#FFC107", "#B7A2FF", "#000000", "#2EC5AC"]
fig, axes = plt.subplots(nrows=8, ncols=3, figsize=plt.figaspect(2))
axes = axes.flatten()
axes_idxs = [
(0, 3, 6, 9),
(1, 4, 7, 10),
(2, 5, 8, 11),
(12, 15, 18, 21),
(13, 16, 19, 22),
(14, 17, 20, 23),
]
axes_list = [(axes[i], axes[j], axes[k], axes[l]) for (i, j, k, l) in axes_idxs]
for distribution, color, axes in zip(distributions, colors, axes_list):
name, X = distribution
X_train, X_test = train_test_split(X, test_size=0.5)
## 执行幂变换和分位数变换
X_trans_bc = bc.fit(X_train).transform(X_test)
lmbda_bc = round(bc.lambdas_[0], 2)
X_trans_yj = yj.fit(X_train).transform(X_test)
lmbda_yj = round(yj.lambdas_[0], 2)
X_trans_qt = qt.fit(X_train).transform(X_test)
ax_original, ax_bc, ax_yj, ax_qt = axes
ax_original.hist(X_train, color=color, bins=BINS)
ax_original.set_title(name, fontsize=FONT_SIZE)
ax_original.tick_params(axis="both", which="major", labelsize=FONT_SIZE)
for ax, X_trans, meth_name, lmbda in zip(
(ax_bc, ax_yj, ax_qt),
(X_trans_bc, X_trans_yj, X_trans_qt),
("Box-Cox", "Yeo-Johnson", "分位数变换"),
(lmbda_bc, lmbda_yj, None),
):
ax.hist(X_trans, color=color, bins=BINS)
title = "After {}".format(meth_name)
if lmbda is not None:
title += "\n$\\lambda$ = {}".format(lmbda)
ax.set_title(title, fontsize=FONT_SIZE)
ax.tick_params(axis="both", which="major", labelsize=FONT_SIZE)
ax.set_xlim([-3.5, 3.5])
plt.tight_layout()
plt.show()
总结
在本实验中,我们学习了如何使用 PowerTransformer 通过 Box-Cox 和 Yeo-Johnson 变换将来自各种分布的数据映射到正态分布。我们还学习了如何使用 QuantileTransformer 将任何任意分布强制转换为高斯分布。在变换前后对数据进行可视化很重要,因为某些变换可能对某些数据集无效。