【问题标题】:Find given row in a scipy sparse matrix?在 scipy 稀疏矩阵中找到给定的行?
【发布时间】:2012-12-26 09:19:13
【问题描述】:

问题很简单:假设我有一个来自 scipy 稀疏矩阵 M (100,000X500,000) 的给定行 r,我想在 M 矩阵中找到它的位置/索引?我怎样才能有效地做到这一点?

目前我正在尝试以下方式,但速度非常慢。

offset = 500
begin = 0
end  = begin + offset
row = row.todense() #convert sparse to dense
while 1:
    sub_M = M[begin:end,:].todense() #M matrix is too big that its dense cannot fit memory 
    labels=np.all(row == sub_M, axis=1) # here we find row in the sub set of M, but in a dense representation
    begin = end
    end = end + offset
    if (end - offset) == M.shape[0]:
        break
    elif end > M.shape[0]:
        end = M.shape[0]

【问题讨论】:

    标签: python numpy scipy sparse-matrix


    【解决方案1】:

    除非您想深入了解一种或多种稀疏矩阵类型的内部结构,否则您应该为您的矩阵使用 CSR 格式,并且:

    • 计算每个矩阵行的长度(L2范数);换句话说:sum(multiply(M, M), 2)
    • 将 r 归一化为 (L2) 长度 1
    • 矩阵乘法M*r(其中 r 被视为列向量)

    如果M*r 的条目与相应行的长度匹配,那么您就有了匹配项。

    请注意,numpy.linalg.norm 的默认 ord 是 L2 规范。

    【讨论】:

    • 感谢您的精彩提示。我正在尝试规范我的数据,但我不断收到 ValueError:尺寸不匹配。你有什么建议吗?
    • @TsendeeMTS 检查正在相乘的对象的.shape()。另外,请告诉我们是什么操作给您带来了错误。
    【解决方案2】:

    最后,我想出了一个非常简单但非常省时的解决方案。稀疏矩阵中的每一行都被转换为字符串,并与其索引/位置一起放入字典中。然后需要找到的行是字典的键, dic[str(row)] 给我它的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      相关资源
      最近更新 更多