平均数编码:针对高基数定性特征(类别特征)的数据预处理/特征工程

https://zhuanlan.zhihu.com/p/26308272

(在另一篇文章中,我正在汇总所有已知的数据挖掘特征工程技巧:【持续更新】机器学习特征工程实用技巧大全 - 知乎专栏。)

前言

读完sklearn.preprocessing所有函数的API文档之后,基础的特征工程就可以算是入门了。然而,进阶的特征工程往往依赖于数据分析师的直觉与经验,而且与具体的数据有密切的联系,比较难找到系统性的“最好”的特征工程方法。

在这里,我希望能向大家分享一种极其有效的、针对高基数定性特征(类别特征)的数据预处理方法。在各类竞赛中,有许多人使用这种方法取得了非常优秀的成绩,但是中文网络上似乎还没有人对此做过介绍。


 

平均数编码:针对高基数定性特征(类别特征)的数据预处理

Mean Encoding: A Preprocessing Scheme for High-Cardinality Categorical Features

(论文原文下载:http://helios.mm.di.uoa.gr/~rouvas/ssi/sigkdd/sigkdd.vol3.1/barreca.pdf,感谢评论区@jin zhang提供更清晰的pdf版本)

 

如果某一个特征是定性的(categorical),而这个特征的可能值非常多(高基数),那么平均数编码(mean encoding)是一种高效的编码方式。在实际应用中,这类特征工程能极大提升模型的性能。

 

在机器学习与数据挖掘中,不论是分类问题(classification)还是回归问题(regression),采集的数据常常会包括定性特征(categorical feature)。因为定性特征表示某个数据属于一个特定的类别,所以在数值上,定性特征值通常是从0到n的离散整数。例子:花瓣的颜色(红、黄、蓝)、性别(男、女)、地址、某一列特征是否存在缺失值(这种NA 指示列常常会提供有效的额外信息)。

一般情况下,针对定性特征,我们只需要使用sklearn的OneHotEncoder或LabelEncoder进行编码:(data_df是一个pandas dataframe,每一行是一个training example,每一列是一个特征。在这里我们假设"street_address"是一个字符类的定性特征。)

 

from sklearn.preprocessing import OneHotEncoder, LabelEncoder
import numpy as np
import pandas as pd

le = LabelEncoder()
data_df['street_address'] = le.fit_transform(data_df['street_address'])

ohe = OneHotEncoder(n_values='auto', categorical_features='all', dtype=np.float64, sparse=True, handle_unknown='error')
one_hot_matrix = ohe.fit_transform(data_df['street_address'])

LabelEncoder能够接收不规则的特征列,并将其转化为[公式][公式]的整数值(假设一共有[公式]种不同的类别);OneHotEncoder则能通过哑编码,制作出一个m*n的稀疏矩阵(假设数据一共有m行,具体的输出矩阵格式是否稀疏可以由sparse参数控制)。

更详细的API文档参见:sklearn.preprocessing.LabelEncoder - scikit-learn 0.18.1 documentation以及sklearn.preprocessing.OneHotEncoder - scikit-learn 0.18.1 documentation

 

这类简单的预处理能够满足大多数数据挖掘算法的需求。

值得一提的是,LabelEncoder将n种类别编码为从0到n-1的整数,虽然能够节省内存降低算法的运行时间,但是隐含了一个假设:不同的类别之间,存在一种顺序关系。在具体的代码实现里,LabelEncoder会对定性特征列中的所有独特数据进行一次排序,从而得出从原始输入到整数的映射。


 

定性特征的基数(cardinality)指的是这个定性特征所有可能的不同值的数量。在高基数(high cardinality)的定性特征面前,这些数据预处理的方法往往得不到令人满意的结果。

高基数定性特征的例子:IP地址、电子邮件域名、城市名、家庭住址、街道、产品号码。

主要原因:

  1. LabelEncoder编码高基数定性特征,虽然只需要一列,但是每个自然数都具有不同的重要意义,对于y而言线性不可分。使用简单模型,容易欠拟合(underfit),无法完全捕获不同类别之间的区别;使用复杂模型,容易在其他地方过拟合(overfit)。
  2. OneHotEncoder编码高基数定性特征,必然产生上万列的稀疏矩阵,易消耗大量内存和训练时间,除非算法本身有相关优化(例:SVM)。

 

因此,我们可以尝试使用平均数编码(mean encoding)的编码方法,在贝叶斯的架构下,利用所要预测的应变量(target variable),有监督地确定最适合这个定性特征的编码方式。在Kaggle的数据竞赛中,这也是一种常见的提高分数的手段。


 

基本思路与原理

平均数编码是一种有监督(supervised)的编码方式,适用于分类和回归问题。为了简化讨论,以下的所有代码都以分类问题作为例子。

假设在分类问题中,目标y一共有C个不同类别,具体的一个类别用target表示;某一个定性特征variable一共有K个不同类别,具体的一个类别用k表示。

先验概率(prior):数据点属于某一个target(y)的概率,[公式]

后验概率(posterior):该定性特征属于某一类时,数据点属于某一个target(y)的概率,[公式]

本算法的基本思想:将variable中的每一个k,都表示为(估算的)它所对应的目标y值概率

[公式]。(估算的结果都用“^”表示,以示区分)

(备注)因此,整个数据集将增加(C-1)列。是C-1而不是C的原因:
[公式],所以最后一个[公式]的概率值必然和其他[公式]的概率值线性相关。在线性模型、神经网络以及SVM里,不能加入线性相关的特征列。如果你使用的是基于决策树的模型(gbdt、rf等),个人仍然不推荐这种over-parameterization。


 

先验概率与后验概率的计算

因为我们没有上帝视角,所以我们在计算中,需要利用已有数据估算先验概率和后验概率。我们在此使用的具体方法被称为Empirical BayesEmpirical Bayes method)。和一般的贝叶斯方法(如常见的Laplace Smoothing)不同,我们在估算先验概率时,会使用已知数据的平均值,而不是[公式]

