fit_transform()采用2个位置参数,但3个是使用LabelBinarizer

时间:2017-09-11 19:12:11

标签: scikit-learn data-science

我是机器学习的新手,我一直在使用无监督学习技术。

图像显示我的样本数据(全部清洗后)截图: Sample Data

我有两个Pipline用于清理数据:

num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]

print(type(num_attribs))

num_pipeline = Pipeline([
    ('selector', DataFrameSelector(num_attribs)),
    ('imputer', Imputer(strategy="median")),
    ('attribs_adder', CombinedAttributesAdder()),
    ('std_scaler', StandardScaler()),
])

cat_pipeline = Pipeline([
    ('selector', DataFrameSelector(cat_attribs)),
    ('label_binarizer', LabelBinarizer())
])

然后我做了这两个管道的联合,并且相同的代码如下所示:

from sklearn.pipeline import FeatureUnion

full_pipeline = FeatureUnion(transformer_list=[
        ("num_pipeline", num_pipeline),
        ("cat_pipeline", cat_pipeline),
    ])

现在我正试图在Data上做fit_transform但是它向我显示错误。

转型代码:

housing_prepared = full_pipeline.fit_transform(housing)
housing_prepared

错误讯息: fit_transform()需要2个位置参数,但有3个被赋予

16 个答案:

答案 0 :(得分:55)

问题:

管道假设LabelBinarizer的fit_transform方法被定义为采用三个位置参数:

def fit_transform(self, x, y)
    ...rest of the code

虽然它被定义为只有两个:

def fit_transform(self, x):
    ...rest of the code

可能的解决方案:

这可以通过制作一个可以处理3个位置参数的自定义变换器来解决:

  1. 导入并创建一个新类:

    from sklearn.base import TransformerMixin #gives fit_transform method for free
    class MyLabelBinarizer(TransformerMixin):
        def __init__(self, *args, **kwargs):
            self.encoder = LabelBinarizer(*args, **kwargs)
        def fit(self, x, y=0):
            self.encoder.fit(x)
            return self
        def transform(self, x, y=0):
            return self.encoder.transform(x)
    
  2. 保持代码相同而不是使用LabelBinarizer(),使用我们创建的类:MyLabelBinarizer()。

  3. <小时/> 注意:如果要访问LabelBinarizer属性(例如classes_),请将以下行添加到fit方法:

        self.classes_, self.y_type_, self.sparse_input_ = self.encoder.classes_, self.encoder.y_type_, self.encoder.sparse_input_
    

答案 1 :(得分:49)

我相信你的例子来自于动手机器学习与Scikit-Learn&amp; amp; TensorFlow 。不幸的是,我也遇到了这个问题。 scikit-learn0.19.0)最近的更改改变了LabelBinarizer fit_transform方法。遗憾的是,LabelBinarizer从未打算如何使用该示例。您可以查看有关更改herehere的信息。

在他们为此提出解决方案之前,您可以安装以前的版本(0.18.0),如下所示:

$ pip install scikit-learn==0.18.0

运行之后,您的代码应无问题地运行。

将来,看起来正确的解决方案可能是使用CategoricalEncoder类或类似的类。他们多年来一直试图解决这个问题。您可以查看新课程here并进一步讨论问题here

答案 2 :(得分:8)

由于LabelBinarizer不允许超过2个位置参数,您应该创建自定义二进制文件,如

class CustomLabelBinarizer(BaseEstimator, TransformerMixin):
    def __init__(self, sparse_output=False):
        self.sparse_output = sparse_output
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        enc = LabelBinarizer(sparse_output=self.sparse_output)
        return enc.fit_transform(X)

num_attribs = list(housing_num)
cat_attribs = ['ocean_proximity']

num_pipeline = Pipeline([
    ('selector', DataFrameSelector(num_attribs)),
    ('imputer', Imputer(strategy='median')),
    ('attribs_adder', CombinedAttributesAdder()),
    ('std_scalar', StandardScaler())
])

cat_pipeline = Pipeline([
    ('selector', DataFrameSelector(cat_attribs)),
    ('label_binarizer', CustomLabelBinarizer())
])

full_pipeline = FeatureUnion(transformer_list=[
    ('num_pipeline', num_pipeline),
    ('cat_pipeline', cat_pipeline)
])

