SciPy

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.

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{numpy.random.RandomState, int, np.random.Generator}, optional

Random number generator or random seed. If not given, the singleton numpy.random will be used.

Returns
ressparse matrix

See also

scipy.sparse.random

Similar function that allows a user-specified random data source.

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
<3x4 sparse matrix of type '<class 'numpy.float64'>'
   with 3 stored elements in Compressed Sparse Row format>
>>> matrix.todense()
matrix([[0.05641158, 0.        , 0.        , 0.65088847],
        [0.        , 0.        , 0.        , 0.14286682],
        [0.        , 0.        , 0.        , 0.        ]])

Previous topic

scipy.sparse.vstack

Next topic

scipy.sparse.random