简体   繁体   中英

Generate bootstrap sample from ndarray

Is there a way to generate a bootstrap sample on an N-dimensional array? I am limited to using numpy==1.19.4

I have already tried using a for loop on the other dimensions to no avail, but the following works for 1-dimensional arrays.

 import numpy as np # Set random state and number of resamples random.seed(random_state) n_resamples = 9999 # Generate data data_1d = np.arange(2, 3, 0.1) data_nd = np.random.default_rng(42).random((2,3,2)) data = data_1d.copy() # Resample the data with replacement, computing the test statistic for each set of resamples bs_samples = [np.std(np.random.choice(data, size=len(data))) for _ in range(n_resamples)]

If I get your problem, I use to apply this method:

suppose you have this multi-dimensionale array:

 data_nd = np.random.rand(100, 3, 2) data_nd.shape #(100, 3, 2)

you can sample elements with bootstrap in this way:

 n_resamples = 99 data_nd[np.random.randint(len(data_nd), size=len(data_nd)*n_resamples)].reshape(n_resamples, *data_nd.shape).shape

what I'm doing is to randomly extract indices (randint) with replacement and finally reshape the sampling to obtain 99 bootstrapped dataset with the same dimensions of the original one.

Note that by this procedure you are considering as "elements" the arrays along the first ax and so each element that you are sampling have shape (3,2).

I hope that is clear, but if you have any doubt please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM