Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select from numpy array

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

I have another array index which stores a list of index which I dont want to sample.

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's were randomly selected (where n=2):

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

the desired output would be:

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

How can I do this?

like image 494
scutnex Avatar asked Apr 19 '17 21:04

scutnex


People also ask

How to select random elements from a given NumPy array?

You can use the numpy.random.choice () function to select random elements from a given 1-D Numpy array. The following is the syntax – It returns the selected random value or array of values (if selecting more than one random value). The numpy.random.choice () function takes the following parameters – a – The 1-D array to sample from.

How to get random rows from a 2-D array in Python?

Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choicethrough its axiskeyword. Examples Generate a uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5,3)array([0, 3, 4]) # random>>> #This is equivalent to np.random.randint(0,5,3)

How to generate random sample from a given 1-D array?

Generates a random sample from a given 1-D array New in version 1.7.0. Note New code should use the choicemethod of a default_rng()instance instead; please see the Quick Start. Parameters a1-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 it were np.arange(a)

How to shuffle the rows of an array randomly in Python?

The shuffle () function shuffles the rows of an array randomly and then we will display a random row of the 2D array. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.


2 Answers

You can create random indices with np.random.choice:

n = 2  # for 2 random indices index = np.random.choice(X.shape[0], n, replace=False)   

Then you just need to index your arrays with the result:

x_random = X[index] y_random = Y[index] 
like image 59
MSeifert Avatar answered Sep 18 '22 05:09

MSeifert


just to wrap @MSeifert 's answer in a function:

def random_sample(arr: numpy.array, size: int = 1) -> numpy.array:     return arr[np.random.choice(len(arr), size=size, replace=False)] 

useage:

randomly_selected_y = random_sample(Y) 
like image 24
Alon Gouldman Avatar answered Sep 18 '22 05:09

Alon Gouldman