numpy的隨機採樣函數
-
np.random.choice(a, size=None,replace=None, p=None)
-
功能:Generates a random sample from a given 1-D array
-
常見的隨機採樣用法如下:
import random # 從0到99的列表中隨機生成10個樣本 out1 = random.sample(range(100),10) # 方法1 # If a is an int, the random sample is generated as if a was np.arange(n) out2 = np.random.choice(100,10) # 方法2 # 結果可能會出現相同的數,通過set()進行去重, out = set(out2) # 從input數組或者列表中隨機生成一個樣本 input = [1,3,6,8] output = np.random.choice(input) # 從input數組或列表中以一定的概率生成樣本 # 選擇元素8的概率最大爲0.4 input = [1,3,6,8] output = np.random.choice(input,p=[0.1,0.2,0.3,0.4]) 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')
-
np.random.choice
的API 如下:choice(a, size=None, replace=True, p=None) Parameters ----------- a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Default is None, in which case a single value is returned. replace : boolean, optional Whether the sample is with or without replacement p : 1-D array-like, optional The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. Returns samples : 1-D ndarray, shape (size,) The generated random samples
See Also
randint, shuffle, permutation
-
np.random.randint(0,10)
-
功能:隨機從0到10之間選取一個數
-
randint(low, high=None, size=None, dtype='l')
-
Return random integers from
low
(inclusive) tohigh
(exclusive)
-
-
np.random.shuffle (array)
- 功能:隨機對給定數組或者列表亂序,默認是axis=0
- 返回的結果就是給定數組本身,只不過順序被打亂
-
np.random.permutation(array)
- 功能:重新對給定數組或者列表排序,如何是多維數組,則沿着first axis重新排列,
- 返回的重新排列後的數組
-