Home > database >  How to input a 1-D array of dimensions into numpy.random.randn?
How to input a 1-D array of dimensions into numpy.random.randn?

Time:11-09

Say I have a 1-D array dims:

dims = np.array((1,2,3,4))

I want to create a n-th order normally distributed tensor where n is the size of the dims and dims[i] is the size of the i-th dimension.

I tried to do

A = np.random.randn(dims)

But this doesn't work. I could do

A = np.random.randn(1,2,3,4)

which would work but n can be large and n can be random in itself. How can I read in a array of the size of the dimensions in this case?

CodePudding user response:

Use unpacking with an asterisk:

np.random.randn(*dims)

CodePudding user response:

Unpacking is standard Python when the signature is randn(d0, d1, ..., dn)

In [174]: A = np.random.randn(*dims)
In [175]: A.shape
Out[175]: (1, 2, 3, 4)

randn docs suggests standard_normal which takes a tuple (or array which can be treated as a tuple):

In [176]: B = np.random.standard_normal(dims)
In [177]: B.shape
Out[177]: (1, 2, 3, 4)

In fact the docs, say new code should use this:

In [180]: rgn = np.random.default_rng()
In [181]: rgn.randn
Traceback (most recent call last):
  File "<ipython-input-181-b8e8c46209d0>", line 1, in <module>
    rgn.randn
AttributeError: 'numpy.random._generator.Generator' object has no attribute 'randn'

In [182]: rgn.standard_normal(dims).shape
Out[182]: (1, 2, 3, 4)
  • Related