Skip to content
ImagineWorld

Distributions of Data

node_idnode-book_building-statistical-models-in-python_chapter-02-distributions-of-data
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleDistributions of Data
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will cover the essential aspects of data and distributions. We will start by covering the types of data and distributions of data. Having covered the essential measurements of distributions, we will describe the normal distribution and its important properties, including the central limit theorem. Finally, we will cover resampling methods such as permutations and transformation methods such as log transformations. This chapter covers the foundational knowledge necessary to begin statistical modeling.

In this chapter, we’re going to cover the following main topics:

  • Understanding data types
  • Measuring and describing distributions
  • The normal distribution and the central limit theorem
  • Bootstrapping
  • Permutations
  • Transformations

This chapter will make use of Python 3.8.

The code for this chapter can be found here – https://github.com/PacktPublishing/Building-Statistical-Models-in-Python – in the ch2 folder.

Please set up a virtual environment or Anaconda environment with the following packages installed:

  • numpy==1.23.0
  • scipy==1.8.1
  • matplotlib==3.5.2
  • pandas==1.4.2
  • statsmodels==0.13.2

Before discussing data distributions, it would be useful to understand the types of data. Understanding data types is critical because the type of data determines what kind of analysis can be used since the type of data determines what operations can be used with the data (this will become clearer through the examples in this chapter). There are four distinct types of data:

  • Nominal data
  • Ordinal data
  • Interval data
  • Ratio data

These types of data can also be grouped into two sets. The first two types of data (nominal and ordinal) are qualitative data, generally non-numeric categories. The last two types of data (interval and ratio) are quantitative data, generally numeric values.

Let’s start with nominal data.

Nominal data is data labeled with distinct groupings. As an example, take machines in a sign factory. It is common for factories to source machines from different suppliers, which would also have different model numbers. For example, the example factory may have 3 of Model A and 5 of Model B (see Figure 2*.1*). The machines would make up a set of nominal data where Model A and Model B are the distinct group labels. With nominal data, there is only one operation that can be performed: equality. Each member of a group is equal while members from different groups are unequal. In our factory example, a Model A machine would be equal to another Model A machine while a Model B machine would be unequal to a Model A machine.

Figure 2.1 – Two groups of machines in a factory

As we can see, with this type of data, we can only group items together under labels. With the next type of data, we will introduce a new feature: order.

The next type of data is like nominal data but exhibits an order. The data can be labeled into distinct groups and the groups can be ordered. We call this type of data ordinal data. Continuing with the factory example, let’s suppose that there is a Model C machine, and Model C is supplied by the same vendor as Model B. However, Model C is the high-performance version, which generates higher output. In this case, Model B and Model C are ordinal data because Model B is a lower-output machine, and Model C is a higher-output machine, which creates a natural order. For instance, we can put the model labels in ascending order of performance: Model B, Model C. University education levels are another example of ordinal data with the levels BS, MS, and PhD. As mentioned, the new operation for this type of data is ordering, meaning the data can be sorted. Thus, ordinal data supports order and equality. While this type of data can be ordered in ascending or descending order, we cannot add or subtract the data, meaning Model B + Model C is not a meaningful statement. The next type of data we will discuss will support addition and subtraction.

The next type of data, interval data, is used to describe data that exists on an interval scale but does not have a clear definition of zero. This means the difference between two data points is meaningful. Take the Celsius temperature scale, for example. The data points are numeric, and the data points are evenly spaced at an interval (for example, 20 and 40 are both 10 degrees away from 30). In this example of the temperature scale, the definition of 0 is arbitrary. For Celsius, 0 happens to be set at water’s freezing point, but this is an arbitrary choice made by the designers of the scale. So, the interval data type supports equality, ordering, and addition/subtraction.

The final data type is ratio data. Like interval data, ratio data is ordered numeric data, but unlike interval data, ratio data has an absolute 0. Absolute 0 means that if the value of a ratio-type variable is zero, none of that variable exists or is present. For example, consider wait times for rides at an amusement park. If no one is in line for the ride, the wait time is 0; new guests can ride the amusement ride immediately. There is no meaningful negative measurement for wait times. A wait time of 0 is the absolute minimum value. Ratio data also supports meaningful multiplication/division, making ratio data the type of data with the most supported operations.

Data visualization is a critical step for understanding distributions and identifying properties of data. In this chapter (and throughout this book), we will utilize matplotlib for visualizing data. While other Python libraries can be used for visualizing data, matplotlib is the de facto standard plotting library for Python. In this section, we will begin using matplotlib to visualize the four types of data discussed previously.

Since the first two types of data are categorical, we will use a bar chart to visualize these distributions of data. Example bar charts are shown in Figure 2*.2*.

Figure 2.2 – Nominal data in a bar chart (left) and ordinal data in a bar chart (right)

The left bar chart in Figure 2*.2* shows the distribution of the Model A machines and Model B machines given in the factory example. The right bar chart shows an example distribution of the education levels of a team of engineers. Note that in the education level bar chart, the x -axis labels are ordered from the lowest level of education to the highest level of education.

The code used to generate Figure 2*.2* is shown next.

The code has three main parts.

  • The library imports: In this case, we are only importing pyplot from matplotlib, which is canonically imported as plt.
  • The code for data creation: After the import statement, there are a few statements to create the data we will plot. The data for the first plot is stored in two Python lists: label and counts, which contain the machine labels and the number of machines, respectively. It’s worth noting that each of these two lists contains the same number of elements (two elements). The education data is stored similarly. While in this example, we are using simple example data, in later chapters, we will have additional steps for retrieving and formatting data.
  • The code for plotting the data: The final step is plotting the data. Since we are plotting two sets of data in this example, we use the subplots method, which will create a grid of plots. The first two arguments to subplots are the number of rows and the number of columns for the grid of figures. In our case, the number of rows is 1 and the number of columns is 2. The subplots method returns two objects; the figure, fig, and the axes, ax. The first returned object, fig, has high-level controls over the figure, such as saving the figure, showing the figure in a new window, and many others. The second object, ax, will either be an individual axis object or an array of axis objects. In our case, ax is an array of axes objects – since our grid has two plots, indexing into ax gives us the axes object. We use the bar method of an axes object to create a bar chart. The bar method has two required arguments. The first required argument is the list of labels. The second argument is the bar heights that correspond to each label, which is why the two lists must have the same length. The other three methods, set_title, set_ylabel, and set_xlabel, set the values for the corresponding plot attributes: title, ylabel, and x-label.

Finally, the figure is created using fig.show():

