Data Understanding
Before starting any machine learning project, such as predicting house prices, recognizing cats and dogs in images, or recommending movies you like, we first need to face the most basic and critical step:Data Understanding。
We can imagine data understanding as the process by which a detective carefully studies all clues and files before investigating a case. If you do not understand the context, authenticity, and meaning of the clues (the data), any subsequent reasoning (modeling) may be built on a faulty foundation.
Data understanding is the cornerstone of the entire machine learning pipeline; it determines how we subsequently clean data and select models, and ultimately affects the success or failure of the model.
What Is Data Understanding?
Data understanding, as the name suggests, means gaining a deep understanding of the dataset at hand. Its core goal is to answer the following questions:
- What data do I have?(The structure and type of the data)
- What is the data quality?(Is the data clean, complete, and reliable?)
- What is the data saying?(What patterns, relationships, and distributions are hidden in the data?)
This process does not involve complex code and algorithms; more often, it gains an understanding of the data through observation, statistics, and visualization.
Core Steps and Tools of Data Understanding
We will use the most popular data analysis library in Python, Pandas and the visualization library Matplotlib/Seaborn for demonstration.
Before starting, please install the following dependency libraries:
pip install pandas matplotlib seaborn
Overview of the Three Major Python Data Analysis Libraries:
- pandas
The core data processing library, specialized in reading/writing, cleaning, filtering, and statistical computation of tabular data; supports Excel/CSV reading and provides the DataFrame tabular structure. - matplotlib
The low-level fundamental plotting library, the foundation of Python visualization; it can draw line charts, bar charts, scatter plots, and other basic chart types, with a high degree of freedom but somewhat verbose code. - seaborn
A high-level plotting library built on matplotlib, designed specifically for statistical charts; it comes with attractive color schemes, and a single line of code can draw distribution plots, heatmaps, and box plots.
Step 1: First Encounter — Loading and Overview
First, we need to load the data into the program and quickly browse its overall appearance.
To begin, we first download the test data into the same directory as the python test code:
Test data download address:https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv
If the githubusercontent network download fails, you can click the link to download directly:https://static.jyshare.com/download/iris.csv。
Example
import
pandas
as
pd
import
matplotlib.
pyplot
as
plt
import
seaborn
as
sns
1. Load the data (here we use the classic Iris dataset as an example; you can also load your own CSV file)
Load from a local file
df
=
pd.
read_csv
(
'iris.csv'
)
Load from the network
url = "https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv"
df = pd.read_csv(url)
2. View the first few rows of data - First Impression
(
"First 5 rows of data:"
)
(
df.
head
(
)
)
(
"\n"
"="
50
"\n"
)
3. View overall data information: number of rows, columns, data types, and memory usage
(
"Basic information of the dataset:"
)
(
df.
info
(
)
)
(
"\n"
"="
50
"\n"
)
4. View the shape of the data (how many rows, how many columns)
(
f
"Dataset shape: {df.shape}"
)
Output (number of rows, number of columns)
(
f
"There are {df.shape[0]} samples and {df.shape[1]} features."
)
Code Analysis:
df.head(): Like flipping through the table of contents of a book, quickly view the first few rows of the data to see what it looks like.df.info(): This is the data's "health check report." It tells you:- The name of each column (
Column) - The number of non-null values (
Non-Null Count), allowing you to immediately spot any missing data - The data type (
Dtype), such asint64(integer),float64(decimal),object(text or mixed type)
df.shape: Directly obtain the dimensions of the data table.
Running the code above produces output similar to the following:
数据的前5行:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
==================================================
Basic information about the dataset:
Step 2: Quality Check — Discovering Missing Values and Anomalies
Data is rarely perfect. Common "data ailments" includeMissing Values(some positions are empty) andOutliers(some numbers are absurdly large or absurdly small).
Example
1. Check for missing values
(
"Number of missing values per feature:"
)
(
df.
isnull
(
)
.
sum
(
)
)
(
"\n"
"="
50
"\n"
)
If there are many missing values, you can calculate the missing ratio
missing_ratio
=
df.
isnull
(
)
.
sum
(
)
/
len
(
df
)
100
(
"Missing value ratio per feature (%):"
)
(
missing_ratio
)
(
"\n"
"="
50
"\n"
)
2. Check the statistical summary of numeric features - can reveal clues to outliers
(
"Statistical description of numeric features:"
)
(
df.
describe
(
)
)
Code Analysis:
df.isnull().sum(): Calculate the total number of null values in each column (NaN).df.describe(): Generate a statistical summary of numeric columns, including:count: Count (can be used to reconfirm missing values)mean: Meanstd: Standard deviation (the magnitude of data fluctuation)min: Minimum25%,50%(Median),75%: Quartilesmax: Maximum- By observing
minandmax, you can preliminarily determine whether there are outliers(for example, an age of 200 appearing in the age column).
Step 3: Deep Insight — Visualization of Distributions and Relationships
Text and numbers are abstract, while charts allow us to intuitively "see" the data. This is the most interesting part of data understanding.
Example
Set the chart style
sns.
set
(
style
=
"whitegrid"
)
1. Univariate Distribution - Understand the distribution of each feature itself
fig
,
axes
=
plt.
subplots
(
2
,
2
,
figsize
=
(
12
,
8
)
)
Create a 2x2 canvas
features
=
[
'sepal_length'
,
'sepal_width'
,
'petal_length'
,
'petal_width'
]
colors
=
[
'skyblue'
,
'lightgreen'
,
'salmon'
,
'gold'
]
for
i
,
(
ax
,
feature
,
color
)
in
enumerate
(
zip
(
axes.
flat
,
features
,
colors
)
)
:
Draw histograms (distribution) and kernel density estimation curves
sns.
histplot
(
df
[
feature
]
,
kde
=
True
,
ax
=
ax
,
color
=
color
,
bins
=
20
)
ax.
set_title
(
f
'Distribution of {feature}'
, fontsize
=
14
)
ax.
set_xlabel
(
feature
)
ax.
set_ylabel
(
'Frequency'
)
plt.
tight_layout
(
)
plt.
show
(
)
2. Box Plots - View Data Distribution and Outliers (More Intuitive)
plt.
figure
(
figsize
=
(
10
,
6
)
)
Select numeric columns to draw box plots
df_box
=
df.
drop
(
columns
=
[
'species'
]
)
Assume 'species' is a text label column; remove it first
sns.
boxplot
(
data
=
df_box
)
plt.
title
(
'Box plots of numeric features (viewing distribution and outliers)'
, fontsize
=
14
)
plt.
xticks
(
rotation
=
45
)
plt.
show
(
)
3. Relationships Between Variables - Scatter Plot Matrix
(
"\nDraw a scatter plot matrix of relationships between features... (this helps us discover associations between features)"
)
Use Seaborn's pairplot; the hue parameter can color points by category (such as iris species)
sns.
pairplot
(
df
,
hue
=
'species'
, height
=
2.5
)
plt.
suptitle
(
'Scatter Plot Matrix of Feature Relationships (Colored by Species)'
, y
=
1.02
,
fontsize
=
16
)
plt.
show
(
)
4. Correlation Heatmap - Quantify Linear Relationships Between Features
plt.
figure
(
figsize
=
(
8
,
6
)
)
Calculate the correlation coefficients between numeric features
numeric_df
=
df.
select_dtypes
(
include
=
[
'float64'
,
'int64'
]
)
correlation_matrix
=
numeric_df.
corr
(
)
sns.
heatmap
(
correlation_matrix
,
annot
=
True
,
cmap
=
'coolwarm'
, center
=
0
,
square
=
True
)
plt.
title
(
'Feature Correlation Heatmap'
, fontsize
=
14
)
plt.
show
(
)
Chart Interpretation:
- Histogram: Shows how the values of a feature (such as petal length) are distributed. Are they concentrated in a certain range, or dispersed?
- Boxplot:
- The line in the middle of the box representsMedian。
- The upper and lower boundaries of the box representthe 25th (Q1) and 75th (Q3) percentiles。
- The "whiskers" extending up and down usually represent the reasonable range (Q1-1.5IQR to Q3+1.5IQR).
- Isolated pointsare very likelyOutliers!
- Scatter plot matrix: View the relationship between any two features simultaneously. A band-like distribution of points suggests a possible correlation.
- Correlation Heatmap: Use colors and numbers (-1 to 1) to precisely represent the degree of linear correlation between two features.
- 1: Perfect positive correlation (as one increases, the other also increases)
- -1: Perfect negative correlation (as one increases, the other decreases)
- 0: No linear relationship
The Output of Data Understanding: A Data Investigation Report
After completing the above steps, you should be able to summarize a clear report about the current dataset, for example:
Investigation Report on the Iris Dataset
Data Overview: A total of 150 samples and 5 features (4 numeric features: sepal/petal length and width; 1 categorical label: species).
Data Quality: No missing values; all numeric features are within reasonable biological ranges, and no obvious outliers were found.
Data Insights:
petal_length) and petal width (petal_width) are highly correlated (>0.96), which may indicate redundant information.sepal_width) has a distribution that is approximately normal.