Search code examples
pythonrandomcoding-style

Simple way to create matrix of random numbers


I am trying to create a matrix of random numbers, but my solution is too long and looks ugly

random_matrix = [[random.random() for e in range(2)] for e in range(3)]

this looks ok, but in my implementation it is

weights_h = [[random.random() for e in range(len(inputs[0]))] for e in range(hiden_neurons)]

which is extremely unreadable and does not fit on one line.


Solution

  • Take a look at numpy.random.rand:

    Docstring: rand(d0, d1, ..., dn)

    Random values in a given shape.

    Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).


    >>> import numpy as np
    >>> np.random.rand(2,3)
    array([[ 0.22568268,  0.0053246 ,  0.41282024],
           [ 0.68824936,  0.68086462,  0.6854153 ]])