Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy array of random matrices

Tags:

python

numpy

I'm new to python/numpy and I need to create an array containing matrices of random numbers.

What I've got so far is this:

for i in xrange(samples):
    SPN[] = np.random.random((6,5)) * np.random.randint(0,100)

Which make sense for me as PHP developer but is not working for python. So how do I create a 3 dimensional array to contain this matrices/arrays?

like image 816
Jorge Zapata Avatar asked Nov 14 '13 17:11

Jorge Zapata


People also ask

How do I generate a random matrix in Numpy?

To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand. Parameters : low : [int] Lowest (signed) integer to be drawn from the distribution.

What is random rand () function in Numpy?

numpy. random. rand() function is used to generate random float values from an uniform distribution over [0,1) . These values can be extracted as a single value or in arrays of any dimension.


1 Answers

Both np.random.randint and np.random.uniform, like most of the np.random functions, accept a size parameter, so in numpy we'd do it in one step:

>>> SPN = np.random.randint(0, 100, (3, 6, 5))
>>> SPN
array([[[45, 95, 56, 78, 90],
        [87, 68, 24, 62, 12],
        [11, 26, 75, 57, 12],
        [95, 87, 47, 69, 90],
        [58, 24, 49, 62, 85],
        [38,  5, 57, 63, 16]],

       [[61, 67, 73, 23, 34],
        [41,  3, 69, 79, 48],
        [22, 40, 22, 18, 41],
        [86, 23, 58, 38, 69],
        [98, 60, 70, 71,  3],
        [44,  8, 33, 86, 66]],

       [[62, 45, 56, 80, 22],
        [27, 95, 55, 87, 22],
        [42, 17, 48, 96, 65],
        [36, 64,  1, 85, 31],
        [10, 13, 15,  7, 92],
        [27, 74, 31, 91, 60]]])
>>> SPN.shape
(3, 6, 5)
>>> SPN[0].shape
(6, 5)

.. actually, it looks like you may want np.random.uniform(0, 100, (samples, 6, 5)), because you want the elements to be floating point, not integers. Well, it works the same way. :^)


Note that what you did isn't equivalent to np.random.uniform, because you're choosing an array of values between 0 and 1 and then multiplying all of them by a fixed integer. I'm assuming that wasn't actually what you were trying to do, because it's a little unusual; please comment if that is what you actually wanted.

like image 61
DSM Avatar answered Oct 19 '22 00:10

DSM