<p>内存不足,因为您试图存储65000x6500矩阵。请注意,您正在构造的矩阵根本不是稀疏矩阵。<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html" rel="nofollow noreferrer">^{<cd1>}</a>生成一个介于0和1之间的随机数。所以没有足够的零来让<code>csr_matrix</code>真正压缩数据。实际上,这里根本没有<a href="https://en.wikipedia.org/wiki/Almost_surely" rel="nofollow noreferrer">almost surely</a>零。</p>
<p>如果仔细查看<code>MemoryError</code>回溯,可以看到<a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html" rel="nofollow noreferrer">^{<cd4>}</a>尝试使用稀疏点积(如果可能):</p>
<pre><code>MemoryError Traceback (most recent call last)
887 Y_normalized = normalize(Y, copy=True)
888
--> 889 K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)
890
891 return K
</code></pre>
<p>所以问题不在于<code>cosine_similarity</code>,而在于你的矩阵。尝试初始化实际稀疏矩阵(例如,稀疏度为1%),如下所示:</p>
<pre><code>>>> a = np.zeros((65000, 10))
>>> i = np.random.rand(a.size)
>>> a.flat[i < 0.01] = 1 # Select 1% of indices and set to 1
>>> a = sparse.csr_matrix(a)
</code></pre>
<p>然后,在具有32GB RAM(8GB RAM对我来说不够)的计算机上,运行以下命令而不出现内存错误:</p>
<pre><code>>>> b = cosine_similarity(a)
>>> b
array([[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
...,
[ 0., 0., 0., ..., 1., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.],
[ 0., 0., 0., ..., 0., 0., 0.]])
</code></pre>