如何为多标签分类器/一个vs休息分类器挑选一个sklearn管道?

问题描述 投票:2回答:1

我正在尝试使用one vs rest分类器包装器创建一个多标签分类器。

我使用了TFIDF和分类器的管道。

在拟合管道时,我必须按类别遍历我的数据,然后每次适合管道以对每个类别进行预测。

现在,我想导出这个,就像通常使用pickle或joblib导出拟合模型一样。

例:

pickle.dump(clf,'clf.pickle')

我怎么能用管道做到这一点?即使我挑选了管道,每当我想要预测新关键字时,我是否还需要适应管道?

例:

pickle.dump(pipeline,'pipeline.pickle')
pipeline = pickle.load('pipeline.pickle')

for category in categories:
    pipeline.fit(X_train, y_train[category])
    pipeline.predict(['kiwi'])
    print (predict)

如果我在加载管道后跳过pipeline.fit(X_train, y_train[category]),我只会在预测中获得单个值数组。如果我适合管道,我得到一个三值数组。

另外,如何将网格搜索合并到我的管道中以便导出?

原始数据

keyword        class1 class2 class3
"orange apple"    1      0      1
"lime lemon"      1      0      0
"banana"          0      1      0

categories = ['class1','class2','class3']

管道

SVC_pipeline = Pipeline([
                ('tfidf', TfidfVectorizer(stop_words=stop_words)),
                ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
            ])

Gridsearch(不知道如何将其合并到管道中)

parameters = {'tfidf__ngram_range': [(1, 1), (1, 2)],
              'tfidf__use_idf': (True, False),
              'tfidf__max_df': [0.25, 0.5, 0.75, 1.0],
              'tfidf__max_features': [10, 50, 100, 250, 500, 1000, None],
              'tfidf__stop_words': ('english', None),
              'tfidf__smooth_idf': (True, False),
              'tfidf__norm': ('l1', 'l2', None),
              }

grid = GridSearchCV(SVC_pipeline, parameters, cv=2, verbose=1)
grid.fit(X_train, y_train)

适合管道

for category in categories:
    print('... Processing {}'.format(category))

    SVC_pipeline.fit(X_train, y_train[category])

    # compute the testing accuracy
    prediction = SVC_pipeline.predict(X_test)
    print('Test accuracy is {}'.format(accuracy_score(y_test[category], prediction)))
python scikit-learn pickle pipeline multilabel-classification
1个回答
0
投票

OneVsRestClassifier在内部适合每个类的一个分类器。所以你不应该像你正在做的那样为每个类安装管道

for category in categories:
    pipeline.fit(X_train, y_train[category])
    pipeline.predict(['kiwi'])
    print (predict)

你应该做这样的事情

SVC_pipeline = Pipeline([
                ('tfidf', TfidfVectorizer()), #add your stop_words
                ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
            ])
SVC_pipeline.fit(["apple","boy","cat"],np.array([[0,1,1],[1,1,0],[1,1,1]]))

您现在可以使用保存模型

pickle.dump(SVC_pipeline,open('pipeline.pickle', 'wb'))   

稍后您可以加载模型并使用进行预测

obj = pickle.load(open('pipeline.pickle', 'rb'))
obj.predict(["apple","boy","cat"])

您可以使用MultiLabelBinarizer对多类标签进行二值化,然后再将它们传递给fit方法

样品:

from sklearn.preprocessing import MultiLabelBinarizer
y = [['c1','c2'],['c3'],['c1'],['c1','c3'],['c1','c2','c3']]
mb = MultiLabelBinarizer()
y_encoded = mb.fit_transform(y)
SVC_pipeline.fit(["apple","boy","cat", "dog", "rat"], y_encoded)

使用网格搜索(示例)

grid = GridSearchCV(SVC_pipeline, {'tfidf__use_idf': (True, False)}, cv=2, verbose=1)
grid.fit(["apple","boy","cat", "dog", "rat"], y_encoded)
# Save the pipeline
pickle.dump(grid,open('grid.pickle', 'wb'))
# Later load it back and make predictions
grid_obj = pickle.load(open('grid.pickle', 'rb'))
grid_obj.predict(["apple","boy","cat", "dog", "rat"])
© www.soinside.com 2019 - 2024. All rights reserved.