我不确定这是否可行但是这里有.假设我有一个数组:
array1 = [0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个numpy 1D数组,由5个元素组成,这些元素是从array1中随机抽取的,条件是sum等于1.例如,类似于numpy数组[.2,.2,.2,.1,.1].
目前我使用随机模块和看起来像这样的选择函数:
range1= np.array([choice(array1),choice(array1),choice(array1),choice(array1),choice(array1)])
然后检查range1以查看它是否符合标准; 我想知道是否有更快的方式,类似的东西
randomArray = np.random.random().
如果我可以将这个数组存储在某个库中会更好,如果我尝试生成100个这样的数组,那就没有重复,但这不是必需的.
numpy.random.choice如果你使用numpy 1.7.0+,你可以使用:
>>> import numpy as np
>>> array1 = np.array([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
>>> np.random.choice(array1, 5)
array([ 0. , 0. , 0.3, 1. , 0.3])
>>> np.random.choice(array1, 5, replace=False)
array([ 0.6, 0.8, 0.1, 0. , 0.4])
Run Code Online (Sandbox Code Playgroud)
要获得总和等于1的5个元素,
>>> import numpy as np
>>>
>>> def solve(arr, total, n):
... while True:
... xs = np.random.choice(arr, n-1)
... remain = total - xs.sum()
... if remain in arr:
... return np.append(xs, remain)
...
>>> array1 = np.array([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1])
>>> print solve(array1, 1, 5)
[ 0.1 0.3 0.4 0.2 0. ]
Run Code Online (Sandbox Code Playgroud)
另一个版本(假设给定的数组已排序):
EPS = 0.0000001
def solve(arr, total, n):
while True:
xs = np.random.choice(arr, n-1)
t = xs.sum()
i = arr.searchsorted(total - t)
if abs(t + arr[i] - total) < EPS:
return np.append(xs, arr[i])
Run Code Online (Sandbox Code Playgroud)