2017-04-24 104 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]]])