如何从两个范围绘制2D随机均匀样本

时间:2018-04-10 13:21:48

标签: python numpy

我有两对变量的最小值和最大值。我想从这两个变量的均匀分布中绘制n个随机样本,位于它们的最小值和最大值之间。例如:

min_x = 0
max_x = 10
min_y = 0
max_y = 20

我们说我画三个样本。这些可能是:

[(4, 15), (8, 9), (0, 19)] # First value is drawn randomly with uniform probability between min_x and max_x, second value is drawn similarly between min_y and max_y

如何以简单的方式实现numpy?

我想出了这个:

>>> min_x = 0
>>> max_x = 10
>>> min_y = 0
>>> max_y = 20
>>> sample = np.random.random_sample(2)
>>> sample[0] = (sample[0]) * max_x - min_x
>>> sample[1] = (sample[1]) * max_y - min_y
>>> sample
array([ 1.81221794, 18.0091034 ])

但我觉得应该有一个更简单的解决方案。

编辑:不重复。建议的重复问题的答案涉及整数。

2 个答案:

答案 0 :(得分:4)

numpy中大多数随机生成函数的参数在数组上运行。以下代码生成10个样本,其中第一列从(0,10)均匀分布中绘制,第二列从(0,20)中绘制。

n = 10
xy_min = [0, 0]
xy_max = [10, 20]
data = np.random.uniform(low=xy_min, high=xy_max, size=(n,2))
print(data)

输出

[[ 5.93168121,  7.36060232],
 [ 6.0681728 ,  8.83458336],
 [ 3.51412518,  7.86395892],
 [ 5.28704184, 11.2423749 ],
 [ 8.14407888,  6.30980757],
 [ 8.93337281, 13.39148231],
 [ 6.94694921, 19.50003171],
 [ 2.52280804, 13.21572422],
 [ 3.41855383,  2.56327567],
 [ 4.06155783,  3.95026796]]

答案 1 :(得分:2)

我认为您可以使用np.random.uniform,它专门从统一分布中提取样本。它需要参数highlowsize,因此您可以使用min_xmax_xmin_ymax_y来绘制2个大小为3的样本, list(zip(np.random.uniform(min_x,max_x,3), np.random.uniform(min_y,max_y,3))) #[(5.3104205843005658, 13.505026912687656), (9.2780870724003979, 7.6835513126639921), (8.0256063658604635, 12.539814624240064)] 作为你的高潮和低谷,将两者拉在一起:

[low, high)

请注意,时间间隔为半开private static DateTime GetEpochInYear(int year) { DateTime currentYearEpoch = new DateTime(year, 4, 1); while (currentYearEpoch.DayOfWeek != DayOfWeek.Sunday) { currentYearEpoch = currentYearEpoch.AddDays(1); } return currentYearEpoch; } private static int GetWeekNumber(DateTime dateOfInterest) { DateTime currentYearEpoch = GetEpochInYear(dateOfInterest.Year); if (dateOfInterest < currentYearEpoch) { currentYearEpoch = GetEpochInYear(dateOfInterest.Year - 1); } int days = (int)(dateOfInterest - currentYearEpoch).TotalDays; return (days / 7) +1; } (请参阅相关文档)