Nip*_*tra 1 python random numpy
我np.random.rand用来创建所需形状的矩阵/张量.但是,此形状参数(在运行时生成)是一个元组,如:(2,3,4).我们如何利用这个shape在np.random.rand?
做np.random.rand(shape)不起作用,会出现以下错误:
TypeError: 'tuple' object cannot be interpreted as an index
Cor*_*mer 18
您可以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]]])
Run Code Online (Sandbox Code Playgroud)
意识到这是参数解包的情况,因此需要使用*运算符。这是最小的工作示例。
import numpy as np
shape = (2, 3, 4)
H = np.random.rand(*shape)
Run Code Online (Sandbox Code Playgroud)
以下StackOverflow 答案提供了有关星号运算符工作原理的更多详细信息。
你也可以使用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]]])
Run Code Online (Sandbox Code Playgroud)
事实上,如果你看到NumPy的注释np.random.rand,它说:
这是一个便利功能.如果您想要一个以shape-tuple作为第一个参数的接口,请参阅
np.random.random_sample.
| 归档时间: |
|
| 查看次数: |
5423 次 |
| 最近记录: |