housing_prepared = full_pipeline.fit_transform(new_housing)

答案 3 :(得分:6)

我遇到了同样的问题,并通过应用book's Github repo中指定的解决方法使其正常工作。

  

警告:本书的早期版本使用了LabelBinarizer类   这点。同样,这是不正确的:就像LabelEncoder一样   class,LabelBinarizer类设计用于预处理标签,而不是   输入功能。更好的解决方案是使用即将推出的Scikit-Learn   CategoricalEncoder类:它很快将被添加到Scikit-Learn,和   在此期间,您可以使用下面的代码(从Pull Request复制   #9151)。

为了节省您的一些问题,请使用解决方法,只需在上一个单元格中粘贴并运行它:

# Definition of the CategoricalEncoder class, copied from PR #9151.
# Just run this cell, or copy it to your code, do not try to understand it (yet).

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array
from sklearn.preprocessing import LabelEncoder
from scipy import sparse

class CategoricalEncoder(BaseEstimator, TransformerMixin):
    def __init__(self, encoding='onehot', categories='auto', dtype=np.float64,
                 handle_unknown='error'):
        self.encoding = encoding
        self.categories = categories
        self.dtype = dtype
        self.handle_unknown = handle_unknown

    def fit(self, X, y=None):
        """Fit the CategoricalEncoder to X.
        Parameters
        ----------
        X : array-like, shape [n_samples, n_feature]
            The data to determine the categories of each feature.
        Returns
        -------
        self
        """

        if self.encoding not in ['onehot', 'onehot-dense', 'ordinal']:
            template = ("encoding should be either 'onehot', 'onehot-dense' "
                        "or 'ordinal', got %s")
            raise ValueError(template % self.handle_unknown)

        if self.handle_unknown not in ['error', 'ignore']:
            template = ("handle_unknown should be either 'error' or "
                        "'ignore', got %s")
            raise ValueError(template % self.handle_unknown)

        if self.encoding == 'ordinal' and self.handle_unknown == 'ignore':
            raise ValueError("handle_unknown='ignore' is not supported for"
                             " encoding='ordinal'")

        X = check_array(X, dtype=np.object, accept_sparse='csc', copy=True)
        n_samples, n_features = X.shape

        self._label_encoders_ = [LabelEncoder() for _ in range(n_features)]

        for i in range(n_features):
            le = self._label_encoders_[i]
            Xi = X[:, i]
            if self.categories == 'auto':
                le.fit(Xi)
            else:
                valid_mask = np.in1d(Xi, self.categories[i])
                if not np.all(valid_mask):
                    if self.handle_unknown == 'error':
                        diff = np.unique(Xi[~valid_mask])
                        msg = ("Found unknown categories {0} in column {1}"
                               " during fit".format(diff, i))
                        raise ValueError(msg)
                le.classes_ = np.array(np.sort(self.categories[i]))

        self.categories_ = [le.classes_ for le in self._label_encoders_]

        return self

    def transform(self, X):
        """Transform X using one-hot encoding.
        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data to encode.
        Returns
        -------
        X_out : sparse matrix or a 2-d array
            Transformed input.
        """
        X = check_array(X, accept_sparse='csc', dtype=np.object, copy=True)
        n_samples, n_features = X.shape
        X_int = np.zeros_like(X, dtype=np.int)
        X_mask = np.ones_like(X, dtype=np.bool)

        for i in range(n_features):
            valid_mask = np.in1d(X[:, i], self.categories_[i])

            if not np.all(valid_mask):
                if self.handle_unknown == 'error':
                    diff = np.unique(X[~valid_mask, i])
                    msg = ("Found unknown categories {0} in column {1}"
                           " during transform".format(diff, i))
                    raise ValueError(msg)
                else:
                    # Set the problematic rows to an acceptable value and
                    # continue `The rows are marked `X_mask` and will be
                    # removed later.
                    X_mask[:, i] = valid_mask
                    X[:, i][~valid_mask] = self.categories_[i][0]
            X_int[:, i] = self._label_encoders_[i].transform(X[:, i])

        if self.encoding == 'ordinal':
            return X_int.astype(self.dtype, copy=False)

        mask = X_mask.ravel()
        n_values = [cats.shape[0] for cats in self.categories_]
        n_values = np.array([0] + n_values)
        indices = np.cumsum(n_values)

        column_indices = (X_int + indices[:-1]).ravel()[mask]
        row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
                                n_features)[mask]
        data = np.ones(n_samples * n_features)[mask]

        out = sparse.csc_matrix((data, (row_indices, column_indices)),
                                shape=(n_samples, indices[-1]),
                                dtype=self.dtype).tocsr()
        if self.encoding == 'onehot-dense':
            return out.toarray()
        else:
            return out

