Common Data Types
This chapter introduces the four most common data types in machine learning: numeric, text, image, and categorical data.
Data types are like the kinds of ingredients; different ingredients require different methods of preparation. Similarly, different types of data require different processing techniques and algorithms.
Classification of the Four Major Data Types

Numeric Data
What Is Numeric Data?
Numeric data is like the result of a measurement with a ruler; it can be used in mathematical operations and is the most common data type in machine learning.
Classification of Numeric Data
1. Continuous Numeric Data
Example
Continuous Numeric Data Example
import
numpy
as
np
import
pandas
as
pd
import
matplotlib.
pyplot
as
plt
def
continuous_data_example
(
)
:
"""Continuous Numeric Data Example"""
(
"=== Continuous Numeric Data Example ==="
)
Generate continuous data
np.
random
.
seed
(
42
)
n_samples
=
1000
Height data (continuous)
heights
=
np.
random
.
normal
(
170
,
10
,
n_samples
)
Mean 170, standard deviation 10
weights
=
heights *
0.7
- np.
random
.
normal
(
0
,
5
,
n_samples
)
Weight correlated with height
temperatures
=
np.
random
.
normal
(
36.5
,
0.5
,
n_samples
)
Body temperature
Create a data frame
continuous_data
=
pd.
DataFrame
(
{
'Height (cm)'
: heights
,
'Weight (kg)'
: weights
,
'Body Temperature (°C)'
: temperatures
,
'Age'
: np.
random
.
randint
(
18
,
65
,
n_samples
)
}
)
(
"Continuous Data Example:"
)
(
continuous_data.
head
(
)
)
(
f
"\nData Statistics:"
)
(
continuous_data.
describe
(
)
)
Visualize the distribution of continuous data
plt.
figure
(
figsize
=
(
12
,
8
)
)
plt.
subplot
(
2
,
2
,
1
)
plt.
hist
(
continuous_data
[
'Height (cm)'
]
,
bins
=
30
,
alpha
=
0.7
,
color
=
'skyblue'
)
plt.
title
(
'Height Distribution'
)
plt.
xlabel
(
'Height (cm)'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
2
)
plt.
hist
(
continuous_data
[
'Weight (kg)'
]
,
bins
=
30
,
alpha
=
0.7
,
color
=
'lightgreen'
)
plt.
title
(
'Weight Distribution'
)
plt.
xlabel
(
'Weight (kg)'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
3
)
plt.
hist
(
continuous_data
[
'Body Temperature (°C)'
]
,
bins
=
30
,
alpha
=
0.7
,
color
=
'salmon'
)
plt.
title
(
'Body Temperature Distribution'
)
plt.
xlabel
(
'Body Temperature (°C)'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
4
)
plt.
scatter
(
continuous_data
[
'Height (cm)'
]
,
continuous_data
[
'Weight (kg)'
]
,
alpha
=
0.6
)
plt.
title
(
'Height vs Weight'
)
plt.
xlabel
(
'Height (cm)'
)
plt.
ylabel
(
'Weight (kg)'
)
plt.
tight_layout
(
)
plt.
show
(
)
return
continuous_data
Running the Example
continuous_df
=
continuous_data_example
(
)
x
. Discrete Numeric Data
Example
Discrete Numeric Data Example
def
discrete_data_example
(
)
:
"""Discrete Numeric Data Example"""
(
"\n=== Discrete Numeric Data Example ==="
)
Generate discrete data
np.
random
.
seed
(
42
)
n_samples
=
500
Discrete data
customer_count
=
np.
random
.
poisson
(
10
,
n_samples
)
Poisson distribution: number of customers
product_rating
=
np.
random
.
randint
(
1
,
6
,
n_samples
)
1-5 star rating
defect_count
=
np.
random
.
binomial
(
20
,
0.1
,
n_samples
)
Binomial distribution: number of defects
call_duration
=
np.
random
.
exponential
(
5
,
n_samples
)
60
Exponential distribution: call duration (seconds)
Create a data frame
discrete_data
=
pd.
DataFrame
(
{
'Number of Customers'
: customer_count
,
'Product Rating'
: product_rating
,
'Number of Defects'
: defect_count
,
'Call Duration (s)'
: call_duration.
astype
(
int
)
}
)
(
"Discrete Data Example:"
)
(
discrete_data.
head
(
)
)
(
f
"\nData Statistics:"
)
(
discrete_data.
describe
(
)
)
Visualize discrete data
plt.
figure
(
figsize
=
(
12
,
8
)
)
plt.
subplot
(
2
,
2
,
1
)
plt.
hist
(
discrete_data
[
'Number of Customers'
]
,
bins
=
range
(
0
,
max
(
discrete_data
[
'Number of Customers'
]
)
2
)
,
alpha
=
0.7
,
color
=
'orange'
)
plt.
title
(
'Customer Count Distribution'
)
plt.
xlabel
(
'Number of Customers'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
2
)
value_counts
=
discrete_data
[
'Product Rating'
]
.
value_counts
(
)
.
sort_index
(
)
plt.
bar
(
value_counts.
index
,
value_counts.
values
,
color
=
'purple'
,
alpha
=
0.7
)
plt.
title
(
'Product Rating Distribution'
)
plt.
xlabel
(
'Rating'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
3
)
plt.
hist
(
discrete_data
[
'Number of Defects'
]
,
bins
=
range
(
0
,
max
(
discrete_data
[
'Number of Defects'
]
)
2
)
,
alpha
=
0.7
,
color
=
'red'
)
plt.
title
(
'Defect Count Distribution'
)
plt.
xlabel
(
'Number of Defects'
)
plt.
ylabel
(
'Frequency'
)
plt.
subplot
(
2
,
2
,
4
)
plt.
hist
(
discrete_data
[
'Call Duration (s)'
]
,
bins
=
30
,
alpha
=
0.7
,
color
=
'brown'
)
plt.
title
(
'Call Duration Distribution'
)
plt.
xlabel
(
'Call Duration (s)'
)
plt.
ylabel
(
'Frequency'
)
plt.
tight_layout
(
)
plt.
show
(
)
return
discrete_data
Running the Example
discrete_df
=
discrete_data_example
(
)
Processing Methods for Numeric Data
Example
Numeric Data Processing Methods
class
NumericDataProcessor:
def
init
(
self
)
:
self
.
scalers
=
{
}
self
.
transformers
=
{
}
def
detect_outliers
(
self
,
data
,
method
=
'iqr'
)
:
"""Detect Outliers"""
outliers_info
=
{
}
for
column
in
data.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
:
if
method
==
'iqr'
:
Q1
=
data
[
column
]
.
quantile
(
0.25
)
Q3
=
data
[
column
]
.
quantile
(
0.75
)
IQR
=
Q3 - Q1
lower_bound
=
Q1 -
1.5
- IQR
upper_bound
=
Q3 +
1.5
- IQR
outliers
=
data
[
(
data
[
column
]
<
lower_bound
)
|
(
data
[
column
]
upper_bound
)
]
elif
method
==
'zscore':
z_scores
=
np.
abs
(
(
data
[
column
]
- data
[
column
]
.
mean
(
)
)
/ data
[
column
]
.
std
(
)
)
outliers
=
data
[
z_scores
3
]
outliers_info
[
column
]
=
{
'count'
:
len
(
outliers
)
,
'indices'
: outliers.
index
.
tolist
(
)
,
'percentage'
:
(
len
(
outliers
)
/
len
(
data
)
)
100
}
return
outliers_info
def
handle_missing_values
(
self
,
data
,
strategy
=
'mean'
)
:
"""Handle Missing Values"""
processed_data
=
data.
copy
(
)
for
column
in
processed_data.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
:
if
processed_data
[
column
]
.
isnull
(
)
.
sum
(
)
0
:
if
strategy
==
'mean'
:
processed_data
[
column
]
.
fillna
(
processed_data
[
column
]
.
mean
(
)
,
inplace
=
True
)
elif
strategy
==
'median'
:
processed_data
[
column
]
.
fillna
(
processed_data
[
column
]
.
median
(
)
,
inplace
=
True
)
elif
strategy
==
'mode'
:
processed_data
[
column
]
.
fillna
(
processed_data
[
column
]
.
mode
(
)
[
0
]
,
inplace
=
True
)
elif
strategy
==
'forward'
:
processed_data
[
column
]
.
fillna
(
method
=
'ffill'
,
inplace
=
True
)
elif
strategy
==
'backward'
:
processed_data
[
column
]
.
fillna
(
method
=
'bfill'
,
inplace
=
True
)
return
processed_data
def
normalize_data
(
self
,
data
,
method
=
'minmax'
)
:
"""Data Standardization"""
from
sklearn.
preprocessing
import
MinMaxScaler
,
StandardScaler
,
RobustScaler
processed_data
=
data.
copy
(
)
numeric_columns
=
data.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
if
method
==
'minmax'
:
scaler
=
MinMaxScaler
(
)
elif
method
==
'standard'
:
scaler
=
StandardScaler
(
)
elif
method
==
'robust'
:
scaler
=
RobustScaler
(
)
else
:
raise
ValueError
(
"Method must be 'minmax', 'standard', or 'robust'"
)
processed_data
[
numeric_columns
]
=
scaler.
fit_transform
(
processed_data
[
numeric_columns
]
)
self
.
scalers
[
method
]
=
scaler
return
processed_data
def
create_features
(
self
,
data
)
:
"""Feature Engineering"""
processed_data
=
data.
copy
(
)
numeric_columns
=
data.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
Create polynomial features
if
len
(
numeric_columns
)
=
2
:
col1
,
col2
=
numeric_columns
[
0
]
,
numeric_columns
[
1
]
processed_data
[
f
'{col1}x{col2}'
]
=
data
[
col1
]
- data
[
col2
]
processed_data
[
f
'{col1}div{col2}'
]
=
data
[
col1
]
/
(
data
[
col2
]
1e-8
)
Create statistical features
for
column
in
numeric_columns:
processed_data
[
f
'{column}_log'
]
=
np.
log1p
(
data
[
column
]
)
processed_data
[
f
'{column}_sqrt'
]
=
np.
sqrt
(
np.
abs
(
data
[
column
]
)
)
processed_data
[
f
'{column}_square'
]
=
data
[
column
]
**
2
return
processed_data
Usage examples
processor
=
NumericDataProcessor
(
)
Detect outliers
outliers
=
processor.
detect_outliers
(
continuous_df
)
(
"\nOutlier Detection Results:"
)
for
column
,
info
in
outliers.
items
(
)
:
if
info
[
'count'
]
0
:
(
f
"{column}: {info['count']} outliers ({info['percentage']:.2f}%)"
)
Data standardization
normalized_data
=
processor.
normalize_data
(
continuous_df
,
method
=
'standard'
)
(
"\nExample of Standardized Data:"
)
(
normalized_data.
head
(
)
)
Text Data
What Is Text Data?
Text data is like the expression of human language; it contains rich semantic information but requires special processing before it can be used by machine learning models.
Classification of Text Data
1. Structured Text Data
Example
Structured Text Data Example
import
pandas
as
pd
import
re
from
collections
import
Counter
def
structured_text_example
(
)
:
"""Structured Text Data Example"""
(
"\n=== Structured Text Data Example ==="
)
Create structured text data
structured_data
=
pd.
DataFrame
(
{
'Email ID'
:
range
(
1
,
11
)
,
'Sender'
:
[
'zhangsan@example.com'
,
'lisi@company.com'
,
'wangwu@service.com'
,
'zhaoliu@business.com'
,
'qianqi@personal.com'
,
'sunba@tech.com'
,
'zhoujiu@edu.com'
,
'wushi@org.com'
,
'zhengyi@gov.com'
,
'chener@health.com'
]
,
'Subject'
:
[
'Meeting Notice: Meeting Tomorrow at 3 PM'
,
'Product Quote: Latest Price List'
,
'Customer Feedback: Service Satisfaction Survey'
,
'Project Progress: Phase One Completed'
,
'Holiday Arrangement: National Day Holiday Notice'
,
'Technical Update: System Upgrade Announcement'
,
'Academic Conference: Call for Papers'
,
'Training Notice: New Employee Training'
,
'Policy Document: Latest Regulations'
,
'Health Reminder: Physical Examination Notice'
]
,
'Content Length'
:
[
156
,
234
,
189
,
145
,
98
,
267
,
198
,
134
,
312
,
87
]
}
)
(
"Structured Text Data Example:"
)
(
structured_data
)
Text feature extraction
(
"\n=== Text Feature Analysis ==="
)
Email domain analysis
domains
=
[
.
split
(
'@'
)
[
1
]
for
in
structured_data
[
'Sender'
]
]
domain_counts
=
Counter
(
domains
)
(
f
"Email Domain Distribution: {dict(domain_counts)}"
)
Subject keyword analysis
all_words
=
[
]
for
subject
in
structured_data
[
'Subject'
]
:
words
=
re
.
findall
(
r
'[\u4e00-\u9fff]+'
,
subject
)
Extract Chinese words
all_words.
extend
(
words
)
word_counts
=
Counter
(
all_words
)
(
f
"Subject Word Frequency: {dict(word_counts)}"
)
Content length statistics
(
f
"Content Length Statistics:"
)
(
structured_data
[
'Content Length'
]
.
describe
(
)
)
return
structured_data
Running the Example
structured_text_df
=
structured_text_example
(
)
2. Unstructured Text Data
Example
Unstructured Text Data Example
def
unstructured_text_example
(
)
:
"""Unstructured Text Data Example"""
(
"\n=== Unstructured Text Data Example ==="
)
Create unstructured text data
unstructured_texts
=
[
"""
Artificial intelligence technology is developing rapidly, with major breakthroughs in fields such as deep learning, machine learning, and natural language processing.
These technologies are widely used in many industries such as healthcare, finance, education, and transportation, bringing new opportunities for social development.
In the future, as computing power increases and algorithms improve, artificial intelligence will play an important role in more fields.
"""
,
"""
The weather is lovely today, sunny with a gentle breeze. I decided to go for a walk in the park and enjoy this wonderful time.
There are many flowers in the park, red, yellow, and purple, colorful and very beautiful. Little birds sing in the trees,
butterflies dance among the flowers, and everything seems so harmonious and natural.
"""
,
"""
The stock market performed strongly today, with the Shanghai Composite Index rising 2.3% and the Shenzhen Component Index rising 1.8%.
Tech stocks led the gains, with many stocks hitting their daily upper limit. Analysts believe this is mainly due to recently introduced favorable policies.
Investor confidence was boosted, market trading was active, and trading volume increased significantly.
"""
,
"""
A healthy lifestyle includes a balanced diet, moderate exercise, adequate sleep, and a good mindset.
It is recommended to eat vegetables and fruits every day, reduce greasy food; exercise at least 3 times a week, for more than 30 minutes each time;
ensure 7-8 hours of sleep; learn to regulate your emotions and maintain a positive and optimistic attitude.
"""
]
text_categories
=
[
'Technology'
,
'Life'
,
'Finance'
,
'Health'
]
Create a data frame
unstructured_df
=
pd.
DataFrame
(
{
'Wen ben' (a Chinese phrase)
: unstructured_texts
,
'Category'
: text_categories
}
)
(
"Unstructured Text Data Example:"
)
for
i
,
row
in
unstructured_df.
iterrows
(
)
:
(
f
"\nCategory: {row['Category']}"
)
(
f
"Text: {row['Text'][:100]}..."
)
return
unstructured_df
Running the Example
unstructured_text_df
=
unstructured_text_example
(
)
Text Data Processing Methods
Example
Text Data Processing Methods
import
jieba
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
,
CountVectorizer
from
sklearn.
preprocessing
import
LabelEncoder
class
TextDataProcessor:
def
init
(
self
)
:
self
.
vectorizers
=
{
}
self
.
label_encoders
=
{
}
def
clean_text
(
self
,
text
)
:
"""Text Cleaning"""
Remove special characters and numbers
text
=
re
.
sub
(
r
'[^\u4e00-\u9fff\s]'
,
''
,
text
)
Remove extra spaces
text
=
re
.
sub
(
r
'\s+'
,
' '
,
text
)
.
strip
(
)
return
text
def
tokenize_chinese
(
self
,
text
)
:
"""Chinese Word Segmentation"""
words
=
jieba.
lcut
(
text
)
Remove stop words (simplified version)
stop_words
=
{
'de'
,
'le'
,
'zai'
,
'Yes'
,
'Wo' (a Chinese character)
,
'you'
,
'he'
,
'jiu'
,
'bu'
,
'ren'
,
'dou'
,
'yi'
,
'yige'
,
'Top'
,
'ye'
,
'Hen' (a Chinese character)
,
'dao'
,
'shuo'
,
'yao'
,
'qu'
,
'Ni' (a Chinese character)
,
'hui'
,
'zhe'
,
'meiyou'
,
'kan'
,
'Good'
,
'ziji'
,
'zhe'
}
words
=
[
word
for
word
in
words
if
word
not
in
stop_words
and
len
(
word
)
1
]
return
words
def
extract_features
(
self
,
texts
,
method
=
'tfidf'
)
:
"""Feature Extraction"""
Text preprocessing
cleaned_texts
=
[
self
.
clean_text
(
text
)
for
text
in
texts
]
if
method
==
'tfidf'
:
vectorizer
=
TfidfVectorizer
(
max_features
=
1000
,
token_pattern
=
r
'(?u)\b\w+\b'
)
elif
method
==
'count'
:
vectorizer
=
CountVectorizer
(
max_features
=
1000
,
token_pattern
=
r
'(?u)\b\w+\b'
)
else
:
raise
ValueError
(
"Method must be 'tfidf' or 'count'"
)
features
=
vectorizer.
fit_transform
(
cleaned_texts
)
self
.
vectorizers
[
method
]
=
vectorizer
return
features.
toarray
(
)
,
vectorizer.
get_feature_names_out
(
)
def
analyze_text_statistics
(
self
,
texts
)
:
"""Text Statistical Analysis"""
stats
=
[
]
for
text
in
texts:
cleaned_text
=
self
.
clean_text
(
text
)
words
=
self
.
tokenize_chinese
(
cleaned_text
)
stats.
append
(
{
'Number of Characters'
:
len
(
text
)
,
'Characters After Cleaning'
:
len
(
cleaned_text
)
,
'Number of Words'
:
len
(
words
)
,
'Average Word Length'
: np.
mean
(
[
len
(
word
)
for
word
in
words
]
)
if
words
else
0
,
'Number of Unique Words'
:
len
(
set
(
words
)
)
}
)
return
pd.
DataFrame
(
stats
)
def
encode_labels
(
self
,
labels
)
:
"""Label Encoding"""
encoder
=
LabelEncoder
(
)
encoded_labels
=
encoder.
fit_transform
(
labels
)
self
.
label_encoders
[
'default'
]
=
encoder
return
encoded_labels
,
encoder.
classes_
Usage examples
text_processor
=
TextDataProcessor
(
)
Text Statistical Analysis
text_stats
=
text_processor.
analyze_text_statistics
(
unstructured_text_df
[
'Wen ben' (a Chinese phrase)
]
)
(
"\nText Statistical Analysis:"
)
(
text_stats
)
Feature extraction
features
,
feature_names
=
text_processor.
extract_features
(
unstructured_text_df
[
'Wen ben' (a Chinese phrase)
]
,
method
=
'tfidf'
)
(
f
"\nFeature Matrix Shape: {features.shape}"
)
(
f
"Top 10 Features: {feature_names[:10]}"
)
Label Encoding
encoded_labels
,
label_classes
=
text_processor.
encode_labels
(
unstructured_text_df
[
'Category'
]
)
(
f
"\nEncoded Labels: {encoded_labels}"
)
(
f
"Label Classes: {label_classes}"
)
Image Data
What Is Image Data?
Image data is like a digital representation of the visual world; it is composed of pixels and contains rich spatial and color information.
Classification of Image Data
1. Grayscale Images
Example
Grayscale Image Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
PIL
import
Image
def
grayscale_image_example
(
)
:
"""Grayscale Image Example"""
(
"\n=== Grayscale Image Example ==="
)
Create a simple grayscale image
Create a 100x100 grayscale image
height
,
width
=
100
,
100
Create a gradient image
gradient
=
np.
zeros
(
(
height
,
width
)
)
for
i
in
range
(
height
)
:
gradient
[
i
,
:
]
=
i
Vertical gradient
Create a checkerboard pattern
checkerboard
=
np.
zeros
(
(
height
,
width
)
)
for
i
in
range
(
0
,
height
,
10
)
:
for
j
in
range
(
0
,
width
,
10
)
:
if
(
i //
10
- j //
10
)
%
2
==
0
:
checkerboard
[
i:i+
10
,
j:j+
10
]
=
255
Create a circular pattern
circle
=
np.
zeros
(
(
height
,
width
)
)
center_x
,
center_y
=
width //
2
,
height //
2
radius
=
30
for
i
in
range
(
height
)
:
for
j
in
range
(
width
)
:
if
(
i - center_y
)
**
2
(
j - center_x
)
**
2
<=
radius **
2
:
circle
[
i
,
j
]
=
255
Displays an image
plt.
figure
(
figsize
=
(
12
,
4
)
)
plt.
subplot
(
1
,
3
,
1
)
plt.
imshow
(
gradient
,
cmap
=
'gray'
)
plt.
title
(
'Gradient Image'
)
plt.
axis
(
'off'
)
plt.
subplot
(
1
,
3
,
2
)
plt.
imshow
(
checkerboard
,
cmap
=
'gray'
)
plt.
title
(
'Checkerboard Pattern'
)
plt.
axis
(
'off'
)
plt.
subplot
(
1
,
3
,
3
)
plt.
imshow
(
circle
,
cmap
=
'gray'
)
plt.
title
(
'Circular Pattern'
)
plt.
axis
(
'off'
)
plt.
tight_layout
(
)
plt.
show
(
)
Image Data Information
(
f
"Gradient Image Shape: {gradient.shape}"
)
(
f
"Data Type: {gradient.dtype}"
)
(
f
"Pixel Value Range: {gradient.min()} - {gradient.max()}"
)
return
gradient
,
checkerboard
,
circle
Running the Example
gradient_img
,
checkerboard_img
,
circle_img
=
grayscale_image_example
(
)
x
2. Color Images
Example
Color Image Example
def
color_image_example
(
)
:
"""Color Image Example"""
(
"\n=== Color Image Example ==="
)
height
,
width
=
100
,
100
Create an RGB color image
Red gradient
red_gradient
=
np.
zeros
(
(
height
,
width
,
3
)
,
dtype
=
np.
uint8
)
red_gradient
[
:
,
:
,
0
]
=
np.
linspace
(
0
,
255
,
width
)
Red channel gradient
Green gradient
green_gradient
=
np.
zeros
(
(
height
,
width
,
3
)
,
dtype
=
np.
uint8
)
green_gradient
[
:
,
:
,
1
]
=
np.
linspace
(
0
,
255
,
width
)
Green channel gradient
Blue gradient
blue_gradient
=
np.
zeros
(
(
height
,
width
,
3
)
,
dtype
=
np.
uint8
)
blue_gradient
[
:
,
:
,
2
]
=
np.
linspace
(
0
,
255
,
width
)
Blue channel gradient
Rainbow pattern
rainbow
=
np.
zeros
(
(
height
,
width
,
3
)
,
dtype
=
np.
uint8
)
for
i
in
range
(
width
)
:
hue
=
i / width
Simplified HSV-to-RGB conversion
if
hue
<
1
/
3:
rainbow
[
:
,
i
]
=
[
255
(
1
3
*hue
)
,
255
3
*hue
,
0
]
elif
hue
<
2
/
3:
rainbow
[
:
,
i
]
=
[
0
,
255
(
2
3
*hue
)
,
255
(
3
*hue -
1
)
]
else
:
rainbow
[
:
,
i
]
=
[
255
(
3
*hue -
2
)
,
0
,
255
(
3
3
*hue
)
]
Displays an image
plt.
figure
(
figsize
=
(
12
,
8
)
)
plt.
subplot
(
2
,
2
,
1
)
plt.
imshow
(
red_gradient
)
plt.
title
(
'Red Gradient'
)
plt.
axis
(
'off'
)
plt.
subplot
(
2
,
2
,
2
)
plt.
imshow
(
green_gradient
)
plt.
title
(
'Green Gradient'
)
plt.
axis
(
'off'
)
plt.
subplot
(
2
,
2
,
3
)
plt.
imshow
(
blue_gradient
)
plt.
title
(
'Blue Gradient'
)
plt.
axis
(
'off'
)
plt.
subplot
(
2
,
2
,
4
)
plt.
imshow
(
rainbow
)
plt.
title
(
'Rainbow Pattern'
)
plt.
axis
(
'off'
)
plt.
tight_layout
(
)
plt.
show
(
)
Image Channel Information
(
f
"Color Image Shape: {rainbow.shape}"
)
(
f
"Data Type: {rainbow.dtype}"
)
(
f
"Pixel Value Range: {rainbow.min()} - {rainbow.max()}"
)
return
red_gradient
,
green_gradient
,
blue_gradient
,
rainbow
Running the Example
red_img
,
green_img
,
blue_img
,
rainbow_img
=
color_image_example
(
)
Image Data Processing Methods
Example
Image Data Processing Methods
from
skimage
import
filters
,
feature
,
measure
,
transform
from
skimage.
color
import
rgb2gray
,
rgb2hsv
class
ImageDataProcessor:
def
init
(
self
)
:
pass
def
resize_image
(
self
,
image
,
target_size
)
:
"""Resize Images"""
from
skimage.
transform
import
resize
return
resize
(
image
,
target_size
,
anti_aliasing
=
True
)
def
normalize_image
(
self
,
image
)
:
"""Image Normalization"""
return
(
image - image.
min
(
)
)
/
(
image.
max
(
)
- image.
min
(
)
)
def
extract_color_features
(
self
,
image
)
:
"""Extract Color Features"""
if
len
(
image.
shape
)
==
3
:
Color images
Compute statistical features for each channel
features
=
{
}
for
i
,
channel
in
enumerate
(
[
'R'
,
'G'
,
'B'
]
)
:
channel_data
=
image
[
:
,
:
,
i
]
features
[
f
'{channel}_mean'
]
=
np.
mean
(
channel_data
)
features
[
f
'{channel}_std'
]
=
np.
std
(
channel_data
)
features
[
f
'{channel}_min'
]
=
np.
min
(
channel_data
)
features
[
f
'{channel}_max'
]
=
np.
max
(
channel_data
)
Compute color histogram features
hist_r
,
_
=
np.
histogram
(
image
[
:
,
:
,
0
]
,
bins
=
256
,
range
=
(
0
,
256
)
)
hist_g
,
_
=
np.
histogram
(
image
[
:
,
:
,
1
]
,
bins
=
256
,
range
=
(
0
,
256
)
)
hist_b
,
_
=
np.
histogram
(
image
[
:
,
:
,
2
]
,
bins
=
256
,
range
=
(
0
,
256
)
)
features.
update
(
{
'hist_r_peak'
: np.
argmax
(
hist_r
)
,
'hist_g_peak'
: np.
argmax
(
hist_g
)
,
'hist_b_peak'
: np.
argmax
(
hist_b
)
}
)
return
features
else
:
Grayscale images
return
{
'mean'
: np.
mean
(
image
)
,
'std'
: np.
std
(
image
)
,
'min'
: np.
min
(
image
)
,
'max'
: np.
max
(
image
)
}
def
extract_texture_features
(
self
,
image
)
:
"""Extract Texture Features"""
if
len
(
image.
shape
)
==
3
:
image
=
rgb2gray
(
image
)
Compute edge features
edges
=
filters.
sobel
(
image
)
edge_density
=
np.
sum
(
edges
0
)
/ edges.
size
Compute local binary patterns (simplified version)
lbp
=
feature.
local_binary_pattern
(
image
,
P
=
8
,
R
=
1
,
method
=
'uniform'
)
lbp_hist
,
_
=
np.
histogram
(
lbp.
ravel
(
)
,
bins
=
10
)
return
{
'edge_density'
: edge_density
,
'lbp_hist'
: lbp_hist.
tolist
(
)
}
def
augment_image
(
self
,
image
)
:
"""Image Augmentation"""
augmented
=
[
]
Original image
augmented.
append
(
image
)
Horizontal flip
augmented.
append
(
np.
fliplr
(
image
)
)
Vertical flip
augmented.
append
(
np.
flipud
(
image
)
)
Rotate 90 degrees
augmented.
append
(
np.
rot90
(
image
)
)
Brightness adjustment
if
len
(
image.
shape
)
==
3
:
brightened
=
np.
clip
(
image *
1.2
,
0
,
255
)
.
astype
(
np.
uint8
)
else
:
brightened
=
np.
clip
(
image *
1.2
,
0
,
1
)
augmented.
append
(
brightened
)
return
augmented
def
visualize_image_channels
(
self
,
image
)
:
"""Visualize Image Channels"""
if
len
(
image.
shape
)
==
3
:
plt.
figure
(
figsize
=
(
12
,
3
)
)
plt.
subplot
(
1
,
4
,
1
)
plt.
imshow
(
image
)
plt.
title
(
'Original Image'
)
plt.
axis
(
'off'
)
plt.
subplot
(
1
,
4
,
2
)
plt.
imshow
(
image
[
:
,
:
,
0
]
,
cmap
=
'Reds'
)
plt.
title
(
'Red Channel'
)
plt.
axis
(
'off'
)
plt.
subplot
(
1
,
4
,
3
)
plt.
imshow
(
image
[
:
,
:
,
1
]
,
cmap
=
'Greens'
)
plt.
title
(
'Green Channel'
)
plt.
axis
(
'off'
)
plt.
subplot
(
1
,
4
,
4
)
plt.
imshow
(
image
[
:
,
:
,
2
]
,
cmap
=
'Blues'
)
plt.
title
(
'Blue Channel'
)
plt.
axis
(
'off'
)
plt.
tight_layout
(
)
plt.
show
(
)
Usage examples
image_processor
=
ImageDataProcessor
(
)
Extract color features
color_features
=
image_processor.
extract_color_features
(
rainbow_img
)
(
"\nColor Features:"
)
for
key
,
value
in
color_features.
items
(
)
:
if
not
key.
startswith
(
'hist'
)
:
(
f
"{key}: {value:.2f}"
)
Extract texture features
texture_features
=
image_processor.
extract_texture_features
(
checkerboard_img
)
(
"\nTexture Features:"
)
for
key
,
value
in
texture_features.
items
(
)
:
if
key
!=
'lbp_hist'
:
(
f
"{key}: {value:.4f}"
)
Image enhancement
augmented_images
=
image_processor.
augment_image
(
circle_img
)
(
f
"\nImage Augmentation: Generated {len(augmented_images)} variants"
)
Visualize image channels
image_processor.
visualize_image_channels
(
rainbow_img
)
Categorical Data
What Is Categorical Data?
Categorical data is like classification labels; it represents different categories or groups and cannot be used in mathematical operations.
Classification of Categorical Data
1. Nominal Data
Example
Nominal Data Example
def
nominal_data_example
(
)
:
"""Nominal Data Example"""
(
"\n=== Nominal Data Example ==="
)
Create nominal data
nominal_data
=
pd.
DataFrame
(
{
'Student ID'
:
range
(
1
,
11
)
,
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Qian Qi'
,
'Sun Ba'
,
'Zhou Jiu'
,
'Wu Shi'
,
'Zheng Shiyi'
,
'Chen Shier'
]
,
'Gender'
:
[
'male'
,
'female'
,
'male'
,
'male'
,
'female'
,
'female'
,
'male'
,
'female'
,
'male'
,
'female'
]
,
'Blood Type'
:
[
'A'
,
'B'
,
'O'
,
'AB'
,
'A'
,
'B'
,
'O'
,
'AB'
,
'A'
,
'O'
]
,
'City'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
,
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
,
'Beijing'
,
'Shanghai'
]
,
'Major'
:
[
'Computer Science'
,
'Math'
,
'Physics'
,
'Chemistry'
,
'Computer Science'
,
'Math'
,
'Physics'
,
'Chemistry'
,
'Computer Science'
,
'Math'
]
}
)
(
"Nominal Data Example:"
)
(
nominal_data
)
Category Statistical Analysis
(
"\n=== Category Statistical Analysis ==="
)
for
column
in
nominal_data.
select_dtypes
(
include
=
[
'object'
]
)
.
columns
:
if
column
!=
'Name'
:
Skip the name column
value_counts
=
nominal_data
[
column
]
.
value_counts
(
)
(
f
"\n{column} Distribution:"
)
(
value_counts
)
(
f
"Number of Unique Values: {len(value_counts)}"
)
return
nominal_data
Running the Example
nominal_df
=
nominal_data_example
(
)
2. Ordinal Data
Example
Ordinal Data Example
def
ordinal_data_example
(
)
:
"""Ordinal Data Example"""
(
"\n=== Ordinal Data Example ==="
)
Create ordinal data
ordinal_data
=
pd.
DataFrame
(
{
'Product ID'
:
range
(
1
,
11
)
,
'Product Name'
:
[
f
'Product {i}'
for
i
in
range
(
1
,
11
)
]
,
'Quality Level'
:
[
'Excellent'
,
'Good'
,
'Average'
,
'Excellent'
,
'Good'
,
'Average'
,
'Poor'
,
'Excellent'
,
'Good'
,
'Average'
]
,
'Customer Satisfaction'
:
[
'Very Satisfied'
,
'Satisfied'
,
'Average'
,
'Very Satisfied'
,
'Satisfied'
,
'Average'
,
'Dissatisfied'
,
'Very Satisfied'
,
'Satisfied'
,
'Average'
]
,
'Price Range'
:
[
'High'
,
'Center'
,
'Low'
,
'High'
,
'Center'
,
'Low'
,
'Low'
,
'High'
,
'Center'
,
'Center'
]
,
'Sales Rank'
:
[
1
,
3
,
5
,
2
,
4
,
7
,
9
,
6
,
8
,
10
]
}
)
(
"Ordinal Data Example:"
)
(
ordinal_data
)
Ordinal Data Statistical Analysis
(
"\n=== Ordinal Data Statistical Analysis ==="
)
Define the order
quality_order
=
[
'Poor'
,
'Average'
,
'Good'
,
'Excellent'
]
satisfaction_order
=
[
'Dissatisfied'
,
'Average'
,
'Satisfied'
,
'Very Satisfied'
]
price_order
=
[
'Low'
,
'Center'
,
'High'
]
Convert to ordinal categories
ordinal_data
[
'Quality Level_Ordinal'
]
=
pd.
Categorical
(
ordinal_data
[
'Quality Level'
]
,
categories
=
quality_order
,
ordered
=
True
)
ordinal_data
[
'Customer Satisfaction_Ordinal'
]
=
pd.
Categorical
(
ordinal_data
[
'Customer Satisfaction'
]
,
categories
=
satisfaction_order
,
ordered
=
True
)
ordinal_data
[
'Price Range_Ordinal'
]
=
pd.
Categorical
(
ordinal_data
[
'Price Range'
]
,
categories
=
price_order
,
ordered
=
True
)
Statistical analysis
for
column
in
[
'Quality Level_Ordinal'
,
'Customer Satisfaction_Ordinal'
,
'Price Range_Ordinal'
]
:
(
f
"\n{column} Distribution:"
)
value_counts
=
ordinal_data
[
column
]
.
value_counts
(
)
.
sort_index
(
)
(
value_counts
)
Calculate the median
median_value
=
ordinal_data
[
column
]
.
median
(
)
(
f
"Median: {median_value}"
)
return
ordinal_data
Running the Example
ordinal_df
=
ordinal_data_example
(
)
Categorical Data Processing Methods
Example
Categorical Data Processing Methods
from
sklearn.
preprocessing
import
LabelEncoder
,
OneHotEncoder
,
OrdinalEncoder
class
CategoricalDataProcessor:
def
init
(
self
)
:
self
.
encoders
=
{
}
self
.
feature_names
=
{
}
def
label_encoding
(
self
,
data
,
columns
)
:
"""Label Encoding"""
encoded_data
=
data.
copy
(
)
for
column
in
columns:
encoder
=
LabelEncoder
(
)
encoded_data
[
f
'{column}_encoded'
]
=
encoder.
fit_transform
(
data
[
column
]
)
self
.
encoders
[
f
'{column}_label'
]
=
encoder
(
f
"{column} Label Encoding:"
)
for
i
,
category
in
enumerate
(
encoder.
classes_
)
:
(
f
" {category} -> {i}"
)
return
encoded_data
def
one_hot_encoding
(
self
,
data
,
columns
)
:
"""One-Hot Encoding"""
encoded_data
=
data.
copy
(
)
for
column
in
columns:
encoder
=
OneHotEncoder
(
sparse
=
False
,
drop
=
'first'
)
Avoid multicollinearity
encoded_features
=
encoder.
fit_transform
(
data
[
[
column
]
]
)
Create new column names
feature_names
=
[
f
'{column}_{category}'
for
category
in
encoder.
categories_
[
0
]
[
1
:
]
]
Add to the dataframe
for
i
,
feature_name
in
enumerate
(
feature_names
)
:
encoded_data
[
feature_name
]
=
encoded_features
[
:
,
i
]
self
.
encoders
[
f
'{column}_onehot'
]
=
encoder
self
.
feature_names
[
f
'{column}_onehot'
]
=
feature_names
(
f
"{column} One-Hot Encoding: Created {len(feature_names)} features"
)
return
encoded_data
def
ordinal_encoding
(
self
,
data
,
columns
,
categories_list
)
:
"""Ordinal Encoding"""
encoded_data
=
data.
copy
(
)
for
column
,
categories
in
zip
(
columns
,
categories_list
)
:
encoder
=
OrdinalEncoder
(
categories
=
[
categories
]
)
encoded_data
[
f
'{column}_ordinal'
]
=
encoder.
fit_transform
(
data
[
[
column
]
]
)
self
.
encoders
[
f
'{column}_ordinal'
]
=
encoder
(
f
"{column} Ordinal Encoding:"
)
for
i
,
category
in
enumerate
(
categories
)
:
(
f
" {category} -> {i}"
)
return
encoded_data
def
target_encoding
(
self
,
data
,
categorical_column
,
target_column
)
:
"""Target Encoding"""
encoded_data
=
data.
copy
(
)
Compute the target mean for each category
target_means
=
data.
groupby
(
categorical_column
)
[
target_column
]
.
mean
(
)
Apply encoding
encoded_data
[
f
'{categorical_column}_target'
]
=
data
[
categorical_column
]
.
map
(
target_means
)
(
f
"{categorical_column} Target Encoding:"
)
for
category
,
mean_value
in
target_means.
items
(
)
:
(
f
" {category} -> {mean_value:.4f}"
)
return
encoded_data
def
frequency_encoding
(
self
,
data
,
columns
)
:
"""Frequency Encoding"""
encoded_data
=
data.
copy
(
)
for
column
in
columns:
Compute the frequency of each category
frequency
=
data
[
column
]
.
value_counts
(
normalize
=
True
)
Apply encoding
encoded_data
[
f
'{column}_frequency'
]
=
data
[
column
]
.
map
(
frequency
)
(
f
"{column} Frequency Encoding:"
)
for
category
,
freq
in
frequency.
head
(
)
.
items
(
)
:
(
f
" {category} -> {freq:.4f}"
)
return
encoded_data
def
analyze_categorical_importance
(
self
,
data
,
categorical_columns
,
target_column
)
:
"""Analyze Categorical Feature Importance"""
importance_scores
=
{
}
for
column
in
categorical_columns:
Compute the target mean difference for each category
category_means
=
data.
groupby
(
column
)
[
target_column
]
.
mean
(
)
mean_difference
=
category_means.
max
(
)
- category_means.
min
(
)
Compute the number of categories
unique_count
=
data
[
column
]
.
nunique
(
)
Simple importance score
importance
=
mean_difference * np.
log
(
unique_count +
1
)
importance_scores
[
column
]
=
importance
Sorting
sorted_importance
=
sorted
(
importance_scores.
items
(
)
,
key
=
lambda
x: x
[
1
]
,
reverse
=
True
)
(
"\nCategorical Feature Importance:"
)
for
column
,
importance
in
sorted_importance:
(
f
"{column}: {importance:.4f}"
)
return
importance_scores
Usage examples
cat_processor
=
CategoricalDataProcessor
(
)
Add a numeric target to nominal data
nominal_df_with_target
=
nominal_df.
copy
(
)
nominal_df_with_target
[
'Score'
]
=
np.
random
.
randint
(
60
,
100
,
len
(
nominal_df
)
)
Label Encoding
label_encoded
=
cat_processor.
label_encoding
(
nominal_df_with_target
,
[
'Gender'
,
'Blood Type'
,
'City'
]
)
One-Hot Encoding
onehot_encoded
=
cat_processor.
one_hot_encoding
(
nominal_df_with_target
,
[
'Major'
]
)
Target encoding
target_encoded
=
cat_processor.
target_encoding
(
nominal_df_with_target
,
'City'
,
'Score'
)
Frequency encoding
frequency_encoded
=
cat_processor.
frequency_encoding
(
nominal_df_with_target
,
[
'Gender'
,
'Blood Type'
]
)
Analyze feature importance
importance_scores
=
cat_processor.
analyze_categorical_importance
(
nominal_df_with_target
,
[
'Gender'
,
'Blood Type'
,
'City'
,
'Major'
]
,
'Score'
)
Multimodal Data Fusion
Data Type Fusion Example
Example
Multimodal Data Fusion Example
class
MultiModalDataProcessor:
def
init
(
self
)
:
self
.
numeric_processor
=
NumericDataProcessor
(
)
self
.
text_processor
=
TextDataProcessor
(
)
self
.
image_processor
=
ImageDataProcessor
(
)
self
.
categorical_processor
=
CategoricalDataProcessor
(
)
def
create_multimodal_dataset
(
self
)
:
"""Create a Multimodal Dataset"""
(
"\n=== Multimodal Dataset Example ==="
)
n_samples
=
100
Numeric features
numeric_features
=
{
'Age'
: np.
random
.
randint
(
18
,
65
,
n_samples
)
,
'Income'
: np.
random
.
normal
(
50000
,
15000
,
n_samples
)
,
'Work Experience'
: np.
random
.
randint
(
0
,
20
,
n_samples
)
}
Categorical features
categorical_features
=
{
'Gender'
: np.
random
.
choice
(
[
'male'
,
'female'
]
,
n_samples
)
,
'Education Level'
: np.
random
.
choice
(
[
'High School'
,
"Bachelor's"
,
"Master's"
,
'PhD'
]
,
n_samples
)
,
'City'
: np.
random
.
choice
(
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
n_samples
)
}
Text features
text_features
=
[
f
"This is the text description of sample {i}, containing some basic information and features."
for
i
in
range
(
n_samples
)
]
Image features (simulated)
image_features
=
np.
random
.
rand
(
n_samples
,
64
,
64
,
3
)
Simulate 64x64 color images
Target variable
target
=
np.
random
.
choice
(
[
0
,
1
]
,
n_samples
)
Create a dataset
dataset
=
{
'numeric'
: pd.
DataFrame
(
numeric_features
)
,
'categorical'
: pd.
DataFrame
(
categorical_features
)
,
'text'
: text_features
,
'image'
: image_features
,
'target'
: target
}
(
f
"Dataset Size: {n_samples}"
)
(
f
"Numeric Features: {list(numeric_features.keys())}"
)
(
f
"Categorical Features: {list(categorical_features.keys())}"
)
(
f
"Text Features: {len(text_features)} entries"
)
(
f
"Image Features: {image_features.shape}"
)
(
f
"Target Variable: {np.bincount(target)}"
)
return
dataset
def
process_multimodal_data
(
self
,
dataset
)
:
"""Process Multimodal Data"""
(
"\n=== Multimodal Data Processing ==="
)
processed_features
=
{
}
Process numeric features
numeric_data
=
dataset
[
'numeric'
]
numeric_processed
=
self
.
numeric_processor
.
normalize_data
(
numeric_data
,
method
=
'standard'
)
processed_features
[
'numeric'
]
=
numeric_processed
Process categorical features
categorical_data
=
dataset
[
'categorical'
]
categorical_processed
=
self
.
categorical_processor
.
one_hot_encoding
(
categorical_data
,
list
(
categorical_data.
columns
)
)
Keep only the encoded columns
categorical_encoded
=
categorical_processed.
select_dtypes
(
include
=
[
np.
number
]
)
processed_features
[
'categorical'
]
=
categorical_encoded
Process text features
text_data
=
dataset
[
'text'
]
text_features
,
_
=
self
.
text_processor
.
extract_features
(
text_data
,
method
=
'tfidf'
)
processed_features
[
'text'
]
=
text_features
Process image features
image_data
=
dataset
[
'image'
]
Extract simple image features (mean, standard deviation, etc.)
image_features
=
[
]
for
img
in
image_data:
features
=
self
.
image_processor
.
extract_color_features
(
img
)
feature_vector
=
list
(
features.
values
(
)
)
[
:
10
]
Take the first 10 features
image_features.
append
(
feature_vector
)
processed_features
[
'image'
]
=
np.
array
(
image_features
)
Print processing results
for
modality
,
features
in
processed_features.
items
(
)
:
if
isinstance
(
features
,
pd.
DataFrame
)
:
(
f
"{modality} Features: {features.shape}"
)
else
:
(
f
"{modality} Features: {features.shape}"
)
return
processed_features
def
fuse_features
(
self
,
processed_features
)
:
"""Feature Fusion"""
(
"\n=== Feature Fusion ==="
)
Merge all features
feature_arrays
=
[
]
for
modality
,
features
in
processed_features.
items
(
)
:
if
isinstance
(
features
,
pd.
DataFrame
)
:
feature_arrays.
append
(
features.
values
)
else
:
feature_arrays.
append
(
features
)
Horizontal concatenation
fused_features
=
np.
hstack
(
feature_arrays
)
(
f
"Fused Feature Shape: {fused_features.shape}"
)
return
fused_features
Usage examples
multimodal_processor
=
MultiModalDataProcessor
(
)
Create a multimodal dataset
multimodal_dataset
=
multimodal_processor.
create_multimodal_dataset
(
)
Process multimodal data
processed_multimodal
=
multimodal_processor.
process_multimodal_data
(
multimodal_dataset
)
Feature fusion
fused_features
=
multimodal_processor.
fuse_features
(
processed_multimodal
)