接下来的计算就是简单的统计:

[公式] = (y = target)的数量 / y 的总数

[公式] = (y = target 并且 variable = k)的数量 / (variable = k)的数量

(其实我本来可以把公式用sigma求和写出来的,但是那样不太方便直观理解)


使用不同的统计方法,以上两个公式的计算方法也会不同。

权重

我们已经得到了先验概率估计[公式]和后验概率估计[公式]。最终编码所使用的概率估算,应当是先验概率与后验概率的一个凸组合(convex combination)。由此,我们引入先验概率的权重[公式]来计算编码所用概率[公式]

[公式]

或:[公式]

 

直觉上,[公式]应该具有以下特性:

  1. 如果测试集中出现了新的特征类别(未在训练集中出现),那么[公式]
  2. 一个特征类别在训练集内出现的次数越多,后验概率的可信度越高,其权重也越大。


在贝叶斯统计学中,[公式]也被称为shrinkage parameter。

权重函数

我们需要定义一个权重函数输入特征类别在训练集中出现的次数n,输出是对于这个特征类别的先验概率的权重[公式]。假设一个特征类别的出现次数为n,以下是一个常见的权重函数:

[公式]

这个函数有两个参数:

k:当[公式]时,[公式],先验概率与后验概率的权重相同;当[公式]时,[公式]

f:控制函数在拐点附近的斜率,f越大,“坡”越缓。

图示:k=1时,不同的f对于函数图象的影响。

当(freq_col - k) / f太大的时候,np.exp可能会产生overflow的警告。我们不需要管这个警告,因为某一类别的频数极高,分母无限时,最终先验概率的权重将成为0,这也表示我们对于后验概率有充足的信任。


 

延伸

以上的算法设计能解决多个(>2)类别的分类问题,自然也能解决更简单的2类分类问题以及回归问题。

还有一种情况:定性特征本身包括了不同级别。例如,国家包含了省,省包含了市,市包含了街区。有些街区可能就包含了大量的数据点,而有些省却可能只有稀少的几个数据点。这时,我们的解决方法是,在empirical bayes里加入不同层次的先验概率估计。


 

