Python:向矢量化的方法“应用具有随机幂的功率函数”到Numpy Array中的每一行。
我想找到有效的方法来执行以下操作:
- 我有一个已知值的向量,这将是提到以下数组中的第一行。
- 我想创建一个数组。对于除第一行以外的每一行,它本质上是具有随机功率的功率函数的第一行。
例如,我们有一个3x2数组。 第一行是已知的:[0,1,2]。
然后,对于第二行,产生一个随机功率,让它为0.5,然后第二行是:[0^0.5,1^0.5,2^0.5]。
现在,对于第三行,生成一个随机的功率,让它为3,然后第三行是:[0^3,1^3,2^3]。
我可以很容易地使用循环来做到这一点。但是我想知道是否有任何有效的方法将其矢量化(或者在没有矢量化的情况下足够有效)。
示例代码:
beta=np.zeros((3,1000+1))
beta[0]=np.append(0,np.random.uniform(0,1,1000))
for i in range(1,3,1):
p=np.random.uniform(0,2)
beta[i]= beta[0]**p
非常感谢您提前提供帮助!
I would like to find efficient ways to do the following operation:
- I have a vector of known values, which will be the first row in the following array mentioned.
- I would like to create an array. For each row other than the first row, it is essentially the first row applied with a power function with a random power.
For example, we have a 3x2 array.
The first row is known: [0,1,2].
Then for the second row, generate a random power, let it be 0.5, then the second row is: [0^0.5,1^0.5,2^0.5].
Now for the third row, generate a random power, let it be 3, then the third row is: [0^3,1^3,2^3].
I can do this easily with for loop. But I am wondering if there is any efficient way to vectorize it (or just efficient enough without vectorization).
Sample code:
beta=np.zeros((3,1000+1))
beta[0]=np.append(0,np.random.uniform(0,1,1000))
for i in range(1,3,1):
p=np.random.uniform(0,2)
beta[i]= beta[0]**p
Thank you so much for your help in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向救援进行广播:
其中
lo
和hi
是您均匀分布的指数的界限,而num_rows_desired
是您要应用于的许多指数beta
(这将导致这么多行)。这可能是您想做这件事的方式,因为在内存中创建整个
beta
数组是浪费的。只需为beta
生成您的初始行矢量,然后让广播为您完成工作即可。Broadcasting to the rescue:
Where
lo
andhi
are the bounds for your uniformly distributed exponents, andnum_rows_desired
is however many exponents you want to apply tobeta
(which will result in that many rows).This is probably the way you want to do this, since creating your entire
beta
array in memory is wasteful. Simply generate your initial row vector forbeta
and let broadcasting do the work for you.