gpt4 book ai didi

python - 将文本特征名称链接到它们的 tfidf 值

转载 作者:行者123 更新时间:2023-11-28 22:00:10 27 4
gpt4 key购买 nike

我正在使用 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 本地方法来做这样的事情。

非常感谢。

最佳答案

对于单个文档,这应该没问题。另一种适用于文档集较小的方法是 this recipe of mine使用 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]

关于python - 将文本特征名称链接到它们的 tfidf 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15361885/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com