【问题标题】:Scikit learn preprocessing LabelBinarizer with lambda functionScikit用lambda函数学习预处理LabelBinarizer
【发布时间】:2018-05-18 03:17:45
【问题描述】:

我正在尝试使用泰坦尼克号数据集。

我想在几列上使用LabelBinarizer,并且我想避免使用 for 循环。

我正在尝试使用lambda 函数,但它不起作用:

from sklearn.preprocessing import LabelBinarizer 

pp = LabelBinarizer()

X = df['sex', 'embarked', 'alive'] df.apply(lambda X: pp.fit_transform())

还有:

df[['sex','embarked','alive']]= df[['sex','embarked','alive']].apply(lambda x: pp.fit_transform(x))

有人能指点我正确的方向吗?

【问题讨论】:

  • 请注意,df.apply 是 Python for-loop 的语法糖。基本上没有性能差异。
  • 将来,当某些东西“不起作用”时,您应该提供错误消息;否则,您的问题可能会被关闭。

标签: python scikit-learn


【解决方案1】:

我认为问题在于,因为您在左侧传递了三个列,所以 sklearn 变得混乱。

替代方案

但正如@unutbu 所说,df.applyfor 在性能上没有区别,所以我就用这个:

for col in ['sex','embarked','alive']:
     df[col] = pp.fit_transform(df[col])

但如果你真的只做一个单行,你可以这样做(警告,大量矫枉过正):

fittranformfit_transform 方法添加另一层缩进,因为格式不起作用(应与def __init__ 方法的缩进匹配。

class MultiColumnLabelBinarizer:
    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] = LabelBinarizer().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelBinarizer().fit_transform(col)
        return output

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

df = MultiColumnLabelBinarizer(columns = ['embarked','alive']).fit_transform(df)

来源:Label encoding across multiple columns in scikit-learn

【讨论】:

  • 感谢您的详尽回答,非常感谢!
猜你喜欢
  • 2016-04-29
  • 2013-12-05
  • 2014-12-06
  • 2018-08-18
  • 1970-01-01
  • 2023-04-05
  • 2018-05-28
  • 2016-02-11
  • 1970-01-01
相关资源
最近更新 更多