2016-09-19 287 views
0

我有載體列表:如何從numpy列表中隨機選擇n個元素?

>>> import numpy as np 
>>> num_dim, num_data = 10, 5 
>>> data = np.random.rand(num_data, num_dim) 
>>> data 
array([[ 0.0498063 , 0.18659463, 0.30563225, 0.99681495, 0.35692358, 
     0.47759707, 0.85755606, 0.39373145, 0.54677259, 0.5168117 ], 
     [ 0.18034536, 0.25935541, 0.79718771, 0.28604057, 0.17165293, 
     0.90277904, 0.94016733, 0.15689765, 0.79758063, 0.41250143], 
     [ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 
     0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628], 
     [ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 
     0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942], 
     [ 0.1955419 , 0.02702753, 0.76828842, 0.5438226 , 0.69407709, 
     0.20865243, 0.12783666, 0.81486189, 0.95583274, 0.30157658]]) 

data,我需要隨機挑選3個向量,我可以做到這一點:

>>> import random 
>>> random.sample(data, 3) 
[array([ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 
     0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628]), array([ 0.18034536, 0.25935541, 0.79718771, 0.28604057, 0.17165293, 
     0.90277904, 0.94016733, 0.15689765, 0.79758063, 0.41250143]), array([ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 
     0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942])] 

我已經檢查了文檔在http://docs.scipy.org/doc/numpy/reference/routines.random.html和我無法確定numpy中是否有random.sample()這樣的功能。

是不是numpy.random.sample()random.sample()不一樣?

請問numpyrandom.sample()是否等值?

+3

我認爲您正在尋找'np.random.choice'。雖然你需要傳遞'replace = False',它的行爲與'random.sample'類似。 – ayhan

+1

你想做什麼*做*?什麼'numpy.random.sample'做(或不做),你想(或不想)它做? – BrenBarn

+0

@brenbarn我需要隨機選擇n號。來自矢量列表的元素。 – alvas

回答

4

作爲@ayhan證實,這是可以做到這樣:

>>> data[np.random.choice(len(data), size=3, replace=False)] 
array([[ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 
     0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628], 
     [ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 
     0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942], 
     [ 0.1955419 , 0.02702753, 0.76828842, 0.5438226 , 0.69407709, 
     0.20865243, 0.12783666, 0.81486189, 0.95583274, 0.30157658]]) 

docs

numpy.random.choice(一個,大小=無,替換=真,p = None)

從給定的一維陣列生成隨機樣本

np.random.choice(data, size=3, replace=False)data的索引列表中選擇3個元素而無需替換。

然後data[...]切片索引並檢索np.random.choice選擇的索引。

相關問題