import matplotlib.pyplot as plt
label = ['model A', 'model B']
counts = [3, 5]
edu_label = ['BS', 'MS', 'PhD']
edu_counts = [10, 5, 2]
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
ax[0].bar(label, counts)
ax[0].set_title('Counts of Machine Models')
ax[0].set_ylabel('Count')
ax[0].set_xlabel('Machine Model')
ax[1].bar(edu_label, edu_counts)
ax[1].set_title('Counts of Education Level')
ax[1].set_ylabel('Count')
ax[1].set_xlabel('Education Level')
fig.show()

Now let’s look at how to plot data from the other two data types.

Since the last two data types are numeric, we will use a histogram to visualize the distributions. Two example histograms are shown in Figure 2*.3*.

Figure 2.3 – Nominal data in a bar chart (left) and ordinal data in a bar chart (right)

The left histogram is synthetic wait time data (ratio data) that might represent wait times at an amusement park. The right histogram is temperature data (interval data) for the Dallas-Fort Worth area during April and May of 2022 (pulled from https://www.iweathernet.com/texas-dfw-weather-records).

The code used to generate Figure 2*.3* is shown next. Again, the code has three main parts, the library imports, the code for data creation, and the code for plotting the data.

Like in the previous example, matplotlib is imported as plt. In this example, we also import a function from scipy; however, this function is only used for generating sample data to work with and we will not discuss it at length here. For our purposes, just think of skewnorm as producing an array of numbers. This code block is very similar to the previous code block.

The main difference is the method used for plotting the data, hist, which creates a histogram. The hist method has one required argument, which is the sequence of numbers to plot in the histogram. The second argument used in this example is bins, which effectively controls the granularity of the histogram – granularity increases with more bins. The bin count of a histogram can be adjusted for the desired visual effect and is generally set experimentally for the data plotted:

from scipy.stats import skewnorm
import matplotlib.pyplot as plt
a = 4
x = skewnorm.rvs(a, size=3000) + 0.5
x = x[x > 0]
dfw_highs = [
85, 87, 75, 88, 80, 86, 90, 94, 93, 92, 90, 92, 94,
93, 97, 90, 95, 96, 96, 95, 92, 70, 79, 73, 88, 92,
94, 93, 95, 76, 78, 86, 81, 95, 77, 71, 69, 88, 86,
89, 84, 82, 77, 84, 81, 79, 75, 75, 91, 86, 86, 84,
82, 68, 75, 78, 82, 83, 85]
fig, ax = plt.subplots(1,2, figsize=(12, 5))
ax[0].hist(x, bins=30)
ax[0].set_xlabel('Wait Time (hr)')
ax[0].set_ylabel('Frequency')
ax[0].set_title('Wait Times');
ax[1].hist(dfw_highs, bins=7)
ax[1].set_title('High Temperatures for DFW (4/2022-5/2022)')
ax[1].set_ylabel('Frequency')
ax[1].set_xlabel('Temperature (F)')
fig.show()

In this section, we had a glimpse into how varied data and distributions can appear. Since distributions of data appear in many shapes and sizes in the wild, it is useful to have methods for describing distributions. In the next section, we will discuss the measurements available for distributions, how those measurements are performed, and the types of data that can be measured.

The distributions of data found in the wild come in many shapes and sizes. This section will discuss how distributions are measured and which measurements apply to the four types of data. These measurements will provide methods to compare and contrast different distributions. The measurements discussed in this section can be broken into the following categories:

  • Central tendency
  • Variability
  • Shape

These measurements are called descriptive statistics. The descriptive statistics discussed in this section are commonly used in statistical summaries of data.

There are three types of measurement of central tendency:

  • Mode
  • Median
  • Mean

Let’s discuss each one of them.

The first measurement of central tendency we will discuss is the mode. The mode of a dataset is simply the most commonly occurring instance. Using the machines in the factory as an example (see Figure 2*.1*), the mode of the dataset would be model B. In the example, there are 3 of model A and 5 of model B, therefore, making model B the most common – the mode.

A dataset can be one of the following:

  • Unimodal – having one mode
  • Multimodal – having more than one mode

In the preceding example, the data is unimodal.

Using the factory example again, let’s imagine that there are 3 of Model A, 5 of Model B, and 5 of Model D (a new model). Then, the dataset will have two modes: Model B and Model D, as shown in Figure 2*.4*.

Figure 2.4 – Multimodel distribution of machines in a factory

Therefore, this dataset is multimodal.

Mode and Data Types

These examples of modes have used nominal data, but all four types of data support the mode because all four data types support the equality operation.

While the mode refers to the most common instance, in multimodal cases of continuous data, the term mode is often used in a less strict sense. For example, the distribution in Figure 2*.5* would commonly be referred to as multimodal even though the peaks of the distribution are not the same magnitude. However, with nominal and ordinal data, it is more common to use the stricter definition of most common when referring to the modality of a distribution.

Figure 2.5 – A multimodal distribution of data

Now, we will look at how to calculate the mode with code using scipy. The scipy library contains functions for calculating descriptive statistics in the stats module. In this example, we import mode from scipy.stats and calculate the mode of the following numbers, 1, 2, 3, 4, 4, 4, ``5, 5:

from scipy.stats import mode
m = mode([1,2,3,4,4,4,5,5])
print(
f"The mode is {m.mode[0]} with a count of"
f" {m.count[0]} instances"
)
# The mode is 4 with a count of 3 instances

The mode function returns a mode object containing mode and count members. Unsurprisingly, the mode and count members contain the modes of the dataset and the number of times the modes appear, respectively. Note that mode and count members are indexable (like lists) because a dataset can contain multiple modes.

The next measure of the center is the median. The median is the middle value occurring when the values are arranged in an order.

Median and Data Types

This measure can be performed on ordinal data, interval data, and ratio data, but not on nominal data.

We will discuss two cases here.

Finding the median when the number of instances is odd

Section titled “Finding the median when the number of instances is odd”

Finding the median of some numeric data is shown in Figure 2*.6*. The data is sorted, then the median is identified.

Figure 2.6 – Identifying the median with an odd number of instances

In the preceding example, the instances are odd in number (7 instances), which have a center value. However, if the number of instances had been even, it would not have been possible to just take the middle number after sorting the values.

Finding the median when the number of instances is even

Section titled “Finding the median when the number of instances is even”

When there are an even number of instances, the average of the two middle-most values is taken. Unlike the mode, there is no concept of multiple medians for the same series of data. An example with an even number of instances (8 instances) is shown in Figure 2*.7*.

Figure 2.7 – Identifying the median with an even number of instances

Now, let’s see how to calculate the median of a dataset with numpy. Like scipy, numpy contains functions for calculating descriptive statistics. We will calculate the median for the eight numbers listed in the preceding example:

import numpy as np
values = [85, 99, 70, 71, 86, 88, 94, 105]
median = np.median(values)
print(f"The median value is {median:.2f}")
# The median value is 87.00

The result of the median calculation is 87, as expected. Note that the median function returns a single value, in contrast to the mode function in the previous code example.

The next center measure is the mean, which is commonly referred to as the average. The mean is defined by the following equation:

Let me explain the equation in words. To calculate the mean, we must add all the values together, then divide the sum by the number of values. Please refer to the following example. The 7 numbers are first added together, which brings the total sum to 593. This sum is then divided by the number of instances, resulting in a value of 84.7.

Figure 2.8 – Finding the mean

Note that the mean and the median of these values (84.7 and 86, respectively) are not the same value. In general, the mean and median will not be the same value, but there are special cases where the mean and median will converge.

Mean and Data Types

As for the supported data types, the mean is valid for interval and ratio data since the values are added together.

Now, we will look at how to calculate the mean with numpy. The following code example shows the calculation of the mean for the values in the previous example:

import numpy as np
values = [85, 99, 70, 71, 86, 88, 94]
mean = np.mean(values)
print(f"The mean value is {mean:.1f}")
# The mean value is 84.7

Like the median function, the mean function returns a single number.

Before concluding this section on center measures, it is worth discussing the use of the mean and median in various situations. As mentioned previously, the median and mean will, in general, be different values. This is an effect driven by the shape of the distribution.

Shape impacts on Mean and Median

If the distribution is symmetric, the mean and median will tend to converge. However, if the distribution is not symmetric, the mean and median will diverge.

The degree to which the measures diverge is driven by how asymmetric the distribution is. Four example distributions are given in Figure 2*.6* to show this effect. Distributions 1 and 2 show the mean pulled toward a higher value than the median. The mean is pulled toward values with a larger absolute value. This is an important effect of the mean to be aware of when a dataset contains (or may contain) outlier values (often called outliers or influential points), which will tend to pull the mean in their direction. Unlike the mean, the median is not affected by outliers if outliers account for a smaller percentage of the data. Outliers will be discussed further in the Measuring variability section.

Figure 2.9 – Two asymmetric distributions and two symmetric distributions

The next category of measurements for distributions is measures of variability.

By variability, we essentially mean how wide a distribution is. The measurements in this category are as follows:

  • Range
  • Quartile ranges
  • Tukey fences
  • Variance

Let’s discuss each of them.

The range is simply the difference between the maximum value and the minimum value in the distribution. Like the mean, the range will be affected by outliers since it depends on the max and min values. However, there is another variability method that, like the median, is robust to the presence of outliers.

Let’s take a look at calculating a range with code with numpy:

import numpy as np
values = [85, 99, 70, 71, 86, 88, 94, 105]
max_value = np.max(values)
min_value = np.min(values)
range_ = max_value - min_value
print(f"The data have a range of {range_}"
f" with max of {max_value}"
f" and min of {min_value}")
# The data have a range of 35 with max of 105 and min of 70

While numpy does not have a range function, the range can be calculated using the min and max functions provided by numpy.

The next measures of variability are determined by sorting the data and then dividing the data into four equal sections. The boundaries of the four sections are the quartiles, which are called the following:

  • The lower quartile (Q1)
  • The middle quartile (Q2)
  • The upper quartile (Q3)

An example of quartiles is shown as follows. Like the median, quartiles are robust to outliers so long as the outliers are a small percentage of the dataset. Note that the middle quartile is, in fact, the median. An adjusted range measurement that is less sensitive to outliers than the normal range discussed in the Range section is the middle quartile, the interquartile range (IQR). The IQR is the difference between the upper and lower quartiles (Q3 - Q1). While this range is less sensitive to outliers, it only contains 50% of the data. Thus, making the interquartile range likely to be less representative of the total variation of the data.

Figure 2.10 – Q1, Q2, and Q3

We can calculate the quartiles and IQR range using numpy and scipy. In the following code example, we use the quantiles function to calculate the quartiles. We will not discuss quantiles here, other than to mention that quantiles are a generalization where the data can be split into any number of equal parts. Since we are splitting the data into four equal parts for quartiles, the quantiles values used for the calculation are 0.25, 0.5, and 0.75. Quartiles Q1 and Q3 could then be used to calculate the IQR. However, we could also use the iqr function from scipy to make the calculation:

import numpy as np
from scipy import stats
values = [85, 99, 70, 71, 86, 88, 94]
quartiles = np.quantile(values, [0.25, 0.5, 0.75],
method="closest_observation")
print(f"The quartiles are Q1: {quartiles[0]},
Q2: {quartiles[1]}, Q3: {quartiles[2]}")
iqr = stats.iqr(values,interpolation='closest_observation')
print(f"The interquartile range is {iqr}")
# The quartiles are Q1: 71, Q2: 85, Q3: 88
# The interquartile range is 17

Note the use of the method and interpolation keyword arguments in the quantiles function and the iqr function, respectively. Several options can be used for these keyword arguments, which will lead to different results.

Quartiles are often visualized with a boxplot. The following Figure 2*.11* shows the main parts of a boxplot. A boxplot is made up of two main parts:

  • The box
  • The whiskers

The box part represents 50% of the data that is contained by the IQR. The whiskers are drawn starting from the edge of the boxes to a length of k * IQR, where k is commonly chosen to be 1.5. Any values beyond the whiskers are considered outliers.

Figure 2.11 – Parts of a box and whisker plot

Figure 2*.12* shows how histograms and boxplots visualize the variability of a symmetric and asymmetric distribution. Notice how the boxplot of the asymmetric data is compressed on the left and expanded on the right, while the other boxplot is clearly symmetric. While a boxplot is useful for visualizing the symmetry of the data and the presence of outliers, the modality of the distribution would not be evident.

Figure 2.12 – Comparison of boxplots and histograms for asymmetric and symmetric distributions

When exploring, it is common to use multiple visualizations since each type of visualization has its own advantages and disadvantages. It is common to use multiple visualizations since each type of visualization has its own advantages and disadvantages.

In the last few sections on measurements, the concept of outliers has appeared a few times. Outliers are values that are atypical compared to the main distribution, or anomalous values. While there are methods for classifying data points as outliers, there is no generally robust method for classifying data points as outliers. Defining outliers typically should be informed by the use case of the data analysis, as there will be different factors to consider based on the application domain. However, it is worth mentioning the common technique shown in the boxplot example called Tukey fences. The lower and upper Tukey fences are based on the IQR and defined as follows:

As mentioned earlier, k is often chosen to be 1.5 as a default value, but there may be a more appropriate value for a given application domain.

Now let’s take a look at how to calculate Tukey fences with numpy and scipy. This code example will build upon the previous example since there is no function to calculate the fences directly. We will again calculate the quartiles and the IQR with numpy and scipy. Then, we apply these operations to the values listed in the preceding equations:

import numpy as np
from scipy import stats
values = stats.norm.rvs(10, size=3000)
q1, q3 = np.quantile(values, [.25, .75],
method='closest_observation')
iqr = stats.iqr(values,interpolation='closest_observation')
lower_fence = q1 - iqr * 1.5
upper_fence = q3 + iqr * 1.5
# may vary due to randomness in data generation
print(f"The lower fence is {lower_fence:.2f} and the upper
fence is {upper_fence:.2f}")
# The lower fence is 7.36 and the upper fence is 12.67

In this case, we used both numpy and scipy; however, the scipy calculation could be replaced with Q3-Q1 as mentioned previously.

The last measure of variability that will be covered in this section is variance. Variance is a measure of dispersion that can be understood as how spread out the numbers are from the average value. The formula for variance, denoted, is as follows:

In this equation, the term () is considered the deviation from the mean, which leads to another measure that is closely related to variance – the standard deviation, which is the square root of variance. The formula for standard deviation, denoted, is given here:

In general, a wider distribution will have a larger variance and a larger standard deviation, but these values are not as easy to interpret as a range or IQR. These concepts will be covered more in detail in the next section, in the context of the normal distribution, which will provide clearer intuition for what these values measure.

Again, these values will be calculated with code using numpy. The functions for variance and standard deviation are var and std, respectively:

import numpy as np
values = [85, 99, 70, 71, 86, 88, 94]
variance = np.var(values)
standard_dev = np.std(values)
print(f"The variance is {variance:.2f} and the standard
deviation is {standard_dev:.2f}")
# The variance is 101.06 and the standard deviation is 10.05

The next type of measure has to do with the shapes of distributions. They are as follows:

  • Skewness
  • Kurtosis

Let’s discuss each of them.

The first measurement is skewness. Put simply, skewness is measurement asymmetry [1]. An example of skewed distributions is shown in Figure 2*.13*.

There are two types of skewed distributions:

  • Left-skewed
  • Right-skewed

A distribution is skewed in the direction of the dominant tail, meaning that a distribution with a dominant tail to the right is right-skewed and a distribution with a dominant tail to the left is left-skewed (as shown in Figure 2*.13*).

Figure 2.13 – Distributions demonstrating skewness

The formula for skewness will not be shown here since it can be calculated trivially with modern software packages. The output of the skewness calculation can be used to determine the skewness and the direction of the skew. If the skewness value is 0 or near 0, the distribution does not exhibit strong skewness. If the skewness is positive, the distribution is right-skewed, and if the skewness value is negative, the distribution is left-skewed. The larger the absolute value of the skewness value, the more the distribution exhibits skewness. An example of how to calculate skewness with scipy is shown in the following code example:

from scipy.stats import skewnorm, norm
from scipy.stats import skew as skew_calc
# generate data
skew_left = -skewnorm.rvs(10, size=3000) + 4
skew_right = skewnorm.rvs(10, size=3000) + 3
symmetric = norm.rvs(10, size=3000)
# calculate skewness
skew_left_value = skew_calc(skew_left)
skew_right_value = skew_calc(skew_right)
symmetric_value = skew_calc(symmetric)
# Output may vary some due to randomness of generated data
print(f"The skewness value of this left skewed
distribution is {skew_left_value:.3f}")
print(f"The skewness value of this right skewed
distribution is {skew_right_value:.3f}")
print(f"The skewness value of this symmetric distribution
is {symmetric_value:.3f}")

The other shape measurement covered in this section is kurtosis.

Kurtosis is a measurement of how heavy or light the tail of a distribution is relative to the normal distribution [2]. While the normal distribution has not been covered in depth yet, the idea of kurtosis can still be discussed. A light-tailed distribution means that more of the data is near or around the mode of the distribution. In contrast, a heavy-tailed distribution means that more of the data is at the edges of the distribution than near the mode. A light-tailed distribution, a normal distribution, and a heavy-tailed distribution are shown in Figure 2*.14*.

Figure 2.14 – Distributions demonstrating tailedness with reference to a normal distribution

The formula for kurtosis will not be shown here since it can be calculated trivially with modern software packages. If the kurtosis value is 0 or near 0, the distribution does not exhibit kurtosis. If the kurtosis value is negative, the distribution exhibits light-tailedness, and if the kurtosis value is positive, the distribution exhibits heavy-tailedness. An example of how to calculate kurtosis with scipy is shown in the following code example:

from scipy.stats import norm
from scipy.stats import gennorm
from scipy.stats import kurtosis
# generate data
light_tailed = gennorm.rvs(5, size=3000)
symmetric = norm.rvs(10, size=3000)
heavy_tailed = gennorm.rvs(1, size=3000)
# calculate skewness
light_tailed_value = kurtosis(light_tailed)
heavy_tailed_value = kurtosis(heavy_tailed)
symmetric_value = kurtosis(symmetric)
# Output may vary some due to randomness of generated data
print(f"The kurtosis value of this light-tailed
distribution is {light_tailed_value:.3f}")
print(f"The kurtosis value of this heavy_tailed
distribution is {heavy_tailed_value:.3f}")
print(f"The kurtosis value of this normal
distribution is {symmetric_value:.3f}")

In this section, we walked through the common descriptive statistics that are used for measuring and describing distributions of data. These measurements provide a common language for describing and comparing distributions. The concepts discussed in this chapter are fundamental to many of the concepts discussed in future chapters. In the next section, we will discuss the normal distribution and describe the normal distribution using these measurements.

The normal distribution and central limit theorem

Section titled “The normal distribution and central limit theorem”

When discussing the normal distribution, we refer to the bell-shaped, standard normal distribution, which is formally synonymous with the Gaussian distribution, named after Carl Friedrich Gauss, an 18th- and 19th-century mathematician and physicist who – among other things – contributed to the concepts of approximation, and, in 1795, invented the method of least squares and the normal distribution, which is commonly used in statistical modeling techniques, such as least squares regression [3]. The standard normal distribution, also referred to as a parametric distribution, is characterized by a symmetrical distribution with a probability of data point dispersion consistent around the mean – that is, the data appears near the mean more frequently than data farther away. Since the location data dispersed within this distribution follows the laws of probability, we can call this a standard normal probability distribution. As an aside, a distribution in statistics that is not a probability distribution is generated through non-probability sampling based on non-random selection, whereas a probability distribution is based on random sampling. Both probability-based and non-probability-based distributions can have a standard normal distribution. The standard normal distribution exhibits neither skew nor kurtosis. It has equal variance throughout and frequently occurs in nature. The Empirical Rule is used to describe this distribution as having three pertinent standard deviations centered around the mean, μ. There are two distinct assumptions about this distribution:

  • The first, second, and third standard deviations contain 68%, 95%, and 99.7% of the measurements dispersed, respectively
  • The mean, median, and mode are all equal to each other

Figure 2.15 – The standard normal distribution

Two common forms of a normal distribution are as follows:

  • The probability density distribution
  • The cumulative density distribution

As mentioned before, the probability density distribution is based on random sampling, whereas the cumulative density distribution is based on accumulated data, which is not necessarily random.

The two-tailed probability density function of the standard normal distribution is this:

The left-tailed cumulative function of the standard normal distribution is this:

With respect to statistical modeling, the normal distribution represents balance and symmetry. This is important when building statistical models as many models assume normal distribution and are not robust to many deviations from that assumption, as they are built around a mean. Consequently, if variables in such a model are not normally distributed, the model’s errors will be increased and inconsistent, thus diminishing the model’s stability. When considering multiple variables in a statistical model, their interaction is more easily approximated when both are normally distributed.

In the following Figure 2*.16*, in the left plot, variables X and Y interact with each other and create a centralized dispersion around a mean. In this case, modeling Y using X with a mean line or linear distance can be done reasonably well. However, if the two variables’ distributions were skewed, as in the plot on the right, this would result in non-constant variance between the two, resulting in an unequal distribution of errors and unreliable output.

Figure 2.16 – Bivariate normal (left) and skewed (right) distributions

In the case of linear classification and regression models, this will mean some results are better than others while some will likely be very bad. This can be difficult to assess at times using basic model metrics and requires deeper model analysis to prevent trusting what could end up being misleading results. Furthermore, deployment into a production environment would be very risky. More on this will be discussed in Chapter 6.

When sampling data, it is common to encounter the issue of non-normal data. This may be for multiple reasons, such as the population not having a normal distribution or the sample being misrepresentative of the population. The Central Limit Theorem, which is important in statistical inference, postulates that if random samples of n observations are taken from a population that has a specific mean, μ, and standard deviation, σ, the sampling distribution constructed from the means of the randomly selected sub-sample distributions will approximate a normal distribution having roughly the same mean, μ, and standard deviation, calculated as, as the population. The next section will use bootstrapping to demonstrate the Central Limit Theorem in action. A later section discussing transformations will provide techniques for reshaping data distributions that do not conform to normal distributions so that tools requiring normal distributions can still be effectively applied.

Bootstrapping is a method of resampling that uses random sampling – typically with replacement – to generate statistical estimates about a population by resampling from subsets of the sampled distribution, such as the following:

  • Confidence intervals
  • Standard error
  • Correlation coefficients (Pearson’s correlation)

The idea is that repeatedly sampling different random subsets of a sample distribution and taking the average each time, given enough repeats, will begin to approximate the true population using each subsample’s average. This follows directly the concept of the Central Limit Theorem, which to be restated, asserts that sampling means begins to approximate normal sampling distributions, centered around the original distribution’s mean, as sample sizes and counts increase. Bootstrapping is useful when a limited quantity of samples exists in a distribution relative to the amount needed for a specific test, but inference is needed.

As discussed in Chapter 1, Sampling and Generalization, constraints such as time and expense are common reasons for obtaining samples rather than populations. Because the underlying concept of bootstrapping is to make assumptions about the population using samples, it is not beneficial to apply this technique to populations as the true statistical parameters – such as the percentiles and variance – of a population are known. Regarding sample preparation, the balance of attributes in the sample should represent the true approximation of the population. Otherwise, the results will likely be misleading. For example, if the population of species within a zoo is a split of 40% reptiles and 60% mammals and we want to bootstrap their longevity to identify the confidence intervals for their lifespans, it would be necessary to ensure the dataset to which bootstrapping was applied contained a split of 40% reptiles and 60% mammals; a split of 15% reptiles and 85% mammals, for example, would lead to misleading results. In other words, the sample stratification should be balanced in proportion to the population.

As mentioned before, one useful application of bootstrapping is to create confidence intervals around sparsely defined or limited datasets – that is to say, datasets with a wide range of values without many samples. Consider an example of bootstrapping to perform a hypothesis test using a 95% confidence interval using the "Duncan" dataset in statsmodels, which contains incomes by profession, type, education, and prestige. While this is the full dataset, consider this dataset a sample since the sampling method is not mentioned and it is not likely to consider all incomes for all workers of every profession and type. To obtain the dataset, we first load the matplotlib, statsmodels, pandas, and numpy libraries. We then download the dataset and store it as a pandas DataFrame in the df_duncan variable. Following this, we recode the “ prof", "wc", and "bc" types as "professional", "white-collar", and "blue collar", respectively. Finally, we create two separate pandas DataFrames; one for professional job types and another for blue-collar job types, as these are the two subsets we will analyze using bootstrapping:

import matplotlib.pyplot as plt, statsmodels.api as sm, pandas as pd, numpy as np, scipy.stats
df_duncan = sm.datasets.get_rdataset("Duncan",
"carData").data
df_duncan.loc[df_duncan['type'] == 'prof',
'type'] = 'professional'
df_duncan.loc[df_duncan['type'] == 'wc',
'type'] = 'white-collar'
df_duncan.loc[df_duncan['type'] == 'bc',
'type'] = 'blue-collar'
df_professional = df_duncan.loc[(
df_duncan['type'] == 'professional')]
df_blue_collar = df_duncan.loc[(
df_duncan['type'] == 'blue-collar')]

Figure 2.17 – Table displaying the first five rows of the statsmodels Duncan data

We then build a set of plotting functions, as seen next. In plot_distributions(), we denote p=5, meaning the p-value will be significant at a significance level of 0.05 (1.00 - 0.05 = 0.95, hence, 95% confidence). We then divide this value by 2 since this will be a two-sided test, meaning we want to know the full interval rather than just one bound (discussed in Chapter 1 as a representative test statistic). Regarding the plots, we visualize the data using histograms (the hist() function) in matplotlib and then plot the 95% sampling confidence intervals using the axvline() functions, which we build using the numpy function percentile().

Percentile in Bootstrapping

When applied to the original data, the percentile is only that, but when applied to the bootstrapped sampling distribution, it is the confidence interval.

To state the confidence interval simply, a 95% confidence interval means that for every 100 sample means taken, 95 of them will fall within this interval. In the numpy percentile() function, we use p=5 to support that 1-p is the confidence level, where p is the level of significance (think p-value, where any value at or lower than p is significant). Since the test is two-tailed, we divide p by 2 and split 2.5 in the left tail and 2.5 in the right since we have a symmetrical, standard normal distribution. The subplot(2,1,...) code creates two rows and one column. Axis 0 of the figure is used for professional incomes and axis 1 is used for blue-collar incomes:

def plot_distributions(n_replicas, professional_sample, blue_collar_sample, professional_label, blue_collar_label, p=5):
fig, ax = plt.subplots(2, 1, figsize=(10,8))
ax[0].hist(professional_sample, alpha=.3, bins=20)
ax[0].axvline(professional_sample.mean(),
color='black', linewidth=5)
# sampling distribution mean
ax[0].axvline(np.percentile(professional_sample, p/2.),
color='red', linewidth=3, alpha=0.99)
# 95% CI Lower limit (if bootstrapping)
ax[0].axvline(np.percentile(professional_sample,
100-p/2.), color='red', linewidth=3, alpha=0.99)
# 95% CI Upper Limit (if bootstrapping)
ax[0].title.set_text(str(professional_label) +
"\nn = {} Resamples".format(n_replicas))
ax[1].hist(blue_collar_sample, alpha=.3, bins=20)
ax[1].axvline(blue_collar_sample.mean(), color='black',
linewidth=5) # sampling distribution mean
ax[1].axvline(np.percentile(blue_collar_sample, p/2.),
color='red', linewidth=3, alpha=0.99)
# 95% CI Lower limit (if bootstrapping)
ax[1].axvline(np.percentile(blue_collar_sample,
100-p/2.), color='red', linewidth=3, alpha=0.99)
# 95% CI Upper Limit (if bootstrapping)
ax[1].title.set_text(str(blue_collar_label) +
"\nn = {} Resamples".format(n_replicas))
if n_replicas > 1:
print("Lower confidence interval limit: ",
np.percentile(round(professional_sample,4),
p/2.))
print("Upper confidence interval limit: ",
np.percentile(round(professional_sample,4),
100-p/2.))
print("Mean: ", round(professional_sample,
4).mean())
print("Standard Error: ",
round(professional_sample.std() /
np.sqrt(n_replicas), 4) )
print("Lower confidence interval limit: ",
np.percentile(round(blue_collar_sample,4),
p/2.))
print("Upper confidence interval limit: ",
np.percentile(round(blue_collar_sample,4),
100-p/2.))
print("Mean: ", round(blue_collar_sample,4).mean())
print("Standard Error: ",
round(blue_collar_sample.std() /
np.sqrt(n_replicas), 4) )
else:
print("At least two samples required to create the following statistics:\nConfidence Intervals\nMean\nStandard Error")

In the original dataset, there are 18 income data points for professional job types and 21 data points for blue-collar job types. The 95% confidence interval for the professional job type ranges from 29.50 to 79.15 with an average of 60.06. That interval ranges from 7.00 to 64.00 for blue-collar job types with a mean of 23.76. Based on Figure 2*.18*, there is a reasonable overlap between the income differences, which causes the overlapping confidence intervals. Consequently, it would be reasonable to assume there is no statistically significant difference in incomes between blue-collar and professional job types. However, this dataset has a very limited volume of samples:

n_replicas=0
plot_distributions(n_replicas=n_replicas,
professional_sample=df_professional['income'],
blue_collar_sample=df_blue_collar['income'],
professional_label="Professional",
blue_collar_label="Blue Collar")

Figure 2.18 – Original data distributions with 95th percentile lines

In the following code, using pandas ’ .sample() function, we randomly resample 50% (frac=0.5) of the income values from each distribution 1,000 times and calculate a new mean each time, appending it to the Python lists ending with _bootstrap_means. Using those lists, we derive new 95% confidence intervals. Figure 2*.19* shows, with respect to the standard deviations and income values in the dataset, the new sample distributions using the average of each resampled subset. The replace=True argument allows for resampling the same record multiple times (in the event that should randomly occur), which is a requirement of bootstrapping.

After performing the bootstrapping procedure, we can see income has started to distribute in a roughly standard normal, Gaussian form. Notably, from this experiment, the confidence intervals no longer overlap. The implication of the separation of the confidence intervals between the professional and blue-collar groups is that with a 95% level of confidence, it can be shown there is a statistically significant difference between the incomes of the two job types. The confidence interval for the professional income levels is now 48.66 to 69.89 with a mean of 60.04, and for blue-collar, 14.60 to 35.90 with a mean of 23.69:

n_replicas = 1000
professional_bootstrap_means = pd.Series(
[df_professional.sample(frac=0.5, replace=True)
['income'].mean() for i in range(n_replicas)])
blue_collar_bootstrap_means = pd.Series(
[df_blue_collar.sample(frac=0.5, replace=True)
['income'].mean() for i in range(n_replicas)])

Figure 2.19 – Distributions of the 95% confidence interval for 1,000 bootstrapped sampling means

Here, you can notice the distribution more closely clusters around the mean with tighter confidence intervals.

As mentioned before, bootstrapping can be used to obtain different statistical parameters of the distribution beyond the confidence intervals.

Another commonly used metric is the standard error,. We can calculate this using the last variables, p rofessional_bootstrap_means, and blue_collar_bootstrap_means, as these contain the new distributions of means obtained through the bootstrapping process. We can also see that standard error – calculated by dividing the standard deviation by the square root of the number of samples (or in our case, n_replicas, representing the count of averages obtained from each random re-subsample) – decreases as the volume resamples increases. We use the following code to calculate the standard error of the professional and blue-collar type income bootstrapped means. The following table, Figure 2*.20*, shows that the standard error reduces as n increases:

scipy.stats.sem(professional_bootstrap_means)
scipy.stats.sem(blue_collar_bootstrap_means)
nProfessional Standard ErrorBlue-Collar Standard Error
10 replicas0.932.09
10,000 replicas0.030.04

Figure 2.20 – Table of standard errors for n = 10 and n = 10,000 bootstrap replicas

Another use case for bootstrapping is Pearson’s correlation, which we will discuss in the following section.

Correlation coefficients (Pearson’s correlation)

Section titled “Correlation coefficients (Pearson’s correlation)”

Typically, this is difficult to find using a small sample size since correlation depends on the covariance of two variables. As the variables overlap more significantly, their correlation is higher. However, if the overlap is the result of a small sample size or sampling error, this correlation may be representative. Figure 2*.21* shows a table of correlation at different counts of bootstrap subsamples. As the distributions form more native distinctions, the correlation diminishes from a small positive correlation to an amount approximating zero.

To test correlation on a sample of 10 records from the original dataset, see the following:

df_prof_corr = df_professional.sample(n=10)
df_blue_corr = df_blue_collar.sample(n=10)
corr, _ = scipy.stats.pearsonr(df_prof_corr['income'],
df_blue_corr['income'])

To test correlation on samples of bootstrapped means:

n_replicas = n_replicas
professional_bootstrap_means = pd.Series([df_prof_corr.sample(frac=0.5,replace=False).income.mean()for i in range(n_replicas)])
blue_collar_bootstrap_means = pd.Series([df_blue_corr.sample(frac=0.5, replace=False).income.mean() for i in range(n_replicas)])
corr, _ = scipy.stats.pearsonr(
professional_bootstrap_means,
blue_collar_bootstrap_means)
print(corr)
nPearson’s Correlation Coefficient
10 samples from original data0.32
10 replicas0.22
10,000 replicas-0.003

Figure 2.21 – Table of Pearson’s correlation coefficients alongside the original samples

It is common to run around 1,000 to 10,000 bootstrap replicas. However, this depends on the type of data being bootstrapped. For example, if bootstrapping data from a human genome sequence dataset, it may be useful to bootstrap a sample 10 million times, but if bootstrapping a simple dataset, it may be useful to bootstrap 1,000 times or less. Ultimately, the researcher should perform a visual inspection of the distributions of the means to determine whether the results appear logical compared to what is expected. As common with statistics, it is best to have some domain knowledge or subject-matter expertise to help validate findings, as this will likely be the best for deciding bootstrap replication counts.

Bootstrapping is also used in machine learning, where it underlies the concept of bootstrap aggregation, also called bagging, a process that combines outputs of predictive models built upon bootstrap subsample distributions. Random Forest is one popular algorithm that performs this operation. The purpose of bootstrapping in bagging algorithms is to preserve the low-bias behavior of non-parametric (more to be discussed on this in later chapters) classification, but also reduce variance, thus using bootstrapping as a way to minimize the significance of the bias-variance trade-off in modeling errors.

In the following section, we will consider another non-parametric test called permutation testing using resampling data.

Before jumping into this testing analysis, we will review some basic knowledge of permutations and combinations.

Permutations and combinations are two mathematical techniques for taking a set of objects to create subsets from a population but in two different ways. The order of objects matters in permutations but does not matter in combinations.

In order to understand these concepts easily, we will consider two examples. There are 10 people at an evening party. The organizer of the party wants to give 3 prizes of 1,000,1,000, 500, and 200randomlyto3people.Thequestionis∗howmanywaysaretheretodistributetheprizes?∗Anotherexampleisthattheorganizerwillgive3equalprizesof200 randomly to 3 people. The question is *how many ways are there to distribute the prizes?* Another example is that the organizer will give 3 equal prizes of 500 to 3 people out of 10 at the party. The organizer really does not care which prize is given to whom among the 3 selected people. Huy, Paul, and Stuart are our winners in these two examples but, in the first example, different situations may play out, for instance, if Paul wins the 200prize,200 prize, 500 prize, or $1,000 prize.

$ 1,000$ 500$ 200
HuyPaulStuart
PaulHuyStuart
PaulStuartHuy
HuyStuartPaul
StuartHuyPaul
StuartPaulHuy

Figure 2.22 – Table of distributed prizes given to Huy, Paul, and Stuart

However, in the second example, because the 3 prizes have the same value of $500, the order of prize arrangements does not matter.

Let us take a closer look at these two permutations and combinations examples. The first example is a permutation example. Since the pool has 10 people, we have 10 possibilities in choosing one person from the pool to give the 1,000prize.Ifthispersonischosentowinthe1,000 prize. If this person is chosen to win the 1,000 prize, then there are only 9 possibilities in choosing another person to give the 500prize,andfinally,wehave8possibilitiesinchoosingapersonfromthepooltogivethe500 prize, and finally, we have 8 possibilities in choosing a person from the pool to give the 200 prize. Then, we have 10*9*8 = 720 ways to distribute the prizes. The mathematical formula for the permutations is this:

Here, is the number of permutations, is the total number of objects in a set, and is the number of objects that can be chosen from the set. In this example, and so then we see this:

There are 720 ways to select 3 people from the 10 people at the party to whom to distribute the 3 prizes of 1,000,1,000, 500, and $200.

In Python, there is a package called itertools to help us to find permutations directly. Readers can check out the following link – https://docs.python.org/3/library/itertools.html – for more information related to this package. We need to import this package into the Python environment for permutations:

from itertools import permutations
# list of 10 people in the party
people = ['P1','P2','P3','P4','P5','P6','P7','P8','P9','P10']
# all the ways that the 3 prizes are distributed
perm = permutations(people, 3)
list_perm = list(perm)
print(f"There are {len(list_perm)} ways to distribute the prizes!")

In the preceding Python code, we created a list, people, containing 10 people, P1 to P10, and then use the permutations function from itertools to get all the ways to distribute the prizes. This method takes a list of 10 people as input and returns an object list of tuples containing all the possibilities in choosing 3 people from this pool of 10 people to whom to distribute the prizes of 1,000,1,000, 500, and $200. Because there are 720 ways to distribute the prizes, here we will just print the 10 first ways that the Python code produced:

print(f"The 10 first ways to distribute the prizes: \n
{list_perm[:10]} ")

The output of the preceding code is the 10 first ways to distribute the prizes:

[('P1', 'P2', 'P3'), ('P1', 'P2', 'P4'), ('P1', 'P2', 'P5'), ('P1', 'P2', 'P6'), ('P1', ' P2', 'P7')]

If we have 10 different gifts, each person who participates in the party can take one gift home. How many ways are there to distribute these gifts? There are 3,628,800 ways. That is a really big number! The reader can check with the following code:

#list of 10 people in the party
people = ['P1','P2','P3','P4','P5','P6','P7','P8','P9','P10']
# all the ways that the 10 different gifts are distributed
perm = permutations(people)
list_perm = list(perm)
print(f"There are {len(list_perm)}
ways to distributed the gifts!")

Going back to the second example, because the 3 prizes have the same value of 500,theorderofthe3selectedpeopledoesnotmatter.Then,ifthe3selectedpeopleareHuy,Paul,andStuart,asin∗Figure2∗∗.22∗,thereare6waystodistributetheprizesinthefirstexample.Then,thereisonly1waytodistributethesameamountof500, the order of the 3 selected people does not matter. Then, if the 3 selected people are Huy, Paul, and Stuart, as in *Figure 2**.22*, there are 6 ways to distribute the prizes in the first example. Then, there is only 1 way to distribute the same amount of 500 to Huy, Paul, and Stuart. The mathematical formula of combinations is this:

Here, is the number of combinations, is the total number of objects in a set, and is the number of objects that can be chosen from the set. Similarly, we can calculate that there are

ways to distribute 3 prizes of $500.

In Python, we also use the itertools package but, instead of the permutations function, we import the combinations function:

from itertools import combinations
# list of 10 people in the party
people = ['P1','P2','P3','P4','P5','P6','P7','P8','P9','P10']
# all the ways that the 3 prizes are distributed
comb = combinations(people, 3)
list_comb = list(comb)
print(f"There are {len(list_comb)} ways to distribute the prizes!")

Permutation testing is a non-parametric test that does not make the required assumption of normally distributed data. Both bootstrapping and permutations are useful for resampling techniques but best for different uses, one for estimating statistical parameters (bootstrapping) and another for hypothesis testing. Permutation testing is used to test the null hypothesis between two samples generated from the same population. It has different names such as exact testing, randomization testing, and re-randomization testing.

First, we go to see a simple example for better understanding before implementing the code in Python. We suppose that there are 2 groups of people, one group representing children (A) and another group representing people over 40 years old (B) as follows:

A = [3,5,4] and B = [43,41,56,78,54]

The mean difference in age between the two samples A and B is

We merge A and B into a single set, denoted as P as follows:

P =

Then, we take a permutation of P, for example, the following:

P_new = [3,54, 78, 41, 4, 43, ``5, 56]

Next, we redivide P_new into 2 subsets called A_new and B_new, which have the same size as A and B, respectively:

A_new = [3,54,78] and B_new = [41,4,43,5,56]

Then, the mean difference in age between A_new and B_new is 15.2, which is lower than the original mean difference in age between A and B (50.4). In other words, the permutated P_new does not contribute to the p-value. We can observe that only one permutation drawn from all possible permutations of P is greater than or equal to the original mean difference itself, P. Now we will implement the code in Python:

import numpy as np
# create permutation testing function
def permutation_testing(A,B,n_iter=1000):
#A, B are 2 lists of samples to test the hypothesis,
#n_iter is number of iterations with the default is 1000
differences = []
P = np.array(A+B)
original_mean = np.array(A).mean()- np.array(B).mean()
for i in range(n_iter):
np.random.shuffle(P)#create a random permutation of P
A_new = P[:len(A)] # having the same size of A
B_new = P[-len(B):] # having the same size of B
differences.append(A_new.mean()-B_new.mean())
#Calculate p_value
p_value = round(1-(float(len(np.where(
differences<=original_mean)[0]))/float(n_iter)),2)
return p_value

In the preceding Python code, A and B are two samples and we want to know whether they are from the same larger population; n_ter is the number of iterations that we want to perform; here, 1,000 is the default number of iterations.

Let’s perform permutation testing for the two groups of people in the example with 10,000 iterations:

A = [3,5,4]
B = [43,41,56,78,54]
permutation_testing(A,B,n_iter=10000)

The p-value obtained is 0.98. That means that we fail to reject the null hypothesis, or there is not enough evidence to confirm that samples A and B are from the same larger population.

Next, we will explore an important and necessary step in many statistical tests requiring the normal distribution assumption.

In this section, we will consider three transformations:

  • Log transformation
  • Square root transformation
  • Cube root transformation

First, we will import the numpy package to create a random sample drawn from a Beta distribution. The documentation on Beta distributions can be found here:

https://numpy.org/doc/stable/reference/random/generated/numpy.random.beta.html

The sample, df, has 10,000 values. We also use matplotlib.pyplot to create different histogram plots. Second, we transform the original data by using a log transformation, square root transformation, and cube root transformation, and we draw four histograms:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42) # for reproducible purpose
# create a random data
df = np.random.beta(a=1, b=10, size = 10000)
df_log = np.log(df) #log transformation
df_sqrt = np.sqrt(df) # Square Root transformation
df_cbrt = np.cbrt(df) # Cube Root transformation
plt.figure(figsize = (10,10))
plt.subplot(2,2,1)
plt.hist(df)
plt.title("Original Data")
plt.subplot(2,2,2)
plt.hist(df_log)
plt.title("Log Transformation")
plt.subplot(2,2,3)
plt.hist(df_sqrt)
plt.title("Square Root Transformation")
plt.subplot(2,2,4)
plt.hist(df_cbrt)
plt.title("Cube Root Transformation")
plt.show()

The following is the output of the code:

Figure 2.23 – Histograms of the original and transformed data

Using transformation, we can see the transformed histograms are more normally distributed than the original one. It seems that the best transformation in this example is cube root transformation. With real-world data, it is important to determine whether a transformation is needed, and, if so, which transformation should be used.

Other data transformation methods, for example, finding duplicate data, dealing with missing values, and feature scaling will be discussed in hands-on, real-world use cases in Python in the following chapters.

In the first section of this chapter, we learned about types of data and how to visualize these types of data. Then, we covered how to describe and measure attributes of data distribution. We learned about the standard normal distribution, why it’s important, and how the central limit theorem is applied in practice by demonstrating bootstrapping. We also learned how bootstrapping can make use of non-normally distributed data to test hypotheses using confidence intervals. Next, we covered mathematical knowledge as permutations and combinations and introduced permutation testing as another non-parametric test in addition to bootstrapping. We finished the chapter with different data transformation methods that are useful in many situations when performing statistical tests requiring normally distributed data.

In the next chapter, we will take a detailed look at hypothesis testing and discuss how to draw statistical conclusions from the results of the tests. We will also look at errors that can occur in statistical tests and how to select statistical power.