Statistics Fundamentals
Before learning various cool algorithms, we need to first lay a crucial foundation —statistics。
We can think of statistics as machine learning'sLanguageandToolbox, without which machine learning models would be like explorers without a map, unable to understand data, make predictions, or evaluate their own performance.
This article systematically introduces the core statistical concepts essential for machine learning, using plain language and vivid examples to help you build a solid theoretical foundation.
Why does machine learning need statistics?
Core reason: Machine learning is essentiallylearning patterns from dataand using these patterns to makePredictorDecisionabout unknown situations. And statistics is precisely the science of how to collect, analyze, interpret, and present data.
- Data Understanding: Statistics helps us describe the basic characteristics of data (such as average height, income distribution), which is the first step in data cleaning and exploration.
- Pattern mining: It provides methods to infer general patterns (models) from data and tells us how reliable these patterns are.
- Prediction and evaluation: Statistical theory underpins how we use models to make predictions and how to objectively evaluate whether a model is good or bad (is it guessing or truly understanding?).
- Uncertainty quantification: The real world is full of noise; statistics enables us to measure uncertainty in predictions (e.g., "I am 95% confident it will rain tomorrow").
Simply put,Statistics is the theoretical cornerstone of machine learning, turning intelligence from mysticism into science.
Core concept 1: Descriptive statistics
Descriptive statistics is like taking a snapshot and a health check report of data, using a few key metrics to summarize the whole picture of a dataset. This is the starting point of any data analysis project.
1. Central tendency: Where does the data cluster?
These metrics tell us where the center or typical value of the data lies.
| Pointer | Explanation (analogy) | Calculation formula (brief) | Features and uses |
|---|---|---|---|
| Mean | The arithmetic mean of all the data. | ||
| Like "average wage". | 总和 / 数据个数 |
Most commonly used, but it is very sensitive to extreme values (such as billionaires) and can be easily "averaged". | |
| Median | After sorting the data from smallest to largest,the middlevalue. | ||
| Like "median wage". | The value at the middle position after sorting. | Robust, unaffected by extreme values, better reflecting the typical situation. | |
| Mode | The value that appearsthe most number of timesvalue. | ||
| Like the best-selling shoe size in a shop. | The value with the highest frequency of occurrence. | Suitable for categorical data, or for finding the most common category. |
Example: The monthly salaries (in thousands) of 5 employees in a department are:[30, 35, 40, 45, 200](The boss is among them).
- Mean = (30+35+40+45+200)/5 = 70. This value is inflated by the boss's 200 and cannot represent the employees' income.
- Median = the third number after sorting 40. This value better represents the income of a "typical" employee in this department.
- Mode = all values appear only once, sothere is no mode。
2. Dispersion: How spread out is the data?
Knowing the center alone is not enough; we also need to know whether the data is tightly clustered around the center or scattered all over. Dispersion measures the variability or diversity of the data.
| Pointer | Explanation (analogy) | Calculation formula (brief) | Features and uses |
|---|---|---|---|
| Variance | The distance of each data point from the mean,squared,averaged — this is the variance. | Σ(每个值 - 均值)² / (n-1) |
It measures overall dispersion, and its unit is the square of the original unit. |
| Standard deviation | The positive square root of the variance。 | ||
| is like the "average fluctuation magnitude". | √方差 |
Most commonly used, with the same unit as the original data, intuitively reflecting the size of the fluctuation. The larger the value, the more dispersed the data. | |
| Range | The difference between the maximum and minimum values. | ||
| "salary span". | 最大值 - 最小值 |
Simple to compute, but determined only by the two extreme values, so it is easily affected by outliers. |
Continuing the example: calculate the standard deviation of employee salaries (using 40 as an estimated mean is more reasonable).
- Calculate the variance:
[(30-40)² + (35-40)² + (40-40)² + (45-40)² + (200-40)²] / 4 ≈ 5875 - Standard deviation =
√5875 ≈ 76.65. This huge standard deviation (76.65) is far greater than the mean (40),strongly suggesting the presence of an extreme outlier in the data (the boss's 200), which requires further analysis.
3. Data Distribution and Visualization
Numerical metrics are abstract, while charts let us intuitively "see" the data.
- Histogram: shows the frequency distribution of data across different intervals (bins). It reveals whether the data is unimodal or multimodal, and whether it is symmetric.
- Boxplot: uses a "box" and "whiskers" to display the data'sminimum, first quartile (Q1), median (Q2), third quartile (Q3), and maximum, and is a powerful tool for identifyingOutliersoutliers.
Example
Python example: using matplotlib and seaborn to draw a box plot that identifies outliers
import
matplotlib.
pyplot
as
plt
import
seaborn
as
sns
import
numpy
as
np
Employee salary data, containing an outlier
salaries
=
np.
array
(
[
30
,
35
,
40
,
45
,
200
]
)
employee_names
=
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Diana'
,
'Boss'
]
plt.
figure
(
figsize
=
(
8
,
5
)
)
Create a box plot
sns.
boxplot
(
y
=
salaries
)
plt.
title
(
'Department Salary Distribution (Boxplot)'
)
plt.
ylabel
(
'Salary (k)'
)
plt.
grid
(
axis
=
'y'
,
linestyle
=
'--'
,
alpha
=
0.7
)
Mark the point corresponding to the outlier
for
i
,
(
name
,
salary
)
in
enumerate
(
zip
(
employee_names
,
salaries
)
)
:
if
salary
45
1.5
(
45
35
)
:
Simple rule for identifying outliers
plt.
annotate
(
f
'{name}: {salary}'
,
xy
=
(
0
,
salary
)
,
xytext
=
(
0.2
,
salary
)
,
arrowprops
=
dict
(
facecolor
=
'red'
,
shrink
=
0.05
)
)
plt.
show
(
)
Code explanation:
sns.boxplot()Draw the box plot. The box spans from Q1 to Q3, with the middle line being the median.- The "whiskers" of a box plot typically extend to the farthest data point within 1.5 times the interquartile range (IQR = Q3 - Q1); points beyond this are treated asOutliersand marked individually with a dot. In the figure,
200this point is clearly identified as an outlier.
Core Concept 2: Probability and Distributions
If descriptive statistics is about looking at the past, then probability is about predicting the future. It quantifiesthe likelihood that a certain event will occur。
1. Basic Probability
- Probability P(A): the likelihood of event A occurring, ranging from 0 (impossible) to 1 (certain).
- Conditional Probability P(A|B): given that event B has already occurred, the probability that event A occurs. This is key to understanding many machine learning algorithms (such as Naive Bayes).
- Formula:
P(A|B) = P(A 且 B) / P(B)
2. Probability Distributions
Describes the probability law by which a random variable takes various possible values. The most important one in machine learning is:
- Normal Distribution (Gaussian Distribution):
- Shape: the famous "bell curve", symmetric left and right.
- Parameters: determined by the **mean (μ)** for the center position, and the **standard deviation (σ)** for the "fatness/thinness" (dispersion) of the curve.
- Importance: a large number of phenomena in nature and social sciences approximately follow a normal distribution (such as height and measurement error). The central limit theorem states that the sum of multiple independent random variables tends toward a normal distribution, making it the cornerstone of statistical inference.
- 68-95-99.7 Rule: the probabilities that data falls within ±1σ, ±2σ, and ±3σ of the mean are approximately 68%, 95%, and 99.7%, respectively.

