2017-07-02 92 views
1

我有一個相同形狀的N個numpy數組的列表。我需要按照以下方式將它們組合成一個數組。輸出數組的每個元素應該從輸入數組之一的相應位置隨機取出。例如,如果我需要決定在位置[2,0,7]使用什麼值,我將在所有N個輸入數組中找到位於此位置的所有值。所以,我得到N個值,我隨機選擇一個值。如何在numpy中隨機混合N個數組?

讓它更復雜一點。我想爲每個輸入數組分配一個概率,以便要選擇的值的概率取決於它是哪個輸入數組。

回答

0
import numpy as np 
import itertools as it 

x = np.random.choice(np.arange(10), (2,3,4)) # pass probabilities with p=... 
N = 10 
a = [k*np.ones_like(x) for k in range(N)] # list of N arrays of same shape 
y = np.empty(a[0].shape) # output array 

# Generate list of all indices of arrays in a (no matter what shape, this is 
# handled with *) and set elements of output array y. 
for index in list(it.product(*list(np.arange(n) for n in x.shape))): 
    y[index] = a[x[index]][index] 
# a[x[index]] is the array chosen at a given index. 
# a[x[index]][index] is the element of this array at the given index. 

# expected result with the choice of list a: x==y is True for all elements 

「更多複雜的部分」應與參數的numpy.random.choicep處理。其他任何內容都應在評論中解釋。使用*這應該適用於a(我希望)數組的任意形狀。

0

讓我們僅僅使用numpy構建的插件來對待它:它將比for循環更快。

import numpy as np 

# N = 3 dummy arrays for the example 
a = np.zeros([4, 5]) 
b = 10 * np.ones([4, 5]) 
c = 2 * b 

arr = np.array([a, b, c]) # this is a 3D array containing your N arrays 
N = arr.shape[0] 

idx = np.random.choice(range(N), 4 * 5) # 4 and 5 are the common dimensions of your N arrays 

# treating this a a 1D problem, but treating as 2D is possible too. 
arr.reshape(N, 20)[idx.ravel(), np.arange(20)].reshape(4, 5) 

如果想要有不同的概率,則可以通過一個參數p np.random.choice(形狀的陣列(N,),其之和必須爲1):

idx_p = np.random.choice(range(n_arr), 4 * 5, p = [0.1, 0.2, 0.7]) 
arr.reshape(n_arr, 20)[idx_p.ravel(), np.arange(20)].reshape(4, 5) 

這給出:

# first result: 
array([[ 0., 0., 0., 20., 10.], 
     [ 20., 0., 20., 0., 10.], 
     [ 0., 10., 0., 10., 0.], 
     [ 10., 20., 10., 0., 10.]]) 
# second result with many 20, a few 10 and fewer 0: 
array([[ 10., 0., 20., 20., 20.], 
     [ 20., 0., 20., 20., 20.], 
     [ 10., 20., 20., 20., 10.], 
     [ 20., 10., 20., 20., 20.]]) 
相關問題