代码实现

原论文并没有提到,如果fit时使用了全部的数据,transform时也使用了全部数据,那么之后的机器学习模型会产生过拟合。因此,我们需要将数据分层分为n_splits个fold,每一个fold的数据都是利用剩下的(n_splits - 1)个fold得出的统计数据进行转换。n_splits越大,编码的精度越高,但也更消耗内存和运算时间。

 

编码完毕后,是否删除原始特征列,应当具体问题具体分析。


 

附:完整版MeanEncoder代码(python)。

一个MeanEncoder对象可以提供fit_transform和transform方法,不支持fit方法,暂不支持训练时的sample_weight参数。

 

import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from itertools import product

class MeanEncoder:
    def __init__(self, categorical_features, n_splits=5, target_type='classification', prior_weight_func=None):
        """
        :param categorical_features: list of str, the name of the categorical columns to encode

        :param n_splits: the number of splits used in mean encoding

        :param target_type: str, 'regression' or 'classification'

        :param prior_weight_func:
        a function that takes in the number of observations, and outputs prior weight
        when a dict is passed, the default exponential decay function will be used:
        k: the number of observations needed for the posterior to be weighted equally as the prior
        f: larger f --> smaller slope
        """

        self.categorical_features = categorical_features
        self.n_splits = n_splits
        self.learned_stats = {}

        if target_type == 'classification':
            self.target_type = target_type
            self.target_values = []
        else:
            self.target_type = 'regression'
            self.target_values = None

        if isinstance(prior_weight_func, dict):
            self.prior_weight_func = eval('lambda x: 1 / (1 + np.exp((x - k) / f))', dict(prior_weight_func, np=np))
        elif callable(prior_weight_func):
            self.prior_weight_func = prior_weight_func
        else:
            self.prior_weight_func = lambda x: 1 / (1 + np.exp((x - 2) / 1))

    @staticmethod
    def mean_encode_subroutine(X_train, y_train, X_test, variable, target, prior_weight_func):
        X_train = X_train[[variable]].copy()
        X_test = X_test[[variable]].copy()

        if target is not None:
            nf_name = '{}_pred_{}'.format(variable, target)
            X_train['pred_temp'] = (y_train == target).astype(int)  # classification
        else:
            nf_name = '{}_pred'.format(variable)
            X_train['pred_temp'] = y_train  # regression
        prior = X_train['pred_temp'].mean()

        col_avg_y = X_train.groupby(by=variable, axis=0)['pred_temp'].agg({'mean': 'mean', 'beta': 'size'})
        col_avg_y['beta'] = prior_weight_func(col_avg_y['beta'])
        col_avg_y[nf_name] = col_avg_y['beta'] * prior + (1 - col_avg_y['beta']) * col_avg_y['mean']
        col_avg_y.drop(['beta', 'mean'], axis=1, inplace=True)

        nf_train = X_train.join(col_avg_y, on=variable)[nf_name].values
        nf_test = X_test.join(col_avg_y, on=variable).fillna(prior, inplace=False)[nf_name].values

        return nf_train, nf_test, prior, col_avg_y

    def fit_transform(self, X, y):
        """
        :param X: pandas DataFrame, n_samples * n_features
        :param y: pandas Series or numpy array, n_samples
        :return X_new: the transformed pandas DataFrame containing mean-encoded categorical features
        """
        X_new = X.copy()
        if self.target_type == 'classification':
            skf = StratifiedKFold(self.n_splits)
        else:
            skf = KFold(self.n_splits)

        if self.target_type == 'classification':
            self.target_values = sorted(set(y))
            self.learned_stats = {'{}_pred_{}'.format(variable, target): [] for variable, target in
                                  product(self.categorical_features, self.target_values)}
            for variable, target in product(self.categorical_features, self.target_values):
                nf_name = '{}_pred_{}'.format(variable, target)
                X_new.loc[:, nf_name] = np.nan
                for large_ind, small_ind in skf.split(y, y):
                    nf_large, nf_small, prior, col_avg_y = MeanEncoder.mean_encode_subroutine(
                        X_new.iloc[large_ind], y.iloc[large_ind], X_new.iloc[small_ind], variable, target, self.prior_weight_func)
                    X_new.iloc[small_ind, -1] = nf_small
                    self.learned_stats[nf_name].append((prior, col_avg_y))
        else:
            self.learned_stats = {'{}_pred'.format(variable): [] for variable in self.categorical_features}
            for variable in self.categorical_features:
                nf_name = '{}_pred'.format(variable)
                X_new.loc[:, nf_name] = np.nan
                for large_ind, small_ind in skf.split(y, y):
                    nf_large, nf_small, prior, col_avg_y = MeanEncoder.mean_encode_subroutine(
                        X_new.iloc[large_ind], y.iloc[large_ind], X_new.iloc[small_ind], variable, None, self.prior_weight_func)
                    X_new.iloc[small_ind, -1] = nf_small
                    self.learned_stats[nf_name].append((prior, col_avg_y))
        return X_new

    def transform(self, X):
        """
        :param X: pandas DataFrame, n_samples * n_features
        :return X_new: the transformed pandas DataFrame containing mean-encoded categorical features
        """
        X_new = X.copy()

        if self.target_type == 'classification':
            for variable, target in product(self.categorical_features, self.target_values):
                nf_name = '{}_pred_{}'.format(variable, target)
                X_new[nf_name] = 0
                for prior, col_avg_y in self.learned_stats[nf_name]:
                    X_new[nf_name] += X_new[[variable]].join(col_avg_y, on=variable).fillna(prior, inplace=False)[
                        nf_name]
                X_new[nf_name] /= self.n_splits
        else:
            for variable in self.categorical_features:
                nf_name = '{}_pred'.format(variable)
                X_new[nf_name] = 0
                for prior, col_avg_y in self.learned_stats[nf_name]:
                    X_new[nf_name] += X_new[[variable]].join(col_avg_y, on=variable).fillna(prior, inplace=False)[
                        nf_name]
                X_new[nf_name] /= self.n_splits

        return X_new


 

