【问题标题】:easy sampling of vectors from a sparse matrix, and creating a new matrix from the sample (python)从稀疏矩阵中轻松采样向量,并从样本中创建一个新矩阵(python)
【发布时间】:2012-04-08 23:59:24
【问题描述】:

这个问题有两个部分(也许一个解决方案?):

从稀疏矩阵中采样向量:有没有简单的方法从稀疏矩阵中采样向量? 当我尝试使用 random.sample 对行进行采样时,我得到一个 TypeError: sparse matrix length is ambiguous.

from random import sample
import numpy as np
from scipy.sparse import lil_matrix
K = 2
m = [[1,2],[0,4],[5,0],[0,8]]
sample(m,K)    #works OK
mm = np.array(m)
sample(m,K)    #works OK
sm = lil_matrix(m)
sample(sm,K)   #throws exception TypeError: sparse matrix length is ambiguous.

我目前的解决方案是从矩阵中的行数中采样,然后使用getrow(),类似:

indxSampls = sample(range(sm.shape[0]), k)
sampledRows = []
for i in indxSampls:
    sampledRows+=[sm.getrow(i)]

还有其他高效/优雅的想法吗?密集矩阵大小为 1000x30000 并且可能更大。

从稀疏向量列表构造稀疏矩阵:现在想象一下,我有采样向量 sampledRows 的列表,如何在不致密的情况下将其转换为稀疏矩阵,将其转换为列出然后将其转换为 lil_matrix?

【问题讨论】:

    标签: python scipy sparse-matrix sampling


    【解决方案1】:

    试试

    sm[np.random.sample(sm.shape[0], K, replace=False), :]
    

    这会让你得到一个只有 K 行的 LIL 格式矩阵(按照random.sample 确定的顺序)。我不确定它是否超快,但它不会比像您目前正在做的那样手动逐行访问更糟糕,并且可能会预先分配结果。

    【讨论】:

    • 它并没有真正起作用,因为它返回不同长度的列表列表,而不是稀疏(/非稀疏)向量。例如sm.data[sample(xrange(sm.shape[0]), 2)] 返回数组([[1, 2], [8]], dtype=object)
    • @ScienceFriction 哎呀,你是对的:我正在测试一个样本,其中所有行都有条目。我已经将答案更改为类似的东西,实际上可以一步一步让你得到一个稀疏矩阵。
    • + 我不熟悉 xrange() 这似乎非常有用:)
    • TypeError: random_sample() takes at most 1 positional argument (2 given) 也许这在过去有效,但现代版本的 numpy np.random.sample 是 numpy.random.random_sample 的别名,它只接受一个参数 size 并吐出一组随机数。
    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2016-07-29
    • 2012-01-10
    • 2019-05-06
    • 2017-03-31
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多