Equivalence to Matlab sprand () in Python?

I am trying to translate a piece of Matlab code into Python. However, I'm not very sure how to properly implement the function sprand()

.

This is how Matlab code uses sprand()

:

% n_z is an integer, n_dw is a matrix
n_p_z_dw = cell(n_z, 1); % n(d,w) * p(z|d,w)
for z = 1:n_z
  n_p_z_dw{z} = sprand(n_dw);

      

And this is how I implement the above logic in Python:

n_p_z_dw = [None]*n_z  # n(d,w) * p(z|d,w)
density = np.count_nonzero(n_dw)/float(n_dw.size)
for i in range(0, n_z):
    n_p_z_dw[i] = scipy.sparse.rand(n_d, n_w, density=density)

      

Seems to work, but I'm not very sure about this. Any comment or suggestion?

+3


source to share


1 answer


The following should be a relatively fast way, I think, for a sparse array A:

import scipy.sparse as sparse
import numpy as np
sparse.coo_matrix((np.random.rand(A.nnz),A.nonzero()),shape=A.shape)

      

This will build a sparse matrix of COO format: it uses A.nonzero()

and as coordinates A.nnz

(the number of non-zero entries in A) to find the number of random numbers generated.




I wonder if this might be a useful addition to the feature scipy.sparse.rand

.

+4


source







All Articles