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

Data Understanding

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:

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:

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

print

(

"First 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\n"

"="

50

"\n"

)

3. View overall data information: number of rows, columns, data types, and memory usage

print

(

"Basic information of the dataset:"

)

print

(

df.

info

(

)

)

print

(

"\n"

"="

50

"\n"

)

4. View the shape of the data (how many rows, how many columns)

print

(

f

"Dataset shape: {df.shape}"

)

Output (number of rows, number of columns)

print

(

f

"There are {df.shape[0]} samples and {df.shape[1]} features."

)

Code Analysis:

- The name of each column (`Column`) - The number of non-null values (`Non-Null Count`), allowing you to immediately spot any missing data - Data type (`Dtype`), such as `int64` (integer), `float64` (decimal), `object` (text or mixed type)

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

print

(

"Number of missing values per feature:"

)

print

(

df.

isnull

(

)

.

sum

(

)

)

print

(

"\n"

"="

50

"\n"

)

If there are many missing values, you can calculate the missing ratio

missing_ratio

=

df.

isnull

(

)

.

sum

(

)

/

len

(

df

)

100

print

(

"Missing value ratio per feature (%):"

)

print

(

missing_ratio

)

print

(

"\n"

"="

50

"\n"

)

2. Check the statistical summary of numeric features - can reveal clues to outliers

print

(

"Statistical description of numeric features:"

)

print

(

df.

describe

(

)

)

Code Analysis:

- `count`: Count (can be used to reconfirm missing values) - `mean`: Mean - `std`: Standard deviation (the magnitude of data fluctuation) - `min`: Minimum - `25%`, `50%` (Median), `75%`: Quartiles - `max`: Maximum - **By observing `min` and `max`, 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

print

(

"\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:

- The line in the middle of the box represents the **median**. - The upper and lower boundaries of the box represent the **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 points** are very likely **outliers**! - **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 (petal_length) and petal width (petal_width) are highly correlated (>0.96), which may indicate redundant information.
  • Different iris species are clearly distinguished by petal size, and the scatter plot shows clear clustering.
  • Sepal width (sepal_width) has a distribution that is approximately normal.