Search code examples
pythonarraysnumpyrandomreshape

How do i sample 6000 elements out of my 4-d array in numpy


So I'm working with an array named train_images of shape (25036, 12, 15, 15) , I need to select 6000 random samples from this array,

I've tried using np.random.choice() screenshot of error message

It returned the error above, seems like it needs to be 1 dimensional, and I definitely do not want to reshape the array,

Please is there any way to get around this issue


Solution

  • To select 6000 random samples from your 4D array without reshaping, you can use np.random.choice() to generate random indices and then use these indices to select the samples from the array.

    Following is the sample code:

    num_samples = 6000
    indices = np.random.choice(train_images.shape[0], num_samples, replace=False)
    selected_samples = train_images[indices]
    

    Here, we first 6000 random indices without replacement, then use these indices to select the corresponding samples from the train_images array. The resulting selected_samples array will have a shape of (6000, 12, 15, 15).