我有一组维基百科的文本。
使用tf-idf,我可以定义每个词的权重。以下是代码:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
wiki = pd.read_csv('people_wiki.csv')
tfidf_vectorizer = TfidfVectorizer(max_features=1000000)
tfidf = tfidf_vectorizer.fit_transform(wiki['text'])
目标是查看类似于tf-idf列中显示的权重:
文件’people_wiki.csv’在这里:
回答:
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