Module 2 · Beginner · Before you start: the Python and maths you need

Statistics for machine learning, with Python

Statistics for machine learning: mean, median, standard deviation, distributions, z-scores, outliers and correlation, with NumPy and pandas.

By theprogrammers team · · 8 min read

Before a model learns from data, you have to understand the data yourself. Is a salary of ₹3 crore a mistake or a CEO? Are most houses small, with a few huge ones? Do two features move together? Statistics gives you the tools to answer these questions in a few lines of code.

This lesson covers the statistics you'll use every day in machine learning: averages, spread, distributions, z-scores, outliers and correlation, each with a real example and Python code.

Describing the centre: mean, median and mode

The full lesson is mean, median and mode explained.

Here are the daily delivery times, in minutes, for one week:

import numpy as np

times = np.array([25, 28, 30, 32, 35, 40, 300])

print(times.mean())          # 70.0
print(np.median(times))      # 32.0
  • The mean (average) adds everything and divides by the count: 70 minutes.
  • The median is the middle value when sorted: 32 minutes.
  • The mode is the most common value, mainly useful for categories, such as the most popular city.

Which is right? One delivery took 300 minutes (maybe the bike broke down), and it dragged the mean up to 70, though six of the seven deliveries took 40 minutes or less. The median ignores that outlier. That's why house prices and salaries are usually reported as medians.

ML connection: when filling in missing values, the median is often safer than the mean for skewed data. Comparing the mean and median is also a quick test for skew and outliers.

Describing spread: variance and standard deviation

The full lesson is range, variance and standard deviation explained.

Two classes can have the same average mark but very different spreads. Spread tells you how much values vary.

marks = np.array([60, 70, 80, 90, 100])

print(marks.mean())     # 80.0
print(marks.var())      # 200.0
print(marks.std())      # 14.142...
  • Variance is the average squared distance from the mean: here (400 + 100 + 0 + 100 + 400) / 5 = 200.
  • Standard deviation (std) is the square root of the variance: about 14 marks. It's in the same units as the data, so it's easier to interpret: "marks typically sit about 14 away from the average".
  • The range is max minus min: 40. Simple, but one outlier distorts it.

pandas's std() divides by n − 1 instead of n (the "sample" standard deviation), so it gives slightly different results from NumPy's default. For large datasets the difference is tiny.

Percentiles and the interquartile range

The full lesson is percentiles, quartiles and the IQR.

A percentile says what percentage of values fall below a point. The median is the 50th percentile.

q1, q3 = np.percentile(times, [25, 75])
print(q1, q3)        # 29.0 37.5
iqr = q3 - q1        # 8.5: the spread of the middle half

A common rule flags as an outlier anything more than 1.5 × IQR beyond the quartiles:

upper = q3 + 1.5 * iqr     # 50.25
print(times[times > upper])  # [300]

That's the same rule box plots use to draw their outlier dots. Whether to remove an outlier is a judgement call: a typo should go, but a genuine fraud transaction is exactly what a fraud model needs to see.

Summarising a whole dataset in one line

For a full worked example, see summary statistics in pandas.

pandas does all of this at once:

import pandas as pd

print(pd.Series(times).describe().round(1))
count      7.0
mean      70.0
std      101.5
min       25.0
25%       29.0
50%       32.0
75%       37.5
max      300.0
dtype: float64

df.describe() on a whole DataFrame is usually the first thing to run on a new dataset. See the pandas DataFrame tutorial.

Distributions: the shape of the data

The full lessons are what is a distribution?, the normal distribution explained and the 68-95-99.7 rule.

A distribution describes how often each value occurs. Draw a histogram to see it. A few shapes come up again and again:

  • Normal (bell curve): symmetric around the mean, most values near the middle. Heights, measurement errors and exam marks are often roughly normal. About 68% of values fall within 1 standard deviation of the mean, and about 95% within 2.
  • Right-skewed: a long tail of large values. Incomes, house prices, website visits. The mean sits above the median.
  • Uniform: every value equally likely, like the roll of a fair die.

Here is the 68% and 95% rule for exam marks with a mean of 60 and a standard deviation of 10:

A bell curve of exam marks centred on 60. The darker middle band from 50 to 70 holds 68% of students, and the wider band from 40 to 80 holds 95%, leaving about 2.5% in each tail.

ML connection: many models train better on roughly symmetric features. Taking the logarithm of a right-skewed feature, np.log1p(prices), often pulls in the long tail.

Z-scores and standardisation

The full lesson is z-scores and standardisation.

A z-score says how many standard deviations a value is from the mean:

