Scikit-Learn报错Error message: fit_transform() takes 2 positional arguments but 3 were given的解决方法

本文介绍了一种在使用sklearn Pipeline进行数据预处理时遇到的常见错误:fit_transform()方法参数数量不匹配的问题。通过自定义MyLabelBinarizer类来适配Pipeline的要求,解决了原始LabelBinarizer类无法正确处理参数的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

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

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', MyLabelBinarizer()),
    ])
from sklearn.pipeline import FeatureUnion

full_pipeline = FeatureUnion(transformer_list=[
        ("num_pipeline", num_pipeline),
        ("cat_pipeline", cat_pipeline),
    ])
housing_prepared = full_pipeline.fit_transform(housing)
housing_prepared

报错
使用sklearn的Pipeline报错:
Error message: fit_transform() takes 2 positional arguments but 3 were given

检错
错误来源是pipeline调用LabelBinarizer的fit_transform方法时发现有三个参数

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

而实际上LabelBinarizer的fit_transform()方法只定义了两个参数

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

解决方法

自己包装一个可以传入三个参数的自定义的LabelBinarizer类

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)
Keep your code the same only instead of using LabelBinarizer(), use the class we created : MyLabelBinarizer().

将代码中的LabelBinarizer类改为自定义的MyLabelBinarizer类。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值