Python 2.7 文档间相似性:余弦距离

Python 2.7 文档间相似性:余弦距离,python-2.7,numpy,nlp,nltk,scikit-learn,Python 2.7,Numpy,Nlp,Nltk,Scikit Learn,更新问题: 根据“心包膜”的解决方案,我发现了两份文件之间的余弦相似性。我尝试使用该解决方案来找出两个文件之间的相似性。但是test()中再次出现一个错误,即 Traceback (most recent call last): File "3.py", line 103, in <module> main() File "3.py", line 99, in main test(tf_idf_matrix,count,nltkutil.cosine_dist

更新问题:

根据“心包膜”的解决方案,我发现了两份文件之间的余弦相似性。我尝试使用该解决方案来找出两个文件之间的相似性。但是test()中再次出现一个错误,即

Traceback (most recent call last):
  File "3.py", line 103, in <module>
    main()
  File "3.py", line 99, in main
    test(tf_idf_matrix,count,nltkutil.cosine_distance)
  File "3.py", line 46, in test
    doc2 = np.asarray(tdMatrix[j-1].todense()).reshape(-1)
  File "/usr/lib/python2.7/dist-packages/scipy/sparse/csr.py", line 281, in __getitem__
    return self[key,:]                                #[i] or [1:2]
  File "/usr/lib/python2.7/dist-packages/scipy/sparse/csr.py", line 233, in __getitem__
    return self._get_row_slice(row, col)      #[i,1:2]
  File "/usr/lib/python2.7/dist-packages/scipy/sparse/csr.py", line 320, in _get_row_slice
    raise IndexError('index (%d) out of range' % i )
IndexError: index (4) out of range

我正在寻求各自导师的建议。

您的错误如下:

tdMatrix[tdMatrix[i], :]
您的
tdMatrix
是一个2x2浮点数数组,索引本身将失败。也许你的意思是:

doc1 = np.asarray(tdMatrix[i].todense()).reshape(-1)

非常感谢。遵循您的建议后,不会显示任何错误。余弦相似性出现[[1.0.81818021][.81818021 1.]。我不确定这是否正确。因为频率项矩阵在这里显示为:[[1 2][0 2]],但它应该显示为[[0 1 1 1][0 2 1 0]]。你能给我一些建议吗?
doc1 = np.asarray(tdMatrix[i].todense()).reshape(-1)