TfidfVectorizer的词汇和get_features()之间的区别?
问题内容:
我有
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Train the vectorizer
text="this is a simple example"
singleTFIDF = TfidfVectorizer(ngram_range=(1,2)).fit([text])
singleTFIDF.vocabulary_ # show the word-matrix position pairs
# Analyse the training string - text
single=singleTFIDF.transform([text])
single.toarray()
我想为每个值分别关联相应的功能。现在单身的结构是什么?您如何将单个值的位置映射到特征?
如何解释词汇和get_features()的索引?他们有关系吗?两者均具有根据文档提供索引的功能。那令人困惑吗?
问题答案:
属性 vocabulary__ 输出一个字典,其中所有ngram是字典关键字,而各个值是tfidf矩阵中每个ngram(特征)的列位置。方法
_get_feature_names()
输出一个列表,其中的ngrams根据每个要素的列位置出现。因此,您可以使用任一方法来确定哪个tfidf列对应于哪个功能。在下面的示例中,使用get_feature_names()的输出来命名列,可以轻松地将tfidf矩阵转换为熊猫数据帧。还要注意,所有值的权重均相等,并且所有权重的平方和等于1。
singleTFIDF.vocabulary_
Out[41]:
{'this': 5,
'is': 1,
'simple': 3,
'example': 0,
'this is': 6,
'is simple': 2,
'simple example': 4}
singleTFIDF.get_feature_names()
Out[42]: ['example', 'is', 'is simple', 'simple', 'simple example', 'this', 'this is']
import pandas as pd
df = pd.DataFrame(single.toarray(), columns=singleTFIDF.get_feature_names())
df
Out[48]:
example is is simple simple simple example this this is
0 0.377964 0.377964 0.377964 0.377964 0.377964 0.377964 0.377964