z = (marks - marks.mean()) / marks.std()
print(z.round(2))    # [-1.41 -0.71  0.    0.71  1.41]

A mark of 100 is 1.41 standard deviations above average. Z-scores let you compare things measured in different units, and values beyond about ±3 are often outliers.

Converting every feature to z-scores is called standardisation, and it's exactly what scikit-learn's StandardScaler does: each feature ends up with mean 0 and standard deviation 1. That stops features measured in big numbers from dominating, as we saw with distances in linear algebra for machine learning.

Correlation: do two features move together?

The full lessons are covariance explained, correlation explained, correlation vs causation, correlation matrix and heatmap in Python and contingency tables.

The correlation coefficient runs from −1 to +1:

  • +1: as one goes up, the other goes up in a perfectly straight line.
  • 0: no straight-line relationship.
  • −1: as one goes up, the other goes down.
hours = [1, 2, 3, 4, 5, 6]
marks = [35, 45, 50, 62, 70, 78]
print(np.corrcoef(hours, marks)[0, 1].round(3))    # 0.997

Study hours and marks are almost perfectly correlated here. In pandas, df.corr() gives the correlation between every pair of columns, often drawn as a heatmap.

ML connections:

  • Features strongly correlated with the target are often useful predictors.
  • Two features strongly correlated with each other carry mostly the same information, which can confuse some models.
  • Correlation only measures straight-line relationships; a perfect U-shape can have a correlation near 0.

Correlation isn't causation

Ice-cream sales and drownings are correlated, but ice cream doesn't cause drowning: hot weather drives both. A model can use correlations to predict, but it can't tell you that changing one thing will cause another to change. That needs controlled experiments.

Samples, populations and bias

The full lesson is population vs sample explained.

You almost never have all the data (the population), only a sample. A model can only be as good as its sample is representative. A loan model trained only on city applicants may fail for rural ones; a face recognition model trained mostly on one skin tone performs worse on others. Asking "who is missing from this data?" is one of the most important statistical questions in ML.

Key takeaways

  • Mean and median describe the centre; the median resists outliers.
  • Standard deviation describes typical spread, in the data's own units.
  • The IQR rule and z-scores help spot outliers; decide case by case whether to remove them.
  • Standardisation (z-scores) puts features on the same scale.
  • Correlation measures straight-line relationships, and isn't causation.
  • Check whether your sample represents the people the model will serve.

Practice

  1. Monthly salaries in a small company, in thousands of rupees, are [30, 32, 35, 38, 40, 45, 400]. Calculate the mean and the median. Which better describes a typical employee?
Show the answer
s = np.array([30, 32, 35, 38, 40, 45, 400])
print(s.mean().round(1), np.median(s))    # 88.6 38.0

The median, ₹38,000. The founder's ₹4 lakh salary pulls the mean far above what anyone else earns.

  1. A student scored 72 in a test where the mean was 60 and the standard deviation 8. What is their z-score, and is it unusual?
Show the answer

z = (72 − 60) / 8 = 1.5. They scored 1.5 standard deviations above average: good, but not extreme. In a normal distribution, roughly 7% of students would score this high or higher.

  1. Use the IQR rule to find outliers in [12, 14, 15, 15, 16, 18, 19, 45].
Show the answer
d = np.array([12, 14, 15, 15, 16, 18, 19, 45])
q1, q3 = np.percentile(d, [25, 75])
iqr = q3 - q1
print(d[(d < q1 - 1.5 * iqr) | (d > q3 + 1.5 * iqr)])    # [45]
  1. A study finds that people who own more books earn more. Can you conclude that buying books raises your income?
Show the answer

No. It's a correlation, not proof of cause. A third factor, such as education level or family background, may drive both. You'd need an experiment to test whether buying books changes income.

Interview questions

When would you use the median instead of the mean?

When the data is skewed or has outliers, such as incomes or house prices, because a few extreme values pull the mean far from typical values while the median stays in the middle.

What is the difference between variance and standard deviation?

Variance is the average of squared deviations from the mean; standard deviation is its square root. Standard deviation is in the same units as the data, which makes it easier to interpret.

What is the difference between standardisation and normalisation?

Standardisation transforms a feature to mean 0 and standard deviation 1 using z-scores (StandardScaler). Normalisation usually means min-max scaling to a fixed range such as 0 to 1 (MinMaxScaler). Standardisation is less affected by outliers squeezing the range.

What does a correlation of 0 mean?

That there's no linear relationship between the two variables. There may still be a strong non-linear relationship, such as a U-shape, so always plot the data too.

What to learn next

  1. Reason about uncertainty with probability for machine learning.
  2. Practise describing real datasets with the pandas DataFrame tutorial.