scipy.sparse.

rand#

scipy.sparse.rand(m, n, density=0.01, format='coo', dtype=None, random_state=None)[source]#

Generate a sparse matrix of the given shape and density with uniformly distributed values.

Warning

This function returns a sparse matrix – not a sparse array. You are encouraged to use random_array to take advantage of the sparse array functionality.

Parameters:
m, nint

shape of the matrix

densityreal, optional

density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items.

formatstr, optional

sparse matrix format.

dtypedtype, optional

type of the returned matrix values.

random_state{None, int, numpy.random.Generator,

If seed is None (or np.random), the numpy.random.RandomState singleton is used. If seed is an int, a new RandomState instance is used, seeded with seed. If seed is already a Generator or RandomState instance then that instance is used.

Returns:
ressparse matrix

See also

random

Similar function allowing a custom random data sampler

random_array

Similar to random() but returns a sparse array

Notes

Only float types are supported for now.

Examples

>>> from scipy.sparse import rand
>>> matrix = rand(3, 4, density=0.25, format="csr", random_state=42)
>>> matrix
<Compressed Sparse Row sparse matrix of dtype 'float64'
    with 3 stored elements and shape (3, 4)>
>>> matrix.toarray()
array([[0.05641158, 0.        , 0.        , 0.65088847],  # random
       [0.        , 0.        , 0.        , 0.14286682],
       [0.        , 0.        , 0.        , 0.        ]])