将文本特征名称与其tfidf值关联

2 投票
1 回答
5360 浏览
提问于 2025-04-17 18:47

我正在使用scikit-learn这个工具,从一种叫“词袋”的文本中提取特征(这种文本是按单个单词进行分词的)。为此,我使用了一个叫做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))

我想知道有没有更好的、scikit-learn自带的方法来做到这一点。

非常感谢!

1 个回答

5

对于单个文档,这样做应该没问题。如果你的文档数量不多,还有一个替代方案,就是我之前分享的这个方法,它使用了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]

撰写回答