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?
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.
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)
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)
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.
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]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With