np.random.seed(1977)

def generate_random_sparse_array(nrows, ncols, numdense):
    """Generate a random sparse array with -1 or 1 in the non-zero portions"""
i = np.random.randint(0, nrows - 1, numdense)
j = np.random.randint(0, ncols - 1, numdense)
data = np.random.random(numdense)
data[data <= 0.5] = -1
data[data > 0.5] = 1
ij = np.vstack((i, j))
return scipy.sparse.coo_matrix((data, ij), shape=(nrows, ncols))
Matrix multiplication for sparse matrices in Python