【问题标题】:How to input a 1-D array of dimensions into numpy.random.randn?如何将一维维度数组输入 numpy.random.randn?
【发布时间】:2021-12-21 19:31:12
【问题描述】:

假设我有一个一维数组dims

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

我想创建一个 n 阶正态分布张量,其中 n 是 dims 的大小,dims[i] 是第 i 个维度的大小。

我试过了

A = np.random.randn(dims)

但这不起作用。我可以的

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

这可行,但n 可以很大,n 本身可以是随机的。在这种情况下,如何读取尺寸大小的数组?

【问题讨论】:

    标签: python arrays numpy random


    【解决方案1】:

    当签名为randn(d0, d1, ..., dn) 时,解包是标准Python

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

    randn docs 建议 standard_normal 接受一个元组(或可以被视为元组的数组):

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

    事实上,文档说新代码应该使用这个:

    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)
    

    【讨论】:

      【解决方案2】:

      使用带星号的解包:

      np.random.randn(*dims)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-03
        • 2021-03-16
        • 2013-07-30
        • 2017-01-03
        相关资源
        最近更新 更多