LabelEncoding Строки столбцы DataFrame - PullRequest
0 голосов
/ 26 августа 2018

У меня есть DataFrame с плавающей точкой, строками и строками, которые можно интерпретировать как даты.

Кодировка метки для нескольких столбцов в scikit-learn

from sklearn.base import BaseEstimator, TransformerMixin
class DataFrameSelector(BaseException, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        return X[self.attribute_names].values

class MultiColumnLabelEncoder:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode

    def fit(self,X,y=None):
        return self # not relevant here

    def transform(self,X):
        '''
        Transforms columns of X specified in self.columns using
        LabelEncoder(). If no columns specified, transforms all
        columns in X.
        '''
        output = X.copy()
        if self.columns is not None:
            for col in self.columns:
                output[col] = LabelEncoder().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelEncoder().fit_transform(col)
        return output

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

num_attributes = ["a", "b", "c"]
num_attributes = list(df_num_median)
str_attributes = list(df_str_only)

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

num_pipeline = Pipeline([
    ('selector', DataFrameSelector(num_attributes)), # transforming the Pandas DataFrame into a NumPy array
    ('imputer', Imputer(strategy="median")), # replacing missing values with the median
    ('std_scalar', StandardScaler()), # scaling the features using standardization (subtract mean value, divide by variance)
])

from sklearn.preprocessing import LabelEncoder

str_pipeline = Pipeline([
    ('selector', DataFrameSelector(str_attributes)), # transforming the Pandas DataFrame into a NumPy array 
    ('encoding', MultiColumnLabelEncoder(str_attributes))
])

from sklearn.pipeline import FeatureUnion
full_pipeline = FeatureUnion(transformer_list=[
    ("num_pipeline", num_pipeline),
    #("str_pipeline", str_pipeline) # replaced by line below
    ("str_pipeline", MultiColumnLabelEncoder(str_attributes))
])

df_prepared = full_pipeline.fit_transform(df_combined)

Часть конвейера num_pipeline работает просто отлично.В части str_pipeline я получаю ошибку

IndexError: только целые числа, срезы (:), многоточие (...), numpy.newaxis (None) и целые или логические массивыдопустимые индексы

Этого не произойдет, если я закомментирую MultiColumnLabelEncoder в str_pipeline.Я также создал некоторый код для применения MultiColumnLabelEncoder к набору данных без конвейера, и он работает просто отлично.Есть идеи?В качестве дополнительного шага мне потребуется создать два отдельных конвейера для строк и строк даты.

РЕДАКТИРОВАТЬ: добавлен класс DataFrameSelector

enter image description here

1 Ответ

0 голосов
/ 27 августа 2018

Проблема не в MultiColumnLabelEncoder, а в DataFrameSelector над ней в конвейере.

Вы делаете это:

str_pipeline = Pipeline([
    ('selector', DataFrameSelector(str_attributes)), # transforming the Pandas DataFrame into a NumPy array 
    ('encoding', MultiColumnLabelEncoder(str_attributes))
])

DataFrameSelector возвращает атрибут .values кадра данных, который представляет собой пустой массив. Очевидно, когда вы делаете это в MultiColumnLabelEncoder:

...
...
    if self.columns is not None:
        for col in self.columns:
            output[col] = LabelEncoder().fit_transform(output[col])

ошибка выдается output[col]. Так как output является копией X, который является массивом NumPy (потому что он был преобразован в NUMPY массив DataFrameSelector), и он не имеет информации об именах столбцов.

Поскольку вы уже передаете 'str_attributes' в MultiColumnLabelEncoder, вам не нужно иметь DataFrameSelector в конвейере. Просто сделайте это:

full_pipeline = FeatureUnion(transformer_list=[
    ("num_pipeline", num_pipeline),
    ("str_pipeline", MultiColumnLabelEncoder(str_attributes))
])

Я удалил str_pipeline, потому что теперь у него был только один трансформатор (после удаления DataFrameSelector).

...