在sklearn的Pipeline中使用LabelEncoder会出现:fit_transform需要2个位置参数,但却提供了3个

我一直在尝试运行一些机器学习代码,但在运行我的pipeline后总是卡在拟合阶段。我查看了各种论坛但收效甚微。我发现有人说不能在pipeline中使用LabelEncoder。我不确定这是不是真的。如果有人对此有任何见解,我会非常高兴听到他们的意见。

我一直得到这个错误:

TypeError: fit_transform() takes 2 positional arguments but 3 were given

因此我不知道问题出在我还是Python上。这是我的代码:

data = pd.read_csv("ks-projects-201801.csv",                   index_col="ID",                   parse_dates=["deadline","launched"],                   infer_datetime_format=True)var = list(data)data = data.drop(labels=[1014746686,1245461087, 1384087152, 1480763647, 330942060, 462917959, 69489148])missing = [i for i in var if data[i].isnull().any()]data = data.dropna(subset=missing,axis=0)le = LabelEncoder()oe = OrdinalEncoder()oh = OneHotEncoder()y = [i for i in var if i=="state"]y = data[var.pop(8)]p,p.index = pd.Series(le.fit_transform(y)),y.indexq = pd.read_csv("y.csv",index_col="ID")["0"]label_y = le.fit_transform(y)x = data[var]obj_feat = x.select_dtypes(include="object")dat_feat = x.select_dtypes(include="datetime64[ns]")dat_feat = dat_feat.assign(dmonth=dat_feat.deadline.dt.month.astype("int64"),                           dyear = dat_feat.deadline.dt.year.astype("int64"),                           lmonth=dat_feat.launched.dt.month.astype("int64"),                           lyear=dat_feat.launched.dt.year.astype("int64"))dat_feat = dat_feat.drop(labels=["deadline","launched"],axis=1)num_feat = x.select_dtypes(include=["int64","float64"])u = dict(zip(list(obj_feat),[len(obj_feat[i].unique()) for i in obj_feat]))le_obj = [i for i in u if u[i]<10]oh_obj = [i for i in u if u[i]<20 and u[i]>10]te_obj = [i for i in u if u[i]>20 and u[i]<25]cb_obj = [i for i in u if u[i]>100]# Pipeline time#Impute and encodestrat = ["constant","most_frequent","mean","median"]sc = StandardScaler()oh_unk = "ignore"encoders = [LabelEncoder(),            OneHotEncoder(handle_unknown=oh_unk),            TargetEncoder(),            CatBoostEncoder()]#num_trans = Pipeline(steps=[("imp",SimpleImputer(strategy=strat[2])),num_trans = Pipeline(steps=[("sc",sc)])#obj_imp = Pipeline(steps=[("imp",SimpleImputer(strategy=strat[1]))])oh_enc = Pipeline(steps=[("oh_enc",encoders[1])])te_enc = Pipeline(steps=[("te_enc",encoders[2])])cb_enc = Pipeline(steps=[("cb_enc",encoders[0])])trans = ColumnTransformer(transformers=[                                        ("num",num_trans,list(num_feat)+list(dat_feat)),                                        #("obj",obj_imp,list(obj_feat)),                                        ("onehot",oh_enc,oh_obj),                                        ("target",te_enc,te_obj),                                        ("catboost",cb_enc,cb_obj)                                        ])models = [RandomForestClassifier(random_state=0),          KNeighborsClassifier(),          DecisionTreeClassifier(random_state=0)]model = models[2]print("Check 4")# Chaining it all togetherrun = Pipeline(steps=[("Transformation",trans),("Model",model)])x = pd.concat([obj_feat,dat_feat,num_feat],axis=1)print("Check 5")run.fit(x,p)

代码运行到run.fit时一切正常,但随后就抛出了错误。我很乐意听到任何人的建议,并且任何可能的解决方案也将不胜感激!谢谢你。


回答:

问题与此回答中提到的一样,但在你的情况下是LabelEncoderLabelEncoderfit_transform方法接受的是:

def fit_transform(self, y):    """Fit label encoder and return encoded labels    ...

Pipeline期望它的所有转换器都接受三个位置参数fit_transform(self, X, y)

你可以按照前述回答中的方法创建一个自定义转换器,然而,LabelEncoder不应被用作特征转换器。关于为什么不应该这样做的详细解释,可以查看LabelEncoder用于分类特征?。因此,我建议不要使用LabelEncoder,如果特征数量过多,可以使用其他贝叶斯编码器,比如你编码器列表中的TargetEncoder

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注