Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Statistics Fundamentals

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.

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).

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).

  1. Calculate the variance:[(30-40)² + (35-40)² + (40-40)² + (45-40)² + (200-40)²] / 4 ≈ 5875
  2. 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.

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:


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

- Formula: `P(A|B) = P(A and 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:

- **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.

- **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 to **reject H0** and accept H1.

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.

- **1**: perfect positive correlation (increase and decrease together). - **-1**: perfect negative correlation (one increases while the other decreases). - **0**: no linear correlation.

Key distinction:Correlation does not equal causation!


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'

)

print

(

"First 5 rows of the dataset:"

)

print

(

df.

head

(

)

)

print

(

f

"\nDataset shape: {df.shape}"

)

View the number of rows and columns

print

(

"\nBasic information:"

)

print

(

df.

info

(

)

)

print

(

"\nDescriptive statistics:"

)

print

(

df.

describe

(

)

)

2. Explore numerical variables: total bill (total_bill) and tip (tip)

print

(

f

"\nMean of total bill: {df['total_bill'].mean():.2f}"

)

print

(

f

"Median of total bill: {df['total_bill'].median():.2f}"

)

print

(

f

"Standard deviation of total bill: {df['total_bill'].std():.2f}"

)

print

(

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:

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).