Select "some" random points from a numpy array

I have two related numpy arrays, X and y . I need to select n random strings from X and store this in an array corresponding to the y value and add an index of selected randomness to it.

I have another index array that stores a list of indexes that I don't want to try.

How can i do this?

Sample data:

 index = [2,3] X = np.array([[0.3,0.7],[0.5,0.5] ,[0.2,0.8], [0.1,0.9]]) y = np.array([[0], [1], [0], [1]]) 

If these X were chosen randomly (where n=2 ):

 randomylSelected = np.array([[0.3,0.7],[0.5,0.5]]) 

desired result:

 index = [0,1,2,3] randomlySelectedY = [0,1] 

How can i do this?

+5
source share
2 answers

I would control an array of booleans that I constantly use to slice an index array and randomly select from the result.

 n = X.shape[0] sampled = np.empty(n, dtype=np.bool) sampled.fill(False) rng = np.arange(n) k = 2 while not sampled.all(): sample = np.random.choice(rng[~sampled], size=k, replace=False) print(X[sample]) print() print(y[sample]) print() sampled[sample] = True [[ 0.2 0.8] [ 0.5 0.5]] [[0] [1]] [[ 0.3 0.7] [ 0.1 0.9]] [[0] [1]] 
0
source

If you want to select n rows in random order, with equal probability of selecting any row:

 n = 2 #for sake of argument randomlySelectedY = np.argsort(np.random.random(4))[:n] #generate a 1x4 array of random, uniformly distributed numbers and then select the indices of the lowest n numbers randomylSelected = X[randomlySelectedY] index = np.linspace(1,np.size(X[:,1]),np.size(X[:,1])) 
0
source

Source: https://habr.com/ru/post/1266949/


All Articles