【问题标题】:Need help calculating cosine similarity of a sparse matrix需要帮助计算稀疏矩阵的余弦相似度
【发布时间】:2020-11-05 13:27:11
【问题描述】:

我正在尝试计算稀疏矩阵的余弦相似度

<63671x30 sparse matrix of type '<class 'numpy.uint8'>'
    with 131941 stored elements in Compressed Sparse Row format>

问题是我使用了 scikit-learn 的 cosine_similarity 函数,但我得到了这个错误: memoryError: Unable to allocate 29.7 GiB for an array with shape (3984375099,) and data type float64

我在谷歌上搜索了建议我增加页面文件大小的错误,但这样做之后,我的电脑就死机了,我不得不强制关机并重新启动。有什么办法可以克服吗?

【问题讨论】:

  • 你能添加更多关于输入的细节吗?形状,密度等
  • @Marat 它不是很密集,基本上它是 32 个类的矢量化,并且矩阵的形状已经在帖子中。
  • 好吧,你有 130K+ 个项目,因此有数十亿对,稀疏的特征根本没有帮助。对于这个问题,您需要考虑其他一些事情,以使其易于管理。
  • 显示准确的调用和错误回溯。
  • 你的矩阵的取值范围是多少?只是二进制或更多?此外,考虑到您的数据有多稀疏,错误消息表明该产品比预期的要密集得多。这似乎表明少数特征比其他特征更频繁。你能对此发表评论吗?它可能有助于设计解决方案。

标签: python numpy nlp recommendation-engine


【解决方案1】:

灵感来自:Link

尝试以分块方式进行余弦相似度,即取n 行数并计算它们与整个矩阵的余弦相似度。

from scipy import sparse
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity


def cosine_similarity_n_space(m1, m2, batch_size=100):
    assert m1.shape[1] == m2.shape[1] and isinstance(batch_size, int) == True

    ret = np.ndarray((m1.shape[0], m2.shape[0]))

    batches = m1.shape[0] // batch_size
    
    if m1.shape[0]%batch_size != 0:
        batches = batches + 1  

    for row_i in range(0, batches):
        start = row_i * batch_size
        end = min([(row_i + 1) * batch_size, m1.shape[0]])        
        rows = m1[start: end]
        sim = cosine_similarity(rows, m2)  
        ret[start: end] = sim
    
    return ret


A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)

similarities = cosine_similarity(A_sparse)
chunk_wise_similarity = cosine_similarity_n_space(A_sparse, A_sparse)

comparison = similarities == chunk_wise_similarity
equal_arrays = comparison.all()

print(equal_arrays)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2014-03-25
    • 2016-10-22
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多