gpt4 book ai didi

python - 获取选定的特征名称 TFIDF Vectorizer

转载 作者:太空狗 更新时间:2023-10-29 17:58:30 25 4
gpt4 key购买 nike

我正在使用 python,我想获取大量数据的 TFIDF 表示,我正在使用以下代码将文档转换为 TFIDF 形式。

from sklearn.feature_extraction.text import TfidfVectorizer
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{1,}', # 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)

tfidf_df = tfidf_vectorizer.fit_transform(df['text'])

这里我传递了一个参数max_features。矢量化器将选择最佳特征并返回一个 scipy 稀疏矩阵。问题是我不知道选择了哪些功能以及如何将这些功能名称映射回我得到的 scipy 矩阵?基本上,对于从 m 个文档中选择的 n 个特征,我想要一个 m x n 矩阵,并将所选特征作为列名而不是它们的列名整数 ID。我该如何实现?

最佳答案

您可以使用 tfidf_vectorizer.get_feature_names() .这将打印从原始文档中选择的特征名称(选择的术语)。

您还可以使用 tfidf_vectorizer.vocabulary_ 属性获取将特征名称映射到其索引但不会排序的字典。 get_feature_names() 中的数组将按索引排序。

关于python - 获取选定的特征名称 TFIDF Vectorizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42525072/

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