I want Scipy to generate a random sparse matrix with a uniform distribution of nonzero elements from -1.0 to 1.0.

Asked 1 years ago, Updated 1 years ago, 125 views

Scipy has a uniform distribution of nonzero elements from -1.0 to 1.0, and
I want to generate a random sparse matrix.

Simply use Scipy's land

scipy.sparse.rand(m,n)


because the element has a uniform distribution between 0.0 and 1.0. All non-zero values are positive.

When generating a random sparse matrix,
Change the upper and lower limits of nonzero element values
Is there an efficient way?

Thank you for your cooperation.

python scipy

2022-09-30 21:16

2 Answers

I understand that it is a uniform distribution from -1.0 to 1.0, so how about the following?[0,1], so I use ceil() to be 1.0.

>>import scope.sparse assp
>>>r=sp.land(100,100)
>>>r2=r*2.0-r.ceil()
>> print r2
(0, 18)  0.105084065469
(0, 96)  -0.667551576265
(3, 60)  0.239045542473
(5, 38)  -0.420674130882
(5, 87)  0.146186464011
(6, 20)  -0.394829441002
               :


2022-09-30 21:16

scipy.sparse.random can pass a random number generator to generate nonzero elements, so use the generator scipy.stats.uniform(loc=-1,scale=2).rvs in [-1,1] for the uniform distribution.

import scope.stats
import scope.sparse

rvs=scipy.stats.uniform(loc=-1, scale=2).rvs#U(loc, loc+scale)
x=scipy.sparse.random(10,5,density=0.1,data_rvs=rvs)

The result I have is

(0,1)-0.351716913146
(8, 0)  -0.308927730864
(9, 2)  0.0949004467739
(5, 4)  0.621192454634
(8, 4)  -0.310937542874

That's it.


2022-09-30 21:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.