Core Concept 3: Inferential Statistics
This is the "upgraded version" of statistics, with the goal of usingSampledata to inferthe population'sproperties. In machine learning, we always train models on finite data (samples), hoping they will perform well in the infinite real world (the population).
1. Central Limit Theorem
Core idea: regardless of the population's distribution, when we draw a large number ofindependentrandom samples from the population and compute each sample's mean,Meanthe distribution of these sample means will approach anormal distribution.。
Significance for Machine Learning: This provides a theoretical basis for using the properties of the normal distribution to perform,on model parameters (such as the mean), hypothesis testingand the construction ofconfidence intervals.Even if we do not know the population's true distribution, we can still perform reliability analysis on estimates obtained from samples.
2. Hypothesis Testing
Used to determine whether a hypothesis about a population (such as "the new drug is ineffective") is supported by the sample data.
- Null Hypothesis (H0): usually represents "no effect" or "no difference" (the default position).
- Alternative Hypothesis (H1): the hypothesis we hope to confirm (such as "the new drug is effective").
- P-value: the probability of observing the current sample data (or more extreme data) under the assumption that the null hypothesis is true.
- How to Decide: if the P-value is very small (usually < 0.05), it means the current situation is extremely unlikely under H0, so we have sufficient evidence toreject H0and accept H1.
- Significance Level (α): the threshold for judging whether the P-value is "small enough", often set at 0.05.
Applications in Machine Learning: used for feature selection, to determine whether there is a statistically significant correlation between a feature and the target variable, rather than a chance association.
3. Correlation and Causation
This is one of the most confusing, yet most important, concepts in data analysis.
- Correlation: measures the tendency of two variablesto change together. It is commonly expressed by the **correlation coefficient (-1 to 1)**.
- 1: perfect positive correlation (increase and decrease together).
- -1: perfect negative correlation (one increases while the other decreases).
- 0: no linear correlation.
- Causation: refers to thechange in one variable (cause) directly causinga change in another variable (effect).
Key distinction:Correlation does not equal causation!
- Classic Fallacy: summer ice cream sales and the number of drowning incidents are highly positively correlated. But this does not mean that eating ice cream causes drowning. Itscommon cause (confounding variable)Ishot weather。
- Implications for Machine Learning: machine learning models (especially predictive models) are good at finding correlations,Correlationbut cannot on their own determine causationCausation. Mistaking strong correlations discovered by a model for causal relationships is a common error in practice. Building causal models requires more rigorous experimental design (such as randomized controlled trials) or special causal inference methods.
Practical Exercise: Basic Statistical Analysis with Python
Let us use Python and the famous pandas、seaborn library to perform simple descriptive and exploratory statistical analysis on a real dataset.
Example
import
pandas
as
pd
import
seaborn
as
sns
import
matplotlib.
pyplot
as
plt
import
numpy
as
np
1. Load the dataset (here we use seaborn's built-in 'tips' dataset)
df
=
sns.
load_dataset
(
'tips'
)
(
"First 5 rows of the dataset:"
)
(
df.
head
(
)
)
(
f
"\nDataset shape: {df.shape}"
)
View the number of rows and columns
(
"\nBasic information:"
)
(
df.
info
(
)
)
(
"\nDescriptive statistics:"
)
(
df.
describe
(
)
)
2. Explore numerical variables: total bill (total_bill) and tip (tip)
(
f
"\nMean of total bill: {df['total_bill'].mean():.2f}"
)
(
f
"Median of total bill: {df['total_bill'].median():.2f}"
)
(
f
"Standard deviation of total bill: {df['total_bill'].std():.2f}"
)
(
f
"Correlation coefficient between tip and total bill: {df['tip'].corr(df['total_bill']):.3f}"
)
3. Visualization
fig
,
axes
=
plt.
subplots
(
2
,
2
,
figsize
=
(
12
,
10
)
)
3.1 Histogram and density estimation of total bill
sns.
histplot
(
df
[
'total_bill'
]
,
kde
=
True
,
ax
=
axes
[
0
,
0
]
)
axes
[
0
,
0
]
.
set_title
(
'Distribution of Total Bill'
)
axes
[
0
,
0
]
.
axvline
(
df
[
'total_bill'
]
.
mean
(
)
,
color
=
'red'
,
linestyle
=
'--'
,
label
=
f
'Mean: {df["total_bill"].mean():.1f}'
)
axes
[
0
,
0
]
.
axvline
(
df
[
'total_bill'
]
.
median
(
)
,
color
=
'green'
,
linestyle
=
'--'
,
label
=
f
'Median: {df["total_bill"].median():.1f}'
)
axes
[
0
,
0
]
.
legend
(
)
3.2 Scatter plot of tip versus total bill (to see the correlation)
sns.
scatterplot
(
data
=
df
,
x
=
'total_bill'
,
y
=
'tip'
,
hue
=
'time'
,
ax
=
axes
[
0
,
1
]
)
axes
[
0
,
1
]
.
set_title
(
'Tip vs Total Bill (Colored by Meal Time)'
)
3.3 Box plot of tips grouped by gender (to compare differences between groups)
sns.
boxplot
(
data
=
df
,
x
=
'sex'
,
y
=
'tip'
,
ax
=
axes
[
1
,
0
]
)
axes
[
1
,
0
]
.
set_title
(
'Tip Amount by Gender'
)
3.4 Bar chart of mean bill by smoking status
bill_by_smoker
=
df.
groupby
(
'smoker'
)
[
'total_bill'
]
.
mean
(
)
.
reset_index
(
)
sns.
barplot
(
data
=
bill_by_smoker
,
x
=
'smoker'
,
y
=
'total_bill'
,
ax
=
axes
[
1
,
1
]
)
axes
[
1
,
1
]
.
set_title
(
'Average Total Bill by Smoking Status'
)
for
index
,
row
in
bill_by_smoker.
iterrows
(
)
:
axes
[
1
,
1
]
.
text
(
index
,
row
[
'total_bill'
]
0.5
,
f
"{row['total_bill']:.1f}"
,
ha
=
'center'
)
plt.
tight_layout
(
)
plt.
show
(
)
Exercise tasks:
Run the Code: run the above code in your Python environment and observe the output and charts.
Interpret the Results:
- From the descriptive statistics table, can you state the approximate range and median of the total bill?
- Are tip and total bill positively or negatively correlated? Can you tell from the scatter plot?
- From the box plot, is there a significant difference in the median tips given by men and women?
formulate hypotheses: based on the "mean bill by smoking status" bar chart, can you propose a null hypothesis that could be used foron model parameters (such as the mean), hypothesis testinghypothesis testing? (For example: H0: there is no difference in the average bill between smokers and non-smokers).