天天看點

python中numpy-choice函數

文章轉到: https://oldpan.me/archives/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]
...