[英]Generate each column of the numpy array with random number from different range
How to generate a numpy array such that each column of the array comes from a uniform distribution within different ranges efficiently?如何生成一个 numpy 数组,使得数组的每一列都有效地来自不同范围内的均匀分布? The following code uses two for loop which is slow, is there any matrix-style way to generate such array faster?
下面的代码使用了两个很慢的 for 循环,有没有矩阵式的方法可以更快地生成这样的数组? Thanks.
谢谢。
import numpy as np
num = 5
ranges = [[0,1],[4,5]]
a = np.zeros((num, len(ranges)))
for i in range(num):
for j in range(len(ranges)):
a[i, j] = np.random.uniform(ranges[j][0], ranges[j][1])
What you can do is produce all random numbers in the interval [0, 1) first and then scale and shift them accordingly:您可以做的是首先生成区间 [0, 1) 中的所有随机数,然后相应地缩放和移动它们:
import numpy as np
num = 5
ranges = np.asarray([[0,1],[4,5]])
starts = ranges[:, 0]
widths = ranges[:, 1]-ranges[:, 0]
a = starts + widths*np.random.random(size=(num, widths.shape[0]))
So basically, you create an array of the right size via np.random.random(size=(num, widths.shape[0]))
with random number between 0 and 1. Then you scale each value by a factor corresponding to the width of the interval that you actually want to sample.所以基本上,你通过
np.random.random(size=(num, widths.shape[0]))
创建一个大小合适的数组,随机数在 0 到 1 之间。然后你将每个值按对应于您实际想要采样的间隔的宽度。 Finally, you shift them by starts
to account for the different starting values of the intervals.最后,您将它们按
starts
以考虑间隔的不同起始值。
numpy.random.uniform
will broadcast its arguments, it can generate the desired samples by passing the following arguments: numpy.random.uniform
将广播它的参数,它可以通过传递以下参数来生成所需的样本:
low
: the sequence of low values. low
: low
的序列。high
: the sequence of high values. high
:高值的序列。size
: a tuple like (num, m)
, where m
is the number of ranges and num
the number of groups of m
samples to generate. size
:像(num, m)
这样的元组,其中m
是范围的数量, num
是要生成的m
样本组的数量。 For example:例如:
In [23]: num = 5
In [24]: ranges = np.array([[0, 1], [4, 5], [10, 15]])
In [25]: np.random.uniform(low=ranges[:, 0], high=ranges[:, 1], size=(num, ranges.shape[0]))
Out[25]:
array([[ 0.98752526, 4.70946614, 10.35525699],
[ 0.86137374, 4.22046152, 12.28458447],
[ 0.92446543, 4.52859103, 11.30326391],
[ 0.0535877 , 4.8597036 , 14.50266784],
[ 0.55854656, 4.86820001, 14.84934564]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.