【问题标题】:Python: compare items within two different tfidf matrices of different dimensionsPython:比较两个不同维度的不同tfidf矩阵中的项目
【发布时间】:2017-10-16 09:08:43
【问题描述】:

我想在包含多行的文件上使用 TfidfVectorizer(),每行都是一个短语。然后我想获取一个包含一小部分短语的测试文件,执行 TfidfVectorizer() 然后获取原始文件和测试文件之间的余弦相似度,以便对于测试文件中的给定短语,我检索其中的前 N ​​个匹配项原始文件。这是我的尝试:

corpus = tuple(open("original.txt").read().split('\n'))
test = tuple(open("test.txt").read().split('\n'))


from sklearn.feature_extraction.text import TfidfVectorizer

tf = TfidfVectorizer(analyzer='word', ngram_range=(1,3), min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform(corpus)
tfidf_matrix2 =  tf.fit_transform(test)

from sklearn.metrics.pairwise import linear_kernel 


def new_find_similar(tfidf_matrix2, index, tfidf_matrix, top_n = 5):
    cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten()
    related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index]
    return [(index, cosine_similarities[index]) for index in related_docs_indices][0:top_n]


for index, score in find_similar(tfidf_matrix, 1234567):
       print score, corpus[index]

但是我得到:

for index, score in new_find_similar(tfidf_matrix2, 1000, tfidf_matrix):
       print score, test[index]
Traceback (most recent call last):

  File "<ipython-input-53-2bf1cd465991>", line 1, in <module>
    for index, score in new_find_similar(tfidf_matrix2, 1000, tfidf_matrix):

  File "<ipython-input-51-da874b8d3076>", line 2, in new_find_similar
    cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten()

  File "C:\Users\arron\AppData\Local\Continuum\Anaconda2\lib\site-packages\sklearn\metrics\pairwise.py", line 734, in linear_kernel
    X, Y = check_pairwise_arrays(X, Y)

  File "C:\Users\arron\AppData\Local\Continuum\Anaconda2\lib\site-packages\sklearn\metrics\pairwise.py", line 122, in check_pairwise_arrays
    X.shape[1], Y.shape[1]))

ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 66662 while Y.shape[1] == 3332088

我不介意合并两个文件然后进行转换,但我想确保我不会将测试文件中的任何短语与测试文件中的其他短语进行比较。

任何指针?

【问题讨论】:

    标签: python scikit-learn tf-idf cosine-similarity


    【解决方案1】:

    用语料库中的数据拟合TfidfVectorizer,然后用已经拟合的向量器转换测试数据(即不要调用fit_transform两次):

    tfidf_matrix =  tf.fit_transform(corpus)
    tfidf_matrix2 =  tf.transform(test)
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2020-04-16
      • 2018-02-28
      • 2013-08-17
      • 2017-07-26
      • 2016-08-03
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      相关资源
      最近更新 更多