在scikit-learn管道中插入CalibratedClassifierCV的正确方法是什么?

时间:2018-04-14 15:17:47

标签: python-3.x pandas scikit-learn

我正在尝试在sklearn管道中添加校准步骤以获得校准分类器,从而在输出中获得have more trustworthy probabilities

到目前为止,我笨拙地试图使用CalibratedClassifierCV插入一个'校准'步骤(愚蠢的再现性示例):

import sklearn.datasets
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfVectorizer

data = sklearn.datasets.fetch_20newsgroups(categories=['alt.atheism', 'sci.space'])
df = pd.DataFrame(data = np.c_[data['data'], data['target']])\
       .rename({0:'text', 1:'class'}, axis = 'columns')

my_pipeline = Pipeline([
    ('vectorizer', TfidfVectorizer()),
    ('classifier', SGDClassifier(loss='modified_huber')),
    ('calibrator', CalibratedClassifierCV(cv=5, method='isotonic'))
])

my_pipeline.fit(df['text'].values, df['class'].values)

但这不起作用(至少不是这样)。有没有人有关于如何正确执行此操作的提示?

1 个答案:

答案 0 :(得分:3)

SGDClassifier对象应该进入CalibratedClassifierCV's base_estimator argument

您的代码可能看起来像这样:

my_pipeline = Pipeline([
    ('vectorizer', TfidfVectorizer()),
    ('classifier', CalibratedClassifierCV(base_estimator=SGDClassifier(loss='modified_huber'), cv=5, method='isotonic'))
])

CalibratedClassifierCV是一个元估算器。