如何在scikit-learn管道的步骤之间传递值?

时间:2017-07-31 15:05:19

标签: python-3.x scikit-learn

我想使用一个管道,它使用Vectorizer,然后是LDA预处理步骤。 LDA预处理步骤需要Vectorizer的词汇表。

如何将拟合的Vectorizer步骤的词汇表传递到下一个LDA步骤?我试图将管道本身传递给LDA步骤,但遗憾的是这不起作用。

    pipe_full = Pipeline(
        [('vect', StemmedCountVectorizer(strip_accents='unicode', analyzer='word')),
         ('lda', SklLdaModel_mod()),
         ('clf', SGDClassifier(loss='log', penalty='elasticnet', n_iter=5, random_state=42, class_weight={0: 1, 1: 2}))])
    param_grid_full = [{'vect__ngram_range': ((1, 1), (1, 2)), 'vect__stop_words': (None, 'english'),
                        'vect__token_pattern': (r'(?u)\b\w\w+\b', r'(?u)\b([a-zA-Z]{3,})\b'),
                        'vect__stemmer': (None, SnowCastleStemmer(mode='NLTK_EXTENSIONS')),
                        'lda': (None, SklLdaModel_mod(id2word=pipe_full, num_topics=10), SklLdaModel_mod(id2word=pipe_full, num_topics=20)),
                        # 'lda__topics': (100, 200),
                        # 'lda__topics': (10, 20),  # for testing purposes only
                        'clf__alpha': (1e-4, 5e-4)}]

...在SklLdaModel_mod的fit方法中我有:

    if isinstance(self.id2word, Pipeline):
        try:
            self.id2word = {v: k for k, v in self.id2word.named_steps['vect'].vocabulary_.items()}

有任何建议怎么做?

1 个答案:

答案 0 :(得分:0)

@Vivek,

遗憾的是,这不起作用,因为Vectorizer也应该在管道中进行优化。查看不同的参数。

我提出的解决方案有点笨拙:

class XAmplifierForLDA(TransformerMixin, BaseEstimator):
    """
    This class amplifies the return value of the transform method of a model to include the vocab information for the 
    id2word parameter of the LDA model
    """
    def __init__(self, model=None):
        self.model = model

    def fit(self, *args, **kwargs):
        self.model.fit(*args, **kwargs)
        return self

    def transform(self, X, **transform_params):
        """
        This assumes model has a vocabulary
        :param X: 
        :param transform_params: 
        :return: 
        """
        return {'transformed': self.model.transform(X), 'vocab': self.model.vocabulary_}

    def set_params(self, **parameters):
        self.model.set_params(**parameters)
        return self

    def get_params(self, deep=True):
        """ return the parameters of the inner model """
        return {'model': self.model}

然后我将CountVectorizer包装在这个XAmplifierLDA中,然后除了词汇表之外还会返回一个带有转换后的X的字典!

 pipe_full = Pipeline(
            [('vect', XAmplifierForLDA(model=StemmedCountVectorizer(strip_accents='unicode', analyzer='word'))),
             ('lda', SklLdaModel_mod()),
             ('clf', SGDClassifier(loss='log', penalty='elasticnet', n_iter=5, random_state=42, class_weight={0: 1, 1: 2}))])

然后,SklLdaModel_mod类会正确地解释字典。

关于如何更干净地实现这一点的任何其他想法?