我想从文档中获取给定词列表的tf-idf权重。例如,我对以下单词感兴趣。
document_list = ['''document 1 blabla''', '''document 2 blabla''']words = ['project', 'management', 'uml theory', 'wireframe']
当然,我可以使用sklearn从文档中获取术语和权重。但我想仅从文档组中获取上述单词的权重,使用scikit-learn。任何建议都会对我有很大帮助。
回答:
这就像将TfidfVectorizer
拟合到你固定的所需词列表上,然后使用你的模型一样简单。
证明:
from sklearn.feature_extraction.text import TfidfVectorizerwords = ['project', 'management', 'uml theory', 'wireframe']mod_tfidf = TfidfVectorizer()mod_tfidf.fit_transform(words)<4x5 sparse matrix of type '<class 'numpy.float64'>' with 5 stored elements in Compressed Sparse Row format>
再添加一个单词,看看第二个维度仍然是5
:
mod_tfidf.transform(words + ["dummy"])<5x5 sparse matrix of type '<class 'numpy.float64'>' with 5 stored elements in Compressed Sparse Row format>
编辑:
鉴于你更新的问题和评论:
mod_tfidf.fit(words)mod_tfidf.transform(document_list)
编辑2:
为完整起见,使用vocabulary
参数初始化TfidfVectorizer
也会得到相同的结果。请注意,在这种情况下,words
是单独的单词列表:
mod_tfidf = TfidfVectorizer(vocabulary=words)
在这种情况下,结果特征的排序将由你的words
顺序固定。你可以通过以下方式检查:
mod_tfidf.get_feature_names()