【问题标题】:python imblearn make_pipeline TypeError: Last step of Pipeline should implement fitpython imblearn make_pipeline TypeError:Pipeline的最后一步应该实现fit
【发布时间】:2019-04-06 11:13:35
【问题描述】:

我正在尝试在管道内实现 imblearn 的 SMOTE。我的数据集是存储在 pandas 数据框中的文本数据。请看下面的代码sn-p

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 只是在 SVC 分类器中调整 C。 这次我收到以下错误:

Last step of Pipeline should implement fit.SMOTE(....) doesn't

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

【问题讨论】:

  • 有什么帮助吗?

标签: python scikit-learn imblearn


【解决方案1】:

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

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

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

另一个更简单的选择就是使用 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'))
])

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2011-03-20
    • 1970-01-01
    相关资源
    最近更新 更多