参考资料:

[ 1 ] Micci-Barreca, Daniele. "A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems.ACM SIGKDD Explorations Newsletter 3.1 (2001): 27-32.

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
数据预处理中的归一化是指将数据缩放到一个预定的范围内,通常是[0, 1]或[-1, 1]之间,以消除数据间的量纲差异,提模型的训练效率。归一化的原理主要包括以下几个步骤: 1. 最小-最大归一化(Min-Max Scaling):将数据映射到指定范围内。首先找到数据集中的最小值(min)和最大值(max),然后使用以下公式将数据归一化到[0, 1]之间: X_normalized = (X - X_min) / (X_max - X_min) 其中,X为原始数据,X_normalized为归一化后的数据。这种方法适用于数据分布没有明显边界的情况。 2. Z-Score归一化(Standardization):将数据转化为均值为0,标准差为1的正态分布。通过以下公式计算: X_standardized = (X - X_mean) / X_std 其中,X_mean为数据的均值,X_std为数据的标准差。这种方法适用于数据分布有明显边界的情况。 3. 小数定标标准化(Decimal Scaling):将数据除以一个固定的基数,使得数据的绝对值都小于1或约等于1。例如,将数据除以10的幂次方,使得数据处于[-1, 1]之间。 归一化的目的是消除数据量纲和大小的差异,使得数据在同一个数量级下进行比较,加快模型的收敛速度。通过归一化,可以去除数据中的夸大特征,使得所有特征的尺度同等重要,从而提模型的性能。 参考资料: Python数据预处理之数据规范化.https://www.jianshu.com/p/406e81b2f978 数据预处理中的归一化、标准化和规范化.https://blog.csdn.net/you_are_my_dream/article/details/79978528 数据预处理之归一化(Normalization).https://www.cnblogs.com/chaosimple/p/4153167.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值