我有一个产品数据集的TF-国防军矩阵:
tfidf = TfidfVectorizer().fit_transform(words)其中words是一个描述列表。这将产生一个69258x22024矩阵。
现在我想找到一个新产品和矩阵中的产品之间的余弦相似点,因为我需要找到与它最相似的10个产品。我使用上述相同的方法将其矢量化。
但是,我不能乘以矩阵,因为它们的大小是不同的(新的矩阵就像6个单词,所以是一个1x6矩阵),所以我需要用列数作为原始矩阵的TFIDFVectorizer。
我该怎么做呢?
发布于 2017-07-01 16:52:42
我找到了一种办法让它发挥作用。不需要使用fit_transform,您需要首先将新文档匹配到TFIDF数据库,如下所示:
queryTFIDF = TfidfVectorizer().fit(words)现在,通过使用转换函数,我们可以将该向量“转换”为该矩阵形状:
queryTFIDF = queryTFIDF.transform([query])其中查询是查询字符串。
然后,我们可以找到余弦相似点,并找到10个最相似/相关的文件:
cosine_similarities = cosine_similarity(queryTFIDF, datasetTFIDF).flatten()
related_product_indices = cosine_similarities.argsort()[:-11:-1]发布于 2017-07-01 16:41:50
我认为words变量是不明确的。我建议您将words重命名为corpus。
实际上,您首先将所有文档放在corpus变量中,然后计算cosinus的相似性。
这里有一个例子:
tf_idf.py:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
]
vectorizer = TfidfVectorizer()
tfidf = vectorizer.fit_transform(corpus)
words = vectorizer.get_feature_names()
similarity_matrix = cosine_similarity(tfidf)在您的ipython控制台中执行:
In [1]: run tf_idf.py
In [2]: words
Out[2]: ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
In [3]: tfidf.toarray()
Out[3]:
array([[ 0. , 0.43877674, 0.54197657, 0.43877674, 0. ,
0. , 0.35872874, 0. , 0.43877674],
[ 0. , 0.27230147, 0. , 0.27230147, 0. ,
0.85322574, 0.22262429, 0. , 0.27230147],
[ 0.55280532, 0. , 0. , 0. , 0.55280532,
0. , 0.28847675, 0.55280532, 0. ],
[ 0. , 0.43877674, 0.54197657, 0.43877674, 0. ,
0. , 0.35872874, 0. , 0.43877674]])
In [4]: similarity_matrix
Out[4]:
array([[ 1. , 0.43830038, 0.1034849 , 1. ],
[ 0.43830038, 1. , 0.06422193, 0.43830038],
[ 0.1034849 , 0.06422193, 1. , 0.1034849 ],
[ 1. , 0.43830038, 0.1034849 , 1. ]])注意:
tfidf是一个scipy.sparse.csr.csr_matrix,to_array转换为numpy.ndarray (但是代价很高,只是为了方便地查看内容)。你可以:
import numpy as np
print(np.triu(similarity_matrix, k=1))给予:
array([[ 0. , 0.43830038, 0.1034849 , 1. ],
[ 0. , 0. , 0.06422193, 0.43830038],
[ 0. , 0. , 0. , 0.1034849 ],
[ 0. , 0. , 0. , 0. ]]) 只看到有趣的相似之处。
见:
similarity.html
extraction.html#text-feature-extraction
https://stackoverflow.com/questions/44862712
复制相似问题