Search code examples
pythonnumpyrandomtypeerrorprobability-distribution

Pass shape tuple to Numpy `random.rand`


I am using np.random.rand to create a matrix/tensor of the desired shape. However, this shape argument (generated in runtime) is a tuple such as: (2, 3, 4). How can we use this shape in np.random.rand?

Doing np.random.rand(shape) doesn't work and would give the following error:

TypeError: 'tuple' object cannot be interpreted as an index


Solution

  • You can also use np.random.random_sample() which accepts the shape as a tuple and also draws from the same half-open interval [0.0, 1.0) of uniform distribution.

    In [458]: shape = (2,3,4)
    
    In [459]: np.random.random_sample(shape)
    Out[459]: 
    array([[[ 0.94734999,  0.33773542,  0.58815246,  0.97300734],
            [ 0.36936276,  0.03852621,  0.46652389,  0.01034777],
            [ 0.81489707,  0.1233162 ,  0.94959208,  0.80185651]],
    
           [[ 0.08508461,  0.1331979 ,  0.03519763,  0.529272  ],
            [ 0.89670103,  0.7133721 ,  0.93304961,  0.58961471],
            [ 0.27882714,  0.39493349,  0.73535478,  0.65071109]]])
    

    In fact, if you see the NumPy notes about np.random.rand, it states :

    This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .