从 Scikit (Python) 中的管道中检索中间特征

Posted

技术标签:

【中文标题】从 Scikit (Python) 中的管道中检索中间特征【英文标题】:retrieve intermediate features from a pipeline in Scikit (Python) 【发布时间】:2016-01-10 05:00:18 【问题描述】:

我使用的管道与给定的in this example 非常相似:

>>> text_clf = Pipeline([('vect', CountVectorizer()),
...                      ('tfidf', TfidfTransformer()),
...                      ('clf', MultinomialNB()),
... ])

我使用GridSearchCV 在参数网格上找到最佳估计器。

但是,我想使用CountVectorizer() 中的get_feature_names() 方法获取我的训练集的列名。如果不在管道之外实现CountVectorizer(),这可能吗?

【问题讨论】:

【参考方案1】:

使用get_params() 函数,您可以访问管道的各个部分及其各自的内部参数。下面是访问'vect'的例子

text_clf = Pipeline([('vect', CountVectorizer()),
                     ('tfidf', TfidfTransformer()),
                     ('clf', MultinomialNB())]
print text_clf.get_params()['vect']

收益(对我而言)

CountVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
    dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
    lowercase=True, max_df=1.0, max_features=None, min_df=1,
    ngram_range=(1, 1), preprocessor=None, stop_words=None,
    strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b',
    tokenizer=None, vocabulary=None)

在这个例子中我没有为任何数据拟合管道,所以此时调用get_feature_names()会返回一个错误。

【讨论】:

【参考方案2】:

仅供参考

The estimators of a pipeline are stored as a list in the steps attribute:
>>>

>>> clf.steps[0]
('reduce_dim', PCA(copy=True, n_components=None, whiten=False))

and as a dict in named_steps:
>>>

>>> clf.named_steps['reduce_dim']
PCA(copy=True, n_components=None, whiten=False)

来自http://scikit-learn.org/stable/modules/pipeline.html

【讨论】:

以上是关于从 Scikit (Python) 中的管道中检索中间特征的主要内容,如果未能解决你的问题,请参考以下文章

如何从 scikit-learn 中的 TransformedTargetRegressor 管道中的经过训练的估计器访问属性?

管道中的 Scikit-Learn FunctionTransformer 没有其他功能 - 不返回原始数据?

Python:Scikit Learn MLPClassifier 放入管道时出错

unpickling 模型文件 python scikit-learn(管道(memory=None, steps=None, verbose=None))

从磁盘加载包含预训练 Keras 模型的 scikit-learn 管道

scikit-learn 管道中的锁定步骤(防止改装)