6

我正在尝试在管道内实现 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

这是怎么回事?有人可以帮忙吗?

4

1 回答 1

3

imblearn.SMOTE没有transform办法。文档在这里

但是除了管道中的最后一步之外的所有步骤都应该有它,以及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'))
])
于 2019-03-09T23:21:31.880 回答