Sklearn:分类输入器?

Sklearn: Categorical Imputer?

有没有办法使用 sklearn.preprocessing 对象来估算分类值?我想最终创建一个预处理对象,我可以将其应用于新数据并以与旧数据相同的方式进行转换。

我正在寻找一种方法,以便我可以使用它this

是的,这是可能的。例如,您可以使用带有参数 strategy = 'most_frequent'sklearn.preprocessing.Imputer

使用fit_transform方法将其应用于旧数据(训练集),然后transform应用于新数据(测试集)。

复制和修改 this 答案,我为 pandas.Series 对象制作了一个 imputer

import numpy
import pandas 

from sklearn.base import TransformerMixin


class SeriesImputer(TransformerMixin):

    def __init__(self):
        """Impute missing values.

        If the Series is of dtype Object, then impute with the most frequent object.
        If the Series is not of dtype Object, then impute with the mean.  

        """
    def fit(self, X, y=None):
        if   X.dtype == numpy.dtype('O'): self.fill = X.value_counts().index[0]
        else                            : self.fill = X.mean()
        return self

    def transform(self, X, y=None):
        return X.fillna(self.fill)

要使用它你会做:

# Make a series
s1 = pandas.Series(['k', 'i', 't', 't', 'e', numpy.NaN])


a  = SeriesImputer()   # Initialize the imputer
a.fit(s1)              # Fit the imputer
s2 = a.transform(s1)   # Get a new series 

您也可以使用 OrdinalEncoder

可以在训练集上训练,使用函数fit(),得到一个模型,然后将模型应用到训练集和测试集上,transform():

oe = OrdinalEncoder()
# train the model on a training set of type pandas.DataFrame, for example
oe.fit(df_train)
# transform the training set using the model:
ar_train_encoded = oe.transform(df_train)
# transform the test set using the SAME model:
ar_test_encoded = oe.transform(df_test)

结果是一个 numpy 数组。

来自 sklearn.preprocessing 的输入法适用于数值变量。 但是对于分类变量,类别大多是字符串,而不是数字。为了能够使用 sklearn 的输入器,您需要将字符串转换为数字,然后输入并最终转换回字符串。

更好的选择是使用 sklearn_pandas package.

中的 CategoricalImputer()

用模式替换null-like值,适用于字符串列。 sklearn-pandas 包可以使用 pip install sklearn-pandas 安装,并且可以作为 import sklearn_pandas

导入