2017年6月5日 星期一

[ Python 常見問題 ] Numpy - Select cells randomly from NumPy array - without replacement

Source From Here
Question
I'm writing some modelling routines in NumPy that need to select cells randomly from a NumPy array and do some processing on them. All cells must be selected without replacement (as in, once a cell has been selected it can't be selected again, but all cells must be selected by the end).

How-To
How about using numpy.random.shuffle or numpy.random.permutation if you still need the original array? If you need to change the array in-place than you can create an index array like this:
>>> import numpy as np
>>> test_array = (np.random.rand(10,3) * 10).astype(int) // Generate testing array
>>> test_array
array([[1, 9, 9],
[1, 3, 7],
[4, 2, 8],
[5, 4, 1],
[3, 1, 0],
[6, 2, 5],
[4, 4, 3],
[4, 9, 9],
[2, 7, 8],
[5, 0, 7]])

>>> index_array = np.arange(test_array.shape[0]) // Generating index array
>>> np.random.shuffle(index_array) // Shuffling the index array for random selection purpose
>>> index_array
array([2, 1, 6, 8, 3, 0, 5, 4, 9, 7])
>>> test_array[index_array[:5]] // Random select 5 element from testing array
array([[4, 2, 8],
[1, 3, 7],
[4, 4, 3],
[2, 7, 8],
[5, 4, 1]])


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...