【问题标题】:Adding a self build vocabulary in scikit-learn?在 scikit-learn 中添加自建词汇?
【发布时间】:2016-07-24 22:31:42
【问题描述】:

sklearn.feature_extraction.text.TfidfVectorizer 中,我们可以使用模型的vocabulary 参数注入我们自己的词汇表。但在这种情况下,只有我自己选择的单词用于模型。

我想在我的自定义词汇表中使用自动检测到的功能。

解决此问题的一种方法是创建模型并使用获取特征

vocab=vectorizer.get_feature_names()

在词汇表上附加我的列表

vocab + vocabulary

然后再次构建模型。

有没有办法一步完成整个过程?

【问题讨论】:

    标签: optimization scikit-learn feature-detection vocabulary sklearn-pandas


    【解决方案1】:

    我认为没有比这更简单的方法来实现您想要的。您可以做的一件事是使用 CountVectorizer 的代码来创建词汇表。我浏览了源代码,方法是

    _count_vocab(self, raw_documents, fixed_vocab)
    

    fixed_vocab=False 调用。

    所以我建议您在运行 TfidfVectorizer 之前修改以下代码 (Source) 以创建词汇表。

    def _count_vocab(self, raw_documents, fixed_vocab):
            """Create sparse feature matrix, and vocabulary where fixed_vocab=False
            """
            if fixed_vocab:
                vocabulary = self.vocabulary_
            else:
                # Add a new value when a new vocabulary item is seen
                vocabulary = defaultdict()
                vocabulary.default_factory = vocabulary.__len__
    
            analyze = self.build_analyzer()
            j_indices = _make_int_array()
            indptr = _make_int_array()
            indptr.append(0)
            for doc in raw_documents:
                for feature in analyze(doc):
                    try:
                        j_indices.append(vocabulary[feature])
                    except KeyError:
                        # Ignore out-of-vocabulary items for fixed_vocab=True
                        continue
                indptr.append(len(j_indices))
    
            if not fixed_vocab:
                # disable defaultdict behaviour
                vocabulary = dict(vocabulary)
                if not vocabulary:
                    raise ValueError("empty vocabulary; perhaps the documents only"
                                     " contain stop words")
    
            j_indices = frombuffer_empty(j_indices, dtype=np.intc)
            indptr = np.frombuffer(indptr, dtype=np.intc)
            values = np.ones(len(j_indices))
    
            X = sp.csr_matrix((values, j_indices, indptr),
                              shape=(len(indptr) - 1, len(vocabulary)),
                              dtype=self.dtype)
            X.sum_duplicates()
            return vocabulary, X
    

    【讨论】:

    • 你能再解释一下吗?
    猜你喜欢
    • 2020-01-15
    • 2015-02-22
    • 2013-02-05
    • 2019-03-14
    • 2013-11-25
    • 1970-01-01
    • 2014-08-14
    • 2016-10-18
    • 2016-11-26
    相关资源
    最近更新 更多