Text
stringlengths
1
9.41k
It’s usually among the first things one learns within the field of statistics. The two most widely used descriptive statistics are the mean and the standard deviation.
Given some collection of numeric data, the mean gives us a measure of the central tendency of the data. There are several 275 ----- different ways to calculate the mean of a data set.
Here we will present the arithmetic mean (average).
The standard deviation is a measure of the amount of variation observed in a data set. We’ll also look briefly at quantiles, which provide a different perspective from which to view the spread or variation in a data set. ###### The arithmetic mean Usually, when speaking of the average of a set of data, without furthe...
You probably have some intuitive sense of what this means.
The mean summarizes the data, boiling it down to a single value that’s somehow “in the middle.” Here’s how we define and calculate the arithmetic mean, denoted 𝜇, given some set of values, 𝑋. 𝜇= [1] 𝑁 𝑁−1 ∑ 𝑥𝑖 𝑖= 0 where we have a set of numeric values, 𝑋, indexed by 𝑖, with 𝑁 equal to the number of ...
We can use Python’s csv module to read ``` the data. [1Source: World Health Organization: https://www.who.int/data/gho/data/](https://www.who.int/data/gho/data/indicators/indicator-details/GHO/dentists-(per-10-000-population)) [indicators/indicator-details/GHO/dentists-(per-10-000-population) (retrieved](https://www....
It’s a simple one-liner. ``` def mean(lst): return sum(lst) / len(lst) ``` That’s a complete implementation of the formula: 𝜇= [1] 𝑁 𝑁−1 ∑ 𝑥𝑖 𝑖= 0 We take all the 𝑥𝑖 and add them up (with sum()).
Then we get the number of elements in the set (with len()) and use this as the divisor.
If we print the result with print(f"{mean(data):.4f}") we get 5.1391. That tells us a little about the data set: on average (for the sample of countries included) there are a little over five dentists per 10,000 population.
If everyone were to go to the dentist once a year, that would suggest, on average, that each dentist serves a little less than 2,000 patients per year.
With roughly 2,000 working hours in a year, that seems plausible.
But the mean doesn’t tell us much more than that. To get a better understanding of the data, it’s helpful to understand how values are distributed about the mean. Let’s say we didn’t know anything about the distribution of values about the mean.
It would be reasonable for us to assume these values are normally distributed.
There’s a function which describes the normal _distribution, and you’ve likely seen the so-called “bell curve” before._ **Figure 14.1** ----- On the 𝑥-axis are the values we might measure, and on the 𝑦-axis we have the probability of observing a particular value.
In a normal distribution, the mean is the most likely value for an observation, and the greater the distance from the mean, the less likely a given value.
The _standard deviation tells us how spread out values are about the mean.
If_ the standard deviation is large, we have a broad curve: **Figure 14.2** With a smaller standard deviation, we have a narrow curve with a higher peak. **Figure 14.3** The area under these curves is equal. ----- **Figure 14.4** If we had a standard deviation of zero, that would mean that every value in the da...
The point is that the greater the standard deviation, the greater the variation there is in the data. Just like we can calculate the mean of our data, we can also calculate the standard deviation.
The standard deviation, written 𝜎, is given by √√√ 1 𝑁−1 𝜎= ⎷ 𝑁 𝑖= 0∑(𝑥𝑖 −𝜇)[2]. Let’s unpack this. First, remember the goal of this measure is to tell us how much variation there is in the data.
But variation with respect to what? Look at the expression (𝑥𝑖 −𝜇)[2]. We subtract the mean, 𝜇, from each value in the data set 𝑥𝑖.
This tells us how far the value of a given observation is from the mean. But we care more about the distance from the mean rather than whether a given value is above or below the mean.
That’s where the squaring comes in. When we square a positive number we get a positive number. When we square a negative number we get a positive number.
So by squaring the difference between a given value and the mean, we’re eliminating the sign.
Then, we divide the sum of these squared differences by the number of elements in the data set (just as we do when calculating the mean). Finally, we take the square root of the result.
Why do we do this? Because by squaring the differences, we stretch them, changing the scale. For example, 5 −2 = 3, but 5[2] −2[2] = 25−4 = 21.
So this last step, taking the square root, returns the result to a scale appropriate to the data.
This is how we calculate standard deviation.[2] As we calculate the summation, we perform the calculation (𝑥𝑖 −𝜇)[2]. On this account, we cannot use sum().
Instead, we must calculate this in 2Strictly speaking, this is the population standard deviation, and is used if the data set represents the entire universe of possible observations, rather than just a sample.
There’s a slightly different formula for the sample standard deviation. ----- a loop.
However, this is not too terribly complicated, and implementing this in Python is left as an exercise for the reader. Assuming we have implemented this correctly, in a function named `std_dev(), if we apply this to the data and print with` ``` print(f"{std_dev(data):.4f}"), we get 4.6569. ``` How do we interpret this?
Again, the standard deviation tells us how spread out values are about the mean. Higher values mean that the data are more spread out.
Lower values mean that the data are more closely distributed about the mean. What practical use is the standard deviation?
There are many uses, but it’s commonly used to identify unusual or “unlikely” observations. We can calculate the area of some portion under the normal curve. Using this fact, we know that given a normal distribution, we’d expect to find 68.26% of observations within one standard deviation of the mean. We’d expect 95.45...
Accordingly, the farther from the mean, the less likely an observation.
If we express this distance in standard deviations, we can determine just how likely or unlikely an observation might be (assuming a normal distribution).
For example, an observation that’s more than five standard deviations from the mean would be very unlikely indeed. Range Expected fraction in range 𝜇± 𝜎 68.2689% 𝜇± 2𝜎 95.4500% 𝜇± 3𝜎 99.7300% 𝜇± 4𝜎 99.9937% 𝜇± 5𝜎 99.9999% When we have real-world data, it’s not often perfectly normally distributed.
By comparing our data with what would be expected if it were normally distributed we can learn a great deal. Returning to our dentists example, we can look for possible outliers by iterating through our data and finding any values that are greater than two standard deviations from the mean. ``` m = mean(data) std =...
This might well lead us to ask, “Why are there so many dentists per 10,000 population in these particular countries?” ----- ###### 14.2 Python’s statistics module While implementing standard deviation (either for a sample or for an entire population) is straightforward in Python, we don’t often write functions like...
Why? Because Python provides a statistics module for us. We can use Python’s statistics module just like we do with the math module.
First we import the module, then we have access to all the functions (methods) within the module. Let’s start off using Python’s functions for mean and population standard deviation.
These are statistics.mean() and statistics.pstdev(), and they each take an iterable of numeric values as arguments. ``` import csv import statistics data = [] with open('dentists_per_10k.csv', newline='') as fh: reader = csv.reader(fh) next(reader) # skip the first row for row in reader: data...
For example, if we divide our data set into quartiles (𝑛= 4), then each quartile represents 1/4 of the distribution.
If we divide our data set into quintiles (𝑛= 5), then each quintile represents 1/5 of the distribution.
If we divide our data into percentiles (𝑛= 100), then each percentile represents 1/100 of the distribution. You may have seen quantiles—specifically percentiles—before, since these are often reported for standardized test scores.
If your score was in the 80th percentile, then you did better than 79% of others taking the ----- test.
If your score was in the 95th percentile, then you’re in the top 5% all those who took the test. Let’s use the statistics module to find quintiles for our dentists data (recall that quintiles divide the distribution into five parts). If we import csv and statistics and then read our data (as above), we can calculate th...
Here we also supply a keyword argument, n=5, to indicate we want quintiles.
When we print the result, we get ``` [0.274, 2.2359999999999998, 6.590000000000001, 8.826] ``` Notice we have four values, which divide the data into five equal parts. Any value below 0.274 is in the first quintile.
Values between 0.274 and 0.236 (rounding) are in the second quartile, and so on.
Values above 8.826 are in the fifth quintile. If we check the value for the United States of America (not shown in the table above), we find that the USA has 5.99 dentists per 10,000 population, which puts it squarely in the third quartile.
Countries with more than 8.826 dentists per 10,000—those in the top fifth—are Belgium (11.33), Chile (14.81), Costa Rica (10.58), Israel (8.88), Lithuania (13.1), Norway (9.29), Paraguay (12.81), and Uruguay (16.95).
Of course, interpreting these results is a complex matter, and results are no doubt influenced by per capita income, number and size of accredited dental schools, regulations for licensure and accreditation, and other infrastructure and economic factors.[3] ###### Other functions in the statistics module I encourage ...
If you have a course in which you’re expected to calculate means, standard deviations, and the like, you might consider doing away with your spreadsheet and trying this in Python! ###### 14.3 A brief introduction to plotting with Matplotlib Now that we’ve seen how to read data from a file, and how to generate some de...
For this we will use a third-party[4] module: Matplotlib. 3I’m happy with my dentist here in Vermont, but I will say she’s booking appointments over nine months in advance, so maybe a few more dentists in the USA wouldn’t be such a bad thing. 4i.e, not provided by Python or written by you ----- Matplotlib is a feat...
It is the de facto standard for visual presentation of data in Python (yes, there are some other tools, but they’re not nearly as widely used). Since Matplotlib is not part of the Python core library (like the math, ``` csv, and statistics modules we’ve seen so far), we need to install Mat ``` plotlib before we can use...
Some IDEs (PyCharm, Thonny, VS Code, etc.) have built-in facilities for installing such modules. IDLE (the Python-supplied IDE) does not have such a facility.
Accordingly, we won’t get into the details of installation here (since details will vary from OS to OS, machine to machine), though if you’re the DIY type and aren’t using PyCharm, Thonny, or VS Code, you may find Appendix _C: pip and venv helpful._ Here are some examples of plots made with Matplotlib (from the Matplot...
Why? Because Matplotlib has thousands of features and it has excellent documentation.
So we’re just going to dip a toe in the waters. For more, see: [• Matplotlib website: https://matplotlib.org](https://matplotlib.org) [• Getting started guide: https://matplotlib.org/stable/users/gettin](https://matplotlib.org/stable/users/getting_started) [g_started](https://matplotlib.org/stable/users/getting_start...
To use pyplot we usually import and abbreviate: ``` import matplotlib.pyplot as plt ``` Renaming isn’t required, but it is commonplace (and this is how it’s done in the Matplotlib documentation).
We’ve seen this syntax before—using ``` as to give a name to an object without using the assignment operator ``` (=).
It’s very much like giving a name to a file object when using the with context manager. Here we give matplotlib.pyplot a shorter name plt so we can refer to it easily in our code.
This is almost as if we’d written ``` import matplotlib.pyplot plt = matplotlib.pyplot ``` Almost. Now let’s generate some data to plot.
We’ll generate random numbers in the interval (−1.0, 1.0). ``` import random data = [0] for _ in range(100): data.append(data[-1]) + random.random() * random.choice([-1, 1])) ``` So now we’ve got some random data to plot.
Let’s plot it. ``` plt.plot(data) ``` That’s pretty straightforward, right? Now let’s label our 𝑦 axis. ``` plt.ylabel('Random numbers (cumulative)') ``` Let’s put it all together and display our plot. ``` import random import matplotlib.pyplot as plt data = [0] for _ in range(100): data.append(data...
We call the savefig() method and provide the file name we’d like to use for our plot.
The plot will be saved in the current directory, with the name supplied. ----- ``` import random import matplotlib.pyplot as plt data = [0] for _ in range(100): data.append(data[-1]) + random.random() * random.choice([-1, 1])) plt.plot(data) plt.ylabel('Random numbers (cumulat...
Our first plot—presented and saved to file. Let’s do another. How about a bar chart?
For our bar chart, we’ll use this as data (which is totally made up by the author): Flavor Servings Cookie dough 9,214 Strawberry 3,115 Chocolate 5,982 Vanilla 2,707 Fudge brownie 6,553 Mint chip 7,005 Kale and beet 315 Let’s assume we have this saved in a CSV file called flavors.csv.
We’ll read the data from the CSV file, and produce a simple bar chart. ``` import csv import matplotlib.pyplot as plt servings = [] # data flavors = [] # labels with open('flavors.csv') as fh: reader = csv.reader(fh) for row in reader: flavors.append(row[0]) servings.append(int(row[1])) ...
A bar plot!_ Notice that we have two lists: one holding the servings data, the other holding the 𝑥-axis labels (the flavors).
Instead of plt.plot() we use plt.bar() (makes sense, right?) and we supply flavors and servings as arguments.
There’s a little tweak we give to the 𝑥-axis labels, we rotate them by 45 degrees so they don’t all mash into one another and become illegible.
plt.tight_layout() is used to automatically adjust the padding around the plot itself, leaving suitable space for the bar labels and axis labels. ###### Be aware of how plt.show() behaves When you call plt.show() to display your plot, Matplotlib creates a window and displays the plot in the window.
At this point, your program’s execution will pause until you close the plot window.
When you close the plot window, program flow will resume. ###### Summary Again, this isn’t the place for a complete presentation of all the features of Matplotlib.
The intent is to give you just enough to get started.
Fortunately, the Matplotlib documentation is excellent, and I encourage you to look there first for examples and help. [• https://matplotlib.org](https://matplotlib.org) ----- ###### 14.5 Exceptions ``` StatisticsError ``` The statistics module has its own type of exception, StatisticsError. You may encounter this...
The exception and how to fix it will depend on context.
If you encounter an exception from Matplotlib, your best bet is to consult the Matplotlib documentation. ###### 14.6 Exercises Exercise 01 Try creating your own small data set (one dimension, five to ten elements) and plot it.
Follow the examples given in this chapter. Plot your data as a line plot and as a bar plot. ###### Exercise 02 Matplotlib supports scatter plots too.
In a scatter plot, each data point is a pair of values, 𝑥 and 𝑦.
Here’s what a scatter plot looks like. ----- Create your own data (or find something suitable on the internet) and create your own scatter plot.
𝑥 values should be in one list, corresponding 𝑦 values should be in another list. Both lists should have the exact same number of elements.
If these are called xs and ys, then you can create a scatter plot with ``` plt.scatter(xs, ys) ``` Make sure you display your plot, and save your plot as an image file. ###### Exercise 03 Edwina has calculated the mean and standard deviation of her data set—measurements of quill length in crested porcupines (speci...
She has found that the mean is 31.2 cm and the standard_ deviation is 7.9 cm. a. If one of the quills in her sample is 40.5 cm, should she consider this an unusually long quill? Why or why not? b.
What if there’s a quill that’s 51.2 cm? Should this be considered unusually long? Why or why not? ----- ###### Exercise 04 Consider the two distributions shown, A and B. a.
Which of these has the greater mean? b. Which of these has the greater standard deviation? c. Which of these curves have the greater area under them?
(hint: this is a trick question) ###### Exercise 05 The geometric mean is another kind of mean used in statistics and finance.
Rather than summing all the values in the data and then dividing by the number of values, we take the product of all the values, and then, if there are 𝑁 values, we take the 𝑁 th root of the result.
Typically, this is only used when all values in the data set are positive. We define the geometric mean: 𝛾= ( 𝑁−1 ∏ 𝑥𝑖) 𝑖= 0 1 𝑁 where the ∏ symbol signifies repeated multiplication.
Just as ∑ says “add them all up”, ∏ means “multiply them all together.” We can calculate the 𝑁 th root of a number using exponentiation by a fraction as shown.
For example, to calculate the cube root of some 𝑥, we can use x ** (1 / 3). Implement a function which calculates the geometric mean of an arbitrary list of positive numeric values.
You can verify your result by comparing the output of your function with the output of the statistics module’s geometric_mean() function. ----- ----- #### Chapter 15 ### Exception handling We’ve seen a lot of exceptions so far: - SyntaxError - IndentationError - AttributeError - NameError - TypeError ...
(There are many, many other exceptions that are outside the scope of this textbook.) When an unhandled exception occurs, your program terminates.
This is usually an undesired outcome. Here we will see that some of these exceptions can be handled gracefully using try and except—these go together, hand in hand.
In a try block, we include the code that we think might raise an exception. In the following except block, we catch or handle certain exceptions.
What we do in the except block will depend on the desired behavior for your program. However, we’ll also see that some of these—SyntaxError and ``` IndentationError for example—can’t be handled, since these occur when ``` Python is first reading your code, prior to execution. We’ll also see that some of these exceptio...
These are exceptions like AttributeError and NameError. Trying to handle these covers up defects in our code that we should repair.