python - 在 sklearn 的 Pipeline 中使用 LabelEncoder 给出 : fit_transform takes 2 positional arguments but 3 were given

标签 python pandas machine-learning scikit-learn label-encoding

我一直在尝试运行一些机器学习代码,但在运行管道后,我在拟合阶段一直步履蹒跚。我在各种论坛上浏览过,但没有多大用处。我发现有些人说你不能在管道中使用 LabelEncoder。我不确定这有多真实。如果有人对此事有任何见解,我会很高兴听到他们的声音。

我不断收到此错误:

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

所以我不确定问题是来 self 还是来自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.index
q = 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 encode

strat = ["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 together
run = 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 抛出错误。我很想听听任何人可能提出的任何建议,并且任何可能解决此问题的方法也将不胜感激!谢谢。

最佳答案

问题与 this answer 中发现的问题相同,但在您的情况下使用 LabelEncoderLabelEncoderfit_transform方法需要:

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

Pipeline期望其所有转换器都采用三个位置参数fit_transform(self, X, y)

您可以按照上述答案制作自定义转换器,但是,LabelEncoder 不应该用作特征转换器。关于原因的详细解释可以在 LabelEncoder for categorical features? 中看到。 。因此,如果功能数量太高,我建议不要使用 LabelEcoder 并使用其他一些贝叶斯编码器,例如编码器列表中的 TargetEncoder .

关于python - 在 sklearn 的 Pipeline 中使用 LabelEncoder 给出 : fit_transform takes 2 positional arguments but 3 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64351918/

相关文章:

machine-learning - Google Cloud ML Engine 中未找到训练器模块

python - Numpy array item order - 序列的平均分布

python - 创建 numpy 数组的重要 View

python - Pandas读取数据表前面有字符的CSV文件

python - 属性错误 : module 'pandas' has no attribute '__version__'

pandas - 箱线图错误: 1 ndim Categorical are not supported at this time

python - 检查列表中的重复项时循环会中断吗?

python - 如何在 python for 循环中迭代多个元素

python - 在 Pandas 中将两个系列与 MultiIndex 相乘

python-3.x - 神经网络预测第 n 个方格