函数功能分析

核心目的:对指定的数值列应用Power Transformation(幂变换),使数据更接近正态分布,常用于满足统计模型假设或提升模型性能。

技术实现分析

优点 

  1. 方法灵活:支持'yeo-johnson'(支持零和负值)和'box-cox'(仅正值)两种方法

  2. 正确分离拟合与变换:训练集上fit_transform,测试集上仅transform,避免数据泄露

  3. 基于sklearn实现:使用成熟的PowerTransformer,稳定可靠

def transformation(X_train, X_test, num_cols, method='yeo-johnson'):
    """数据正态变换(改进版)"""
    # 1. 输入验证
    if not all(col in X_train.columns for col in num_cols):
        raise ValueError("部分列不在X_train中")
    
    # 2. 检查空值
    if X_train[num_cols].isnull().any().any():
        raise ValueError("训练数据包含空值,请先处理")
    
    # 3. 复制数据避免原地修改(可选)
    X_train = X_train.copy()
    X_test = X_test.copy()
    
    # 4. 确保数值类型
    X_train[num_cols] = X_train[num_cols].astype(float)
    X_test[num_cols] = X_test[num_cols].astype(float)
    
    # 5. 变换
    pt = PowerTransformer(method=method)
    X_train[num_cols] = pt.fit_transform(X_train[num_cols])
    X_test[num_cols] = pt.transform(X_test[num_cols])
    
    return X_train, X_test

调用示例

import pandas as pd
import numpy as np
from sklearn.preprocessing import PowerTransformer
from sklearn.model_selection import train_test_split

# 准备示例数据
np.random.seed(42)
data = pd.DataFrame({
    'age': np.random.exponential(scale=30, size=1000),  # 偏态分布
    'income': np.random.lognormal(mean=10, sigma=1, size=1000),  # 对数正态
    'score': np.random.normal(loc=70, scale=15, size=1000),  # 正态
    'category': np.random.choice(['A', 'B', 'C'], size=1000)  # 分类变量
})

# 划分训练集和测试集
X_train, X_test = train_test_split(data, test_size=0.2, random_state=42)

# 指定要变换的数值列
num_cols = ['age', 'income']  # score已经是正态,可不变换

# 调用函数
X_train_transformed, X_test_transformed = transformation(
    X_train, X_test, num_cols, method='yeo-johnson'
)

print("变换前 - 训练集统计:")
print(X_train[['age', 'income']].describe())
print("\n变换后 - 训练集统计:")
print(X_train_transformed[['age', 'income']].describe())

适用场景

场景 推荐度 说明
线性回归/逻辑回归 ⭐⭐⭐⭐⭐ 提升模型对异常值的鲁棒性
SVM/神经网络 ⭐⭐⭐⭐ 加速收敛,但非必需
树模型(RF/XGB) ⭐⭐ 对分布不敏感,可跳过
小样本数据集 ⭐⭐⭐ 注意过拟合风险

额外注意事项

  1. Yeo-Johnson vs Box-Cox

    • 数据包含零/负值 → 必须用Yeo-Johnson

    • 仅正值 → Box-Cox通常效果更好(更稳定)

  2. 后续处理

    • 保存pt对象,用于新数据的变换

    • 记录变换参数(如λ值),便于逆变换和解释

  3. PCA/特征工程前使用效果更佳

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