[英]How to input a 1-D array of dimensions into numpy.random.randn?
Say I have a 1-D array dims
:假设我有一个一维数组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.我想创建一个 n 阶正态分布张量,其中 n 是dims
的大小, dims[i]
是第 i 维的大小。
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.这会起作用,但n
可能很大,而且n
本身可以是随机的。 How can I read in a array of the size of the dimensions in this case?在这种情况下,如何读取尺寸大小的数组?
使用带星号的解包:
np.random.randn(*dims)
Unpacking is standard Python when the signature is randn(d0, d1, ..., dn)
当签名为randn(d0, d1, ..., dn)
时,解包是标准 Python
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): randn
docs 建议使用一个元组(或可以被视为元组的数组)的standard_normal
:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.