Pass shape tuple to Numpy `random.rand`

Nipun Batra picture Nipun Batra · Apr 24, 2017 · Viewed 9k times · Source

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

Answer

Cory Kramer picture Cory Kramer · Apr 24, 2017

You can unpack your shape tuple using * for example

>>> shape = (2,3,4)
>>> np.random.rand(*shape)
array([[[ 0.20116981,  0.74217953,  0.52646679,  0.11531305],
        [ 0.03015026,  0.3853678 ,  0.60093178,  0.20432243],
        [ 0.66351518,  0.45499515,  0.7978615 ,  0.92803441]],

       [[ 0.92058567,  0.27187654,  0.84221945,  0.19088589],
        [ 0.83938788,  0.53997298,  0.45754298,  0.36799766],
        [ 0.35040683,  0.62268483,  0.66754818,  0.34045979]]])