将文本特性名称链接到它们的tfidf值



我正在使用scikit-learn从"bag of words"文本(按单个单词标记的文本)中提取文本特征。为了做到这一点,我使用了TfidfVectorizer来减少非常频繁的单词(例如:"a","the"等)的权重。

text = 'Some text, with a lot of words...'
tfidf_vectorizer = TfidfVectorizer(
    min_df=1,  # min count for relevant vocabulary
    max_features=4000,  # maximum number of features
    strip_accents='unicode',  # replace all accented unicode char
    # by their corresponding  ASCII char
    analyzer='word',  # features made of words
    token_pattern=r'w{4,}',  # tokenize only words of 4+ chars
    ngram_range=(1, 1),  # features made of a single tokens
    use_idf=True,  # enable inverse-document-frequency reweighting
    smooth_idf=True,  # prevents zero division for unseen words
    sublinear_tf=False)
# vectorize and re-weight
desc_vect = tfidf_vectorizer.fit_transform([text])

我现在希望能够将每个预测特征与其相应的tfidf浮点值链接起来,并将其存储在字典

中。
{'feature1:' tfidf1, 'feature2': tfidf2, ...}

我通过使用

实现了它
d = dict(zip(tfidf_vectorizer.get_feature_names(), desc_vect.data))

我想知道是否有更好的,科学学习的方法来做这样的事情。

非常感谢。

对于单个文档,这应该没问题。当文档集很小时,另一种方法是使用Pandas。

如果您想为多个文档这样做,那么您可以调整DictVectorizer.inverse_transform中的代码:

desc_vect = desc_vect.tocsr()
n_docs = desc_vect.shape[0]
tfidftables = [{} for _ in xrange(n_docs)]
terms = tfidf_vectorizer.get_feature_names()
for i, j in zip(*desc_vect.nonzero()):
    tfidftables[i][terms[j]] = X[i, j]

最新更新