生成仅填充值 0 或 1 的随机稀疏矩阵

Generate random sparse matrix filled with only values 0 or 1

我正在尝试使用 SciPy 生成随机 csr_matrix,但我需要它只填充值 0 或 1。

到目前为止,我正在尝试使用:

rand(1000, 10, density=0.2, format='csr', random_state=np.random.randint(0, 2))

我得到了我想要的正确结构和密度,但填充它的值是介于 0 和 1 之间的浮点数。

有没有办法只用 0 或 1 的浮点数生成这个结构?

您可以简单地将随机矩阵中的非零值替换为:

from scipy.sparse import rand

x = rand(1000, 10, density=0.2, format='csr')
x.data[:] = 1

print(np.unique(x.todense().flat))
# [ 0.  1.]

我不认为 random_state= kwarg 做了你认为它做的事 - 它只是允许你指定随机数生成器的种子,或者显式传递一个 np.random.RandomState作为 RNG 的实例。

np.random.randint(0,2,1000)

将生成 1000 个介于 0 和 1 之间的随机变量。然后,由您决定要为矩阵使用哪种容器

my_v = np.random.randint(0,5,1000)
my_v[my_v>1]=1

怎么样

import scipy.sparse as ss
data = ss.random(1000, 10, density=.2, format='csr',
                 data_rvs=np.ones,   # fill with ones
                 dtype='f'           # use float32 first
                 ).astype('int8')    # then convert to int8

ss.random只支持float类型,其中float32是最小的,而int8是可用的最小整数类型。

有关详细信息,请参阅 https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.random.html