1. 程式人生 > >python中numpy-choice函式

python中numpy-choice函式

RandomState.choice(a, size=None, replace=True, p=None)

–通過給定的一維陣列資料產生隨機取樣

引數:

a:一維陣列或者int型變數,如果是陣列,就按照裡面的範圍來進行取樣,如果是單個變數,則採用np.arange(a)的形式

size : int 或者 tuple of ints, 可選引數
決定了輸出的shape. 如果給定的是, (m, n, k), 那麼 m * n * k 個取樣點將會被取樣. 預設為零,也就是隻有一個取樣點會被取樣回來。

replace : 布林引數,可選引數
決定取樣中是否有重複值

p :一維陣列引數,可選引數
對應著a中每個取樣點的概率分佈,如果沒有標出,則使用標準分佈。

返回值:
samples : single item or ndarray

容易引發的錯誤

Raises:
ValueError
If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size

例子

從 np.arange(5) 中產生一個size為3的隨機取樣:

>>> np.random.choice(5, 3)
array([0, 3, 4])
>>> #This is equivalent to np.random.randint(0,5,3)

從 np.arange(5) 中產生一個非標準的 size為 3的隨機取樣:

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])

從 np.arange(5) 產生一個標準分佈、size為 3、沒有重複替換的隨機取樣:

>>> np.random.choice(5, 3, replace=False)
array([3,1,0])
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]

也可以這樣,不必一定是整型數字:

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
      dtype='|S11')

實際使用中,首先建立一個mask變數,然後通過mask來對需要取樣的資料進行取樣:

...
  mask = np.random.choice(split_size, batch_size)
  captions = data['%s_captions' % split][mask]
  image_idxs = data['%s_image_idxs' % split][mask]
...