我正在尝试在管道内实现imblearn的SMOTE。我的数据集是存储在pandas数据框中的文本数据。请参见下面的代码片段

text_clf =Pipeline([('vect', TfidfVectorizer()),('scale', StandardScaler(with_mean=False)),('smt', SMOTE(random_state=5)),('clf', LinearSVC(class_weight='balanced'))])

在此之后,我将使用GridsearchCV。
grid = GridSearchCV(text_clf, parameters, cv=4, n_jobs=-1, scoring = 'accuracy')

其中的参数不过是主要针对TfidfVectorizer()调整参数的地方。
我收到以下错误。
 All intermediate steps should be transformers and implement fit and transform. 'SMOTE

发布此错误后,我将代码更改如下。
vect = TfidfVectorizer(use_idf=True,smooth_idf = True, max_df = 0.25, sublinear_tf = True, ngram_range=(1,2))
X = vect.fit_transform(X).todense()
Y = vect.fit_transform(Y).todense()
X_Train,X_Test,Y_Train,y_test = train_test_split(X,Y, random_state=0, test_size=0.33, shuffle=True)
text_clf =make_pipeline([('smt', SMOTE(random_state=5)),('scale', StandardScaler(with_mean=False)),('clf', LinearSVC(class_weight='balanced'))])
grid = GridSearchCV(text_clf, parameters, cv=4, n_jobs=-1, scoring = 'accuracy')

其中parameters只是在C分类器中调整SVC而已。
这次我收到以下错误:
Last step of Pipeline should implement fit.SMOTE(....) doesn't

这是怎么回事?谁能帮忙吗?

最佳答案

imblearn.SMOTE没有transform方法。文件是here

但是,除了管道中的最后一个步骤之外,所有其他步骤都应该包含它,以及fit

要将SMOTE与sklearn管道一起使用,您应该实现一个自定义转换器,并在SMOTE.fit_sample()方法中调用transform

另一个更简单的选择是使用ibmlearn管道:

from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline as imbPipeline

# This doesn't work with sklearn.pipeline.Pipeline because
# SMOTE doesn't have a .tranform() method.
# (It has .fit_sample() or .sample().)
pipe = imbPipeline([
    ...
    ('oversample', SMOTE(random_state=5)),
    ('clf', LinearSVC(class_weight='balanced'))
])

关于python imblearn make_pipeline TypeError : Last step of Pipeline should implement fit,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53114668/

10-12 22:02