2017-04-24 65 views
1

我使用np.random.rand创建所需形状的矩阵/张量。但是,此形状参数(在运行时生成)是一个元组,例如:(2,3,4)。我们如何在np.random.rand中使用shape将形状元组传递给Numpy`random.rand`

np.random.rand(shape)不工作,将给予以下错误:

TypeError: 'tuple' object cannot be interpreted as an index

回答

5

您还可以使用np.random.random_sample()其接受shape作为一个元组,也从均匀分布的同半开区间[0.0, 1.0)平局。

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]]]) 

事实上,如果你看到了NumPy的事项有关np.random.rand,它指出:

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 .

1

意识到这是争论拆包的情况,因此需要使用*运营商。这是最小的工作示例。

import numpy as np 
shape = (2, 3, 4) 
H = np.random.rand(*shape) 

以下StackOverflow answer有关于星运算符工作的更多细节。

8

您可以使用解包您*元组shape例如

>>> 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]]])