# Bootstrap Sampling in Python With Examples

May 3, 2021

This is a tutorial on Bootstrap Sampling in Python. In this tutorial, we will learn what is bootstrapping and then see how to implement it.

Let’s get started.

## What is Bootstrap Sampling?

The definition for bootstrap sampling is as follows :

In statistics, Bootstrap Sampling is a method that involves drawing of sample data repeatedly with replacement from a data source to estimate a population parameter.

This basically means that bootstrap sampling is a technique using which you can estimate parameters like mean for an entire population without explicitly considering each and every data point in the population.

Instead of looking at the entire population, we look at multiple subsets all of the same size taken from the population.

For example, if your population size is 1000. Then to find the mean, instead of considering all the 1000 entries you can take 50 samples of size 4 each and calculate the mean for each sample. This way you will be taking an average of 200 entries (50X4) chosen randomly.

A similar strategy is used by market researchers to carry out research in a huge population.

## How to implement Bootstrap Sampling in Python?

Now let’s look at how to implement bootstrap sampling in python.

We will generate some random data with a predetermined mean. To do that we are going to use the NumPy module in Python.

Let’s start by importing the necessary modules.

### 1. Import the necessary modules.

The modules we need are :

To import these modules, use :

In the next step, we need to generate some random data. Let’s do that using the Numpy module.

### 2. Generate Random Data

Let’s generate a normal distribution with a mean of 300 and with 1000 entries.

The code for that is given below:

We can calculate the mean of this data using :

Output :

Note that this is the actual mean of the population.

### 3. Use Bootstrap Sampling to estimate the mean

Let’s create 50 samples of size 4 each to estimate the mean.

The code for doing that is :

The list sample_mean will contain the mean for all the 50 samples. For estimating the mean of the population we need to calculate the mean for sample_mean.

You can do that using :

Output :

Now if we run the code in this section again then we will get a different output. This is because each time we run the code, we will generate new samples. However, each time the output will be close to the actual mean (300).

On running the code in this section again, we get the following output :

Running it again, we get:

## Complete code to Implement Bootstrap Sampling in Python

Here’s the complete code for this tutorial :

## Conclusion

This tutorial was about Bootstrap Sampling in Python. We learned how to estimate the mean of a population by creating smaller samples. This is very useful in the world of Machine Learning to avoid overfitting. Hope you had fun learning with us!