答案 4 :(得分:4)

我认为您正在浏览本书中的示例:Hands on Machine Learning with Scikit Learn and Tensorflow。在阅读第2章中的示例时,我遇到了相同的问题。

正如其他人所提到的,问题在于sklearn的LabelBinarizer。与管道中的其他转换器相比,其fit_transform方法所需的args更少。 (仅当其他变压器通常同时使用X和y时才使用y,有关详细信息,请参见here)。这就是为什么当我们运行pipeline.fit_transform时,我们向该转换器提供了比所需数量更多的args。

我使用的一个简单修复方法是仅使用OneHotEncoder并将“ sparse”设置为False,以确保输出是与num_pipeline输出相同的numpy数组。 (这样一来,您无需编写自己的自定义编码器)

您的原始cat_pipeline:

cat_pipeline = Pipeline([
('selector', DataFrameSelector(cat_attribs)),
('label_binarizer', LabelBinarizer())
])

您只需将此部分更改为:

cat_pipeline = Pipeline([
('selector', DataFrameSelector(cat_attribs)),
('one_hot_encoder', OneHotEncoder(sparse=False))
])

您可以从这里开始,一切都会正常工作。

答案 5 :(得分:1)

我遇到了同样的问题,并通过使用DataFrameMapper(需要安装sklearn_pandas)得到解决:

from sklearn_pandas import DataFrameMapper
cat_pipeline = Pipeline([
    ('label_binarizer', DataFrameMapper([(cat_attribs, LabelBinarizer())])),
])

答案 6 :(得分:1)

忘记LaberBinarizer,改用OneHotEncoder。

如果在OneHotEncoder之前使用LabelEncoder将类别转换为整数,则现在可以直接使用OneHotEncoder。

答案 7 :(得分:1)

最简单的方法是将管道内的 LabelBinarize() 替换为 OrdinalEncoder()

答案 8 :(得分:1)

此示例中的 LabelBinarizer 类已过时,不幸的是,它从未打算按照本书使用的方式使用。

您需要使用 OrdinalEncoder 中的 sklearn.preprocessing 类,该类旨在

<块引用>

“将分类特征编码为整数数组。” (sklearn 文档)。

所以,只需添加:

from sklearn.preprocessing import OrdinalEncoder

然后在您的代码中用 LabelBinarizer() 替换所有提到的 OrdinalEncoder()

答案 9 :(得分:0)

我最终滚动了自己的

class LabelBinarizer(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        X = self.prep(X)
        unique_vals = []
        for column in X.T:
            unique_vals.append(np.unique(column))
        self.unique_vals = unique_vals
    def transform(self, X, y=None):
        X = self.prep(X)
        unique_vals = self.unique_vals
        new_columns = []
        for i, column in enumerate(X.T):
            num_uniq_vals = len(unique_vals[i])
            encoder_ring = dict(zip(unique_vals[i], range(len(unique_vals[i]))))
            f = lambda val: encoder_ring[val]
            f = np.vectorize(f, otypes=[np.int])
            new_column = np.array([f(column)])
            if num_uniq_vals <= 2:
                new_columns.append(new_column)
            else:
                one_hots = np.zeros([num_uniq_vals, len(column)], np.int)
                one_hots[new_column, range(len(column))]=1
                new_columns.append(one_hots)
        new_columns = np.concatenate(new_columns, axis=0).T        
        return new_columns

    def fit_transform(self, X, y=None):
        self.fit(X)
        return self.transform(X)

    @staticmethod
    def prep(X):
        shape = X.shape
        if len(shape) == 1:
            X = X.values.reshape(shape[0], 1)
        return X

似乎工作

lbn = LabelBinarizer()
thingy = np.array([['male','male','female', 'male'], ['A', 'B', 'A', 'C']]).T
lbn.fit(thingy)
lbn.transform(thingy)

返回

array([[1, 1, 0, 0],
       [1, 0, 1, 0],
       [0, 1, 0, 0],
       [1, 0, 0, 1]])

答案 10 :(得分:0)

您可以再创建一个Custom Transformer来为您编码。

  <Target Name="CopyChromeDriverToBin" BeforeTargets="AfterBuild">
    <Copy SourceFiles="$(ChromeDriverSrcPath)" DestinationFiles="$(TargetDir)$(ChromeDriverName)" SkipUnchangedFiles="true">
    </Copy>
  </Target>

在此示例中,我们完成了LabelEncoding,但您也可以使用LabelBinarizer

答案 11 :(得分:0)

简单来说,您可以做的就是在管道之前定义以下类:

class NewLabelBinarizer(LabelBinarizer):
    def fit(self, X, y=None):
        return super(NewLabelBinarizer, self).fit(X)
    def transform(self, X, y=None):
        return super(NewLabelBinarizer, self).transform(X)
    def fit_transform(self, X, y=None):
        return super(NewLabelBinarizer, self).fit(X).transform(X)

然后其余的代码就像书中提到的那样,在管道连接之前对cat_pipeline进行了微小的修改-如下:

cat_pipeline = Pipeline([
    ("selector", DataFrameSelector(cat_attribs)),
    ("label_binarizer", NewLabelBinarizer())])

您完成了!

答案 12 :(得分:0)

我也面临同样的问题。以下链接帮助我解决了此问题。 https://github.com/ageron/handson-ml/issues/75

总结要进行的更改

1)在笔记本中定义以下课程

Class SupervisionFriendlyLabelBinarizer(LabelBinarizer):

   def fit_transform(self, X, y=None):

       return super(SupervisionFriendlyLabelBinarizer, self).fit_transform(X)

2)修改以下代码

  cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)),
                     ('label_binarizer', SupervisionFriendlyLabelBinarizer()),])

3)重新运行笔记本。您现在就可以运行

答案 13 :(得分:0)

我见过许多自定义标签二值化器,但 repo 中有一个对我有用。

class LabelBinarizerPipelineFriendly(LabelBinarizer):
    def fit(self, X, y=None):
        """this would allow us to fit the model based on the X input."""
        super(LabelBinarizerPipelineFriendly, self).fit(X)
    def transform(self, X, y=None):
        return super(LabelBinarizerPipelineFriendly, self).transform(X)

    def fit_transform(self, X, y=None):
        return super(LabelBinarizerPipelineFriendly, self).fit(X).transform(X)

然后将 cat_pipeline 编辑为:

cat_pipeline = Pipeline([
        ('selector', DataFrameSelector(cat_attribs)),
        ('label_binarizer', LabelBinarizerPipelineFriendly()),
    ])

祝你好运!

答案 14 :(得分:-1)

要对多个分类功能执行单热编码,我们可以创建一个新类,自定义我们自己的多个分类功能二进制文件,并将其插入到分类管道中,如下所示。

假设CAT_FEATURES = ['cat_feature1', 'cat_feature2']是分类功能列表。以下脚本应解决问题并产生我们想要的东西。

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin

class CustomLabelBinarizer(BaseEstimator, TransformerMixin):
    """Perform one-hot encoding to categorical features."""
    def __init__(self, cat_features):
        self.cat_features = cat_features

    def fit(self, X_cat, y=None):
        return self

    def transform(self, X_cat):
        X_cat_df = pd.DataFrame(X_cat, columns=self.cat_features)
        X_onehot_df = pd.get_dummies(X_cat_df, columns=self.cat_features)
        return X_onehot_df.values

# Pipeline for categorical features.
cat_pipeline = Pipeline([
    ('selector', DataFrameSelector(CAT_FEATURES)),
    ('onehot_encoder', CustomLabelBinarizer(CAT_FEATURES))
])

答案 15 :(得分:-1)

我们只需添加属性sparce_output = False

cat_pipeline = Pipeline([
  ('selector', DataFrameSelector(cat_attribs)),
  ('label_binarizer', LabelBinarizer(sparse_output=False)),   
])