TfidfVectorizer 有一个 vocabulary_ 属性,它对你想要的东西非常有用。该属性是以单词为键,以单词对应的列索引为值的字典。
对于下面的例子,我想要那个字典的逆,因为我使用字典理解。
tfidf_vec = TfidfVectorizer()
transformed = tfidf_vec.fit_transform(raw_documents=['this is a quick example','just to show off'])
index_value={i[1]:i[0] for i in tfidf_vec.vocabulary_.items()}
index_value 将进一步用作查找表。
fit_transform 返回压缩稀疏行格式矩阵。对您想要实现的目标有用的属性是indices 和data。 indices 返回所有实际包含数据的索引,data 返回这些索引中的所有数据。
循环返回的transformed稀疏矩阵如下。
fully_indexed = []
for row in transformed:
fully_indexed.append({index_value[column]:value for (column,value) in zip(row.indices,row.data)})
返回包含以下内容的字典列表。
[{'example': 0.5, 'is': 0.5, 'quick': 0.5, 'this': 0.5},
{'just': 0.5, 'off': 0.5, 'show': 0.5, 'to': 0.5}]
请注意,这样做只会返回特定文档的非零值的单词。查看我示例中的第一个文档,字典中没有 'just', 0.0 键值对。如果你想包括那些,你需要稍微调整一下最终的字典理解。
像这样
fully_indexed = []
transformed = np.array(transformed.todense())
for row in transformed:
fully_indexed.append({index_value[column]:value for (column,value) in enumerate(row)})
我们创建一个密集版本的矩阵作为一个 numpy 数组循环遍历 numpy 数组的每一行枚举内容,然后填充字典列表。
这样做会导致输出还包括文档中不存在的所有单词。
[{'example': 0.5,'is': 0.5,'just': 0.0,'off': 0.0,'quick': 0.5,'show': 0.0,'this': 0.5,'to': 0.0},
{'example': 0.0,'is': 0.0,'just': 0.5,'off': 0.5,'quick': 0.0,'show': 0.5,'this': 0.0,'to': 0.5}]
然后,您可以将字典添加到您的数据框中。
df['tf_idf'] = fully_indexed