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
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]]])
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
.
Realised that this was a case of argument unpacking and thus would need to use *
operator. Here is the minimal working example.
import numpy as np
shape = (2, 3, 4)
H = np.random.rand(*shape)
The following StackOverflow answer has more details on the working of the star operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With