Machine Learning Project Lifecycle
A machine learning project is like building a house: it requires a complete process from design blueprints to construction and then to acceptance, with every link being crucial and indispensable.
The Six Core Stages of the Machine Learning Workflow:
- Problem Definition: Clearly define what problem to solve
- Data Collection: Acquire relevant data
- Data Preparation: Clean and preprocess data
- Model Training: Select an algorithm and train the model
- Model Evaluation: Evaluate model performance
- Model Deployment: Put the model into use

Stage One: Problem Definition
Clarify the Business Problem
Problem definition is the most important starting point of a machine learning project, just as you need to clarify your destination before navigating.
Key Questions
What problem do we want to solve?
- Classification problem: determine whether an email is spam
- Regression problem: predict house prices
- Clustering problem: customer segmentation
- Anomaly detection: detect credit card fraud
Why is this problem important?
- Business value: improve efficiency, reduce costs, increase revenue
- User value: improve experience, provide personalized services
What are the criteria for success?
- Quantitative metric: accuracy above 90%
- Business metric: conversion rate increased by 20%
Problem Definition Example
Example
Problem Definition Example: E-commerce Recommendation System
class
ProblemDefinition:
def
init
(
self
)
:
Business Problem
self
.
business_problem
=
"User purchase conversion rate is low, and recommendation accuracy needs to be improved"
Technical Problem
self
.
technical_problem
=
"Predict products a user is likely to purchase based on user behavior"
Problem Type
self
.
problem_type
=
"Recommendation system (classification + ranking)"
Success Criteria
self
.
success_criteria
=
{
"Improved click-through rate"
:
"15%"
,
"Improved conversion rate"
:
"10%"
,
"Recommendation accuracy"
:
"80%"
}
Constraints
self
.
constraints
=
{
"Response time"
:
"< 100ms"
,
"Data privacy"
:
"Complies with GDPR requirements"
,
"Computing resources"
:
"Existing server configuration"
}
def
define_features_and_labels
(
self
)
:
"""Define features and labels"""
features
=
{
"User features"
:
[
"Age"
,
"Gender"
,
"Purchase history"
,
"Browsing behavior"
]
,
"Product features"
:
[
"Category"
,
"Price"
,
"Rating"
,
"Inventory"
]
,
"Contextual features"
:
[
"time"
,
"Device"
,
"Geographic location"
]
}
labels
=
{
"Primary label"
:
"Whether clicked"
,
"Secondary label"
:
"Whether purchased"
,
"Auxiliary label"
:
"Dwell time"
}
return
features
,
labels
def
print_definition
(
self
)
:
"""Print problem definition"""
(
"="
50
)
(
"Machine Learning Problem Definition"
)
(
"="
50
)
(
f
"Business problem: {self.business_problem}"
)
(
f
"Technical problem: {self.technical_problem}"
)
(
f
"Problem type: {self.problem_type}"
)
(
"\nSuccess criteria:"
)
for
metric
,
target
in
self
.
success_criteria
.
items
(
)
:
(
f
" {metric}:{target}"
)
(
"\nConstraints:"
)
for
constraint
,
limit
in
self
.
constraints
.
items
(
)
:
(
f
" {constraint}:{limit}"
)
features
,
labels
=
self
.
define_features_and_labels
(
)
(
"\nFeature definitions:"
)
for
category
,
items
in
features.
items
(
)
:
(
f
" {category}:{', '.join(items)}"
)
(
"\nLabel definitions:"
)
for
label_type
,
label_name
in
labels.
items
(
)
:
(
f
" {label_type}:{label_name}"
)
Usage examples
problem
=
ProblemDefinition
(
)
problem.
print_definition
(
)
Output:
==================================================
机器学习问题定义
==================================================
业务问题:用户购买转化率低,需要提高推荐精准度
技术问题:基于用户行为预测用户可能购买的商品
问题类型:推荐系统(分类+排序)
Success criteria:
点击率提升:15%
转化率提升:10%
推荐准确率:80%
Constraints:
响应时间:< 100ms
数据隐私:符合 GDPR 要求
计算资源:现有服务器配置
特征定义:
用户特征:年龄, 性别, 购买历史, 浏览行为
商品特征:类别, 价格, 评分, 库存
上下文特征:时间, 设备, 地理位置
标签定义:
主要标签:是否点击
次要标签:是否购买
辅助标签:停留时间
Phase 2: Data Collection
Data Source
Data is the fuel of machine learning, without suitable data, even the best algorithms cannot work.
Common Data Sources
- Internal data: company business data and user behavior data
- External Data: public datasets and third-party data services
- Web scraping: web page data and social media data
- Sensor data: IoT devices and monitoring systems
Data Collection Example
Example
Data collection example: simulating multiple data sources
import
pandas
as
pd
import
numpy
as
np
from
datetime
import
datetime
,
timedelta
class
DataCollector:
def
init
(
self
)
:
self
.
collected_data
=
{
}
def
collect_user_data
(
self
,
n_users
=
1000
)
:
"""Collect user data"""
np.
random
.
seed
(
42
)
user_data
=
{
'user_id'
:
range
(
1
,
n_users +
1
)
,
'age'
: np.
random
.
randint
(
18
,
65
,
n_users
)
,
'gender'
: np.
random
.
choice
(
[
'male'
,
'female'
]
,
n_users
)
,
'city'
: np.
random
.
choice
(
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
n_users
)
,
'registration_date'
:
[
datetime
.
now
(
)
- timedelta
(
days
=
np.
random
.
randint
(
1
,
365
)
)
for
_
in
range
(
n_users
)
]
}
self
.
collected_data
[
'users'
]
=
pd.
DataFrame
(
user_data
)
(
f
"Collected {len(user_data['user_id'])} user records"
)
return
self
.
collected_data
[
'users'
]
def
collect_behavior_data
(
self
,
n_behaviors
=
5000
)
:
"""Collect user behavior data"""
np.
random
.
seed
(
42
)
user_ids
=
np.
random
.
choice
(
range
(
1
,
1001
)
,
n_behaviors
)
product_ids
=
np.
random
.
choice
(
range
(
1
,
501
)
,
n_behaviors
)
behavior_data
=
{
'behavior_id'
:
range
(
1
,
n_behaviors +
1
)
,
'user_id'
: user_ids
,
'product_id'
: product_ids
,
'behavior_type'
: np.
random
.
choice
(
[
'Browse'
,
'Click'
,
'Add to cart'
,
'Purchase'
]
,
n_behaviors
,
p
=
[
0.4
,
0.3
,
0.2
,
0.1
]
)
,
'timestamp'
:
[
datetime
.
now
(
)
- timedelta
(
minutes
=
np.
random
.
randint
(
1
,
10080
)
)
for
_
in
range
(
n_behaviors
)
]
,
'duration'
: np.
random
.
exponential
(
30
,
n_behaviors
)
Dwell time (seconds)
}
self
.
collected_data
[
'behaviors'
]
=
pd.
DataFrame
(
behavior_data
)
(
f
"Collected {len(behavior_data['behavior_id'])} behavior records"
)
return
self
.
collected_data
[
'behaviors'
]
def
collect_product_data
(
self
,
n_products
=
500
)
:
"""Collect product data"""
np.
random
.
seed
(
42
)
categories
=
[
'Electronics'
,
'Clothing'
,
'Food'
,
'Home goods'
,
'Books'
]
product_data
=
{
'product_id'
:
range
(
1
,
n_products +
1
)
,
'category'
: np.
random
.
choice
(
categories
,
n_products
)
,
'price'
: np.
random
.
uniform
(
10
,
1000
,
n_products
)
,
'rating'
: np.
random
.
uniform
(
3.0
,
5.0
,
n_products
)
,
'stock'
: np.
random
.
randint
(
0
,
1000
,
n_products
)
}
self
.
collected_data
[
'products'
]
=
pd.
DataFrame
(
product_data
)
(
f
"Collected {len(product_data['product_id'])} product records"
)
return
self
.
collected_data
[
'products'
]
def
get_data_summary
(
self
)
:
"""Get data summary"""
(
"\nData collection summary:"
)
for
name
,
df
in
self
.
collected_data
.
items
(
)
:
(
f
"\n{name} dataset:"
)
(
f
" Shape: {df.shape}"
)
(
f
" Columns: {list(df.columns)}"
)
(
f
" Missing values: {df.isnull().sum().sum()}"
)
(
f
" Sample data:"
)
(
df.
head
(
2
)
)
Usage examples
collector
=
DataCollector
(
)
collector.
collect_user_data
(
)
collector.
collect_behavior_data
(
)
collector.
collect_product_data
(
)
collector.
get_data_summary
(
)
Phase 3: Data Preparation
The Importance of Data Preparation
Data preparation accounts for 60-80% of the time in a machine learning project, and is as important as the preparation before cooking.
Main Tasks of Data Preparation
- Data cleaning: handle missing values, outliers, and duplicate values
- Feature Engineering: create new features and select important features
- Data Transformation: standardization, normalization, and encoding
- Data Splitting: training set, validation set, and test set
Data Preparation Example
Example
Data Preparation Example
import
pandas
as
pd
import
numpy
as
np
from
sklearn.
preprocessing
import
StandardScaler
,
LabelEncoder
from
sklearn.
model_selection
import
train_test_split
class
DataPreparer:
def
init
(
self
,
data
)
:
self
.
data
=
data.
copy
(
)
self
.
processed_data
=
None
def
clean_data
(
self
)
:
"""Data cleaning"""
(
"Starting data cleaning..."
)
1. Handle missing values
(
f
"Number of missing values before processing: {self.data.isnull().sum().sum()}"
)
Fill numeric columns with the mean.
numeric_columns
=
self
.
data
.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
for
col
in
numeric_columns:
if
self
.
data
[
col
]
.
isnull
(
)
.
sum
(
)
0
:
self
.
data
[
col
]
.
fillna
(
self
.
data
[
col
]
.
mean
(
)
,
inplace
=
True
)
Fill categorical columns with the mode.
categorical_columns
=
self
.
data
.
select_dtypes
(
include
=
[
'object'
]
)
.
columns
for
col
in
categorical_columns:
if
self
.
data
[
col
]
.
isnull
(
)
.
sum
(
)
0
:
mode_val
=
self
.
data
[
col
]
.
mode
(
)
[
0
]
self
.
data
[
col
]
.
fillna
(
mode_val
,
inplace
=
True
)
(
f
"Number of missing values after processing: {self.data.isnull().sum().sum()}"
)
2. Handle duplicate values
duplicates_before
=
self
.
data
.
duplicated
(
)
.
sum
(
)
self
.
data
.
drop_duplicates
(
inplace
=
True
)
duplicates_after
=
self
.
data
.
duplicated
(
)
.
sum
(
)
(
f
"Duplicates removed: {duplicates_before - duplicates_after} records"
)
3. Handle outliers (simple method: using IQR)
for
col
in
numeric_columns:
Q1
=
self
.
data
[
col
]
.
quantile
(
0.25
)
Q3
=
self
.
data
[
col
]
.
quantile
(
0.75
)
IQR
=
Q3 - Q1
lower_bound
=
Q1 -
1.5
- IQR
upper_bound
=
Q3 +
1.5
- IQR
outliers
=
(
(
self
.
data
[
col
]
<
lower_bound
)
|
(
self.
data
[
col
]
upper_bound
)
)
.
sum
(
)
if
outliers
0
:
Replace outliers with boundary values
self
.
data
[
col
]
=
self
.
data
[
col
]
.
clip
(
lower_bound
,
upper_bound
)
(
f
"Handle {outliers} outliers in column {col}"
)
return
self
.
data
def
feature_engineering
(
self
)
:
"""Feature Engineering"""
(
"\nStarting feature engineering..."
)
1. Create new features (example)
if
'price'
in
self
.
data
.
columns
and
'rating'
in
self
.
data
.
columns
:
Create a cost-effectiveness feature
self
.
data
[
'price_per_rating'
]
=
self
.
data
[
'price'
]
/
self
.
data
[
'rating'
]
(
"Create new feature: price_per_rating"
)
2. Feature selection (simple example: removing low-variance features)
numeric_columns
=
self
.
data
.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
low_variance_features
=
[
]
for
col
in
numeric_columns:
if
self
.
data
[
col
]
.
var
(
)
<
0.01
:
Variance threshold
low_variance_features.
append
(
col
)
if
low_variance_features:
self
.
data
.
drop
(
columns
=
low_variance_features
,
inplace
=
True
)
(
f
"Remove low-variance features: {low_variance_features}"
)
return
self
.
data
def
transform_data
(
self
)
:
"""Data transformation"""
(
"\nStarting data transformation..."
)
1. Encode categorical variables
categorical_columns
=
self
.
data
.
select_dtypes
(
include
=
[
'object'
]
)
.
columns
label_encoders
=
{
}
for
col
in
categorical_columns:
le
=
LabelEncoder
(
)
self
.
data
[
col
]
=
le.
fit_transform
(
self
.
data
[
col
]
)
label_encoders
[
col
]
=
le
(
f
"Encode categorical variable: {col}"
)
2. Standardize numerical variables
numeric_columns
=
self
.
data
.
select_dtypes
(
include
=
[
np.
number
]
)
.
columns
scaler
=
StandardScaler
(
)
if
len
(
numeric_columns
)
0
:
self
.
data
[
numeric_columns
]
=
scaler.
fit_transform
(
self
.
data
[
numeric_columns
]
)
(
f
"Standardize numerical variables: {list(numeric_columns)}"
)
return
self
.
data
,
label_encoders
,
scaler
def
split_data
(
self
,
target_column
,
test_size
=
0.2
,
val_size
=
0.2
)
:
"""Data splitting"""
(
f
"\nStarting data splitting (test set ratio: {test_size}, validation set ratio: {val_size})..."
)
X
=
self
.
data
.
drop
(
columns
=
[
target_column
]
)
y
=
self
.
data
[
target_column
]
First, separate out the test set
X_temp
,
X_test
,
y_temp
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
test_size
,
random_state
=
42
)
Then separate the validation set from the remaining data
val_size_adjusted
=
val_size /
(
1
- test_size
)
X_train
,
X_val
,
y_train
,
y_val
=
train_test_split
(
X_temp
,
y_temp
,
test_size
=
val_size_adjusted
,
random_state
=
42
)
(
f
"Training set size: {X_train.shape[0]}"
)
(
f
"Validation set size: {X_val.shape[0]}"
)
(
f
"Test set size: {X_test.shape[0]}"
)
return
{
'X_train'
: X_train
,
'y_train'
: y_train
,
'X_val'
: X_val
,
'y_val'
: y_val
,
'X_test'
: X_test
,
'y_test'
: y_test
}
def
prepare_pipeline
(
self
,
target_column
)
:
"""Complete data preparation pipeline"""
(
"="
50
)
(
"Data Preparation Pipeline"
)
(
"="
50
)
1. Data cleaning
self
.
clean_data
(
)
2. Feature engineering
self
.
feature_engineering
(
)
3. Data transformation
processed_data
,
encoders
,
scaler
=
self
.
transform_data
(
)
4. Data splitting
splits
=
self
.
split_data
(
target_column
)
self
.
processed_data
=
processed_data
return
splits
,
encoders
,
scaler
Create sample data and demonstrate data preparation
np.
random
.
seed
(
42
)
sample_data
=
pd.
DataFrame
(
{
'age'
: np.
random
.
randint
(
18
,
65
,
1000
)
,
'income'
: np.
random
.
normal
(
50000
,
15000
,
1000
)
,
'gender'
: np.
random
.
choice
(
[
'male'
,
'female'
]
,
1000
)
,
'city'
: np.
random
.
choice
(
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
]
,
1000
)
,
'target'
: np.
random
.
choice
(
[
0
,
1
]
,
1000
)
}
)
Add some missing values and outliers
sample_data.
loc
[
np.
random
.
choice
(
1000
,
50
)
,
'income'
]
=
np.
nan
sample_data.
loc
[
np.
random
.
choice
(
1000
,
20
)
,
'age'
]
=
np.
random
.
randint
(
100
,
150
)
preparer
=
DataPreparer
(
sample_data
)
splits
,
encoders
,
scaler
=
preparer.
prepare_pipeline
(
'target'
)
hr>
Phase 4: Model Training
Model Selection Strategy
Choosing the right model is the key to success, just like choosing the right tool for the job.
Model Selection Considerations
- Problem Type: classification, regression, clustering, etc.
- Data characteristics: data volume, number of features, data types
- Performance requirements: accuracy, speed, interpretability
- Resource constraints: computing resources, time constraints
Model Training Example
Example
Model Training Example
from
sklearn.
linear_model
import
LogisticRegression
,
LinearRegression
from
sklearn.
ensemble
import
RandomForestClassifier
,
RandomForestRegressor
from
sklearn.
svm
import
SVC
,
SVR
from
sklearn.
metrics
import
accuracy_score
,
mean_squared_error
,
classification_report
class
ModelTrainer:
def
init
(
self
)
:
self
.
models
=
{
}
self
.
trained_models
=
{
}
def
register_model
(
self
,
name
,
model
,
problem_type
)
:
"""Register a model"""
self
.
models
[
name
]
=
{
'model'
: model
,
'problem_type'
: problem_type
}
(
f
"Register model: {name} ({problem_type})"
)
def
train_single_model
(
self
,
name
,
X_train
,
y_train
)
:
"""Train a single model"""
if
name
not
in
self
.
models
:
raise
ValueError
(
f
"Model {name} is not registered"
)
model_info
=
self
.
models
[
name
]
model
=
model_info
[
'model'
]
(
f
"\nTraining model: {name}"
)
model.
fit
(
X_train
,
y_train
)
self
.
trained_models
[
name
]
=
model
(
f
"Model {name} training complete"
)
return
model
def
train_all_models
(
self
,
X_train
,
y_train
)
:
"""Train all registered models"""
(
"\nStarting training for all models..."
)
for
name
in
self
.
models
.
keys
(
)
:
try
:
self
.
train_single_model
(
name
,
X_train
,
y_train
)
except
Exception
as
e:
(
f
"Error training model {name}: {e}"
)
return
self
.
trained_models
def
evaluate_models
(
self
,
X_test
,
y_test
)
:
"""Evaluate all trained models"""
(
"\nModel evaluation results:"
)
(
"-"
50
)
results
=
{
}
for
name
,
model
in
self
.
trained_models
.
items
(
)
:
problem_type
=
self
.
models
[
name
]
[
'problem_type'
]
Predict
y_pred
=
model.
predict
(
X_test
)
Select evaluation metrics based on the problem type
if
problem_type
==
'classification'
:
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
results
[
name
]
=
{
'accuracy'
: accuracy
}
(
f
"{name}: accuracy = {accuracy:.4f}"
)
Detailed report
(
classification_report
(
y_test
,
y_pred
)
)
elif
problem_type
==
'regression'
:
mse
=
mean_squared_error
(
y_test
,
y_pred
)
rmse
=
np.
sqrt
(
mse
)
results
[
name
]
=
{
'mse'
: mse
,
'rmse'
: rmse
}
(
f
"{name}: MSE = {mse:.4f}, RMSE = {rmse:.4f}"
)
(
"-"
50
)
return
results
def
get_best_model
(
self
,
results
,
metric
=
'accuracy'
)
:
"""Get the best model"""
if
not
results:
return
None
best_model_name
=
max
(
results.
keys
(
)
,
key
=
lambda
x: results
[
x
]
.
get
(
metric
,
0
)
)
best_score
=
results
[
best_model_name
]
[
metric
]
(
f
"\nBest model: {best_model_name} ({metric} = {best_score:.4f})"
)
return
best_model_name
,
self
.
trained_models
[
best_model_name
]
Usage examples
trainer
=
ModelTrainer
(
)
Register different types of models
trainer.
register_model
(
'Logistic Regression'
,
LogisticRegression
(
random_state
=
42
)
,
'classification'
)
trainer.
register_model
(
'Random Forest'
,
RandomForestClassifier
(
n_estimators
=
100
,
random_state
=
42
)
,
'classification'
)
trainer.
register_model
(
'Support Vector Machine'
,
SVC
(
random_state
=
42
)
,
'classification'
)
Create training data
X_train
=
splits
[
'X_train'
]
y_train
=
splits
[
'y_train'
]
X_test
=
splits
[
'X_test'
]
y_test
=
splits
[
'y_test'
]
Train all models
trained_models
=
trainer.
train_all_models
(
X_train
,
y_train
)
Evaluate the model
results
=
trainer.
evaluate_models
(
X_test
,
y_test
)
Get the best model
best_name
,
best_model
=
trainer.
get_best_model
(
results
)
Phase 5: Model Evaluation
Evaluation Metric Selection
Choosing the right evaluation metric is like choosing the right ruler, as different metrics suit different scenarios.
Common evaluation metrics
Classification problems:
- Accuracy: the proportion of correct predictions
- Precision: the proportion of samples predicted positive that are actually positive
- Recall: the proportion of actually positive samples that are correctly predicted as positive
- F1 score: the harmonic mean of precision and recall
Regression problems:
- Mean Squared Error (MSE): the average of the squared differences between predicted and true values
- Root Mean Squared Error (RMSE): the square root of MSE
- Mean Absolute Error (MAE): the average of the absolute differences between predicted and true values
- R² score: the proportion of variance explained by the model
Model Evaluation Example
Example
Model Evaluation Example
import
matplotlib.
pyplot
as
plt
from
sklearn.
metrics
import
(
accuracy_score
,
precision_score
,
recall_score
,
f1_score
,
confusion_matrix
,
roc_curve
,
auc
)
class
ModelEvaluator:
def
init
(
self
)
:
self
.
evaluation_results
=
{
}
def
evaluate_classification
(
self
,
y_true
,
y_pred
,
y_prob
=
None
,
model_name
=
"Model"
)
:
"""Evaluate a classification model"""
results
=
{
}
Basic metrics
results
[
'accuracy'
]
=
accuracy_score
(
y_true
,
y_pred
)
results
[
'precision'
]
=
precision_score
(
y_true
,
y_pred
,
average
=
'weighted'
)
results
[
'recall'
]
=
recall_score
(
y_true
,
y_pred
,
average
=
'weighted'
)
results
[
'f1'
]
=
f1_score
(
y_true
,
y_pred
,
average
=
'weighted'
)
(
f
"\n{model_name} classification evaluation results:"
)
(
f
"Accuracy: {results['accuracy']:.4f}"
)
(
f
"Precision: {results['precision']:.4f}"
)
(
f
"Recall: {results['recall']:.4f}"
)
(
f
"F1 score: {results['f1']:.4f}"
)
Confusion matrix
cm
=
confusion_matrix
(
y_true
,
y_pred
)
(
f
"\nConfusion matrix:"
)
(
cm
)
ROC curve (if probability predictions are available)
if
y_prob
is
not
None
and
len
(
np.
unique
(
y_true
)
)
==
2
:
fpr
,
tpr
,
thresholds
=
roc_curve
(
y_true
,
y_prob
[
:
,
1
]
)
roc_auc
=
auc
(
fpr
,
tpr
)
results
[
'roc_auc'
]
=
roc_auc
Plot the ROC curve
plt.
figure
(
figsize
=
(
8
,
6
)
)
plt.
plot
(
fpr
,
tpr
,
color
=
'darkorange'
,
lw
=
2
,
label
=
f
'ROC curve (AUC = {roc_auc:.2f})'
)
plt.
plot
(
[
0
,
1
]
,
[
0
,
1
]
,
color
=
'navy'
,
lw
=
2
,
linestyle
=
'--'
)
plt.
xlim
(
[
0.0
,
1.0
]
)
plt.
ylim
(
[
0.0
,
1.05
]
)
plt.
xlabel
(
'False Positive Rate'
)
plt.
ylabel
(
'True Positive Rate'
)
plt.
title
(
f
'{model_name} ROC curve'
)
plt.
legend
(
loc
=
"lower right"
)
plt.
grid
(
True
)
plt.
show
(
)
self
.
evaluation_results
[
model_name
]
=
results
return
results
def
evaluate_regression
(
self
,
y_true
,
y_pred
,
model_name
=
"Model"
)
:
"""Evaluate a regression model"""
results
=
{
}
Basic metrics
mse
=
np.
mean
(
(
y_true - y_pred
)
**
2
)
rmse
=
np.
sqrt
(
mse
)
mae
=
np.
mean
(
np.
abs
(
y_true - y_pred
)
)
R² score
ss_res
=
np.
sum
(
(
y_true - y_pred
)
**
2
)
ss_tot
=
np.
sum
(
(
y_true - np.
mean
(
y_true
)
)
**
2
)
r2
=
1
(
ss_res / ss_tot
)
results
[
'mse'
]
=
mse
results
[
'rmse'
]
=
rmse
results
[
'mae'
]
=
mae
results
[
'r2'
]
=
r2
(
f
"\n{model_name} regression evaluation results:"
)
(
f
"Mean Squared Error (MSE): {mse:.4f}"
)
(
f
"Root Mean Squared Error (RMSE): {rmse:.4f}"
)
(
f
"Mean Absolute Error (MAE): {mae:.4f}"
)
(
f
"R² score: {r2:.4f}"
)
Plot predicted vs. true values
plt.
figure
(
figsize
=
(
8
,
6
)
)
plt.
scatter
(
y_true
,
y_pred
,
alpha
=
0.6
)
plt.
plot
(
[
y_true.
min
(
)
,
y_true.
max
(
)
]
,
[
y_true.
min
(
)
,
y_true.
max
(
)
]
,
'r--'
,
lw
=
2
)
plt.
xlabel
(
'True values'
)
plt.
ylabel
(
'Predicted values'
)
plt.
title
(
f
'{model_name} predicted vs. true values'
)
plt.
grid
(
True
)
plt.
show
(
)
self
.
evaluation_results
[
model_name
]
=
results
return
results
def
compare_models
(
self
)
:
"""Compare all evaluated models"""
if
not
self
.
evaluation_results
:
(
"No model evaluation results to compare"
)
return
(
"\nModel comparison:"
)
(
"-"
50
)
Create a comparison table
comparison_data
=
[
]
for
model_name
,
results
in
self
.
evaluation_results
.
items
(
)
:
row
=
[
model_name
]
for
metric
,
value
in
results.
items
(
)
:
row.
append
(
f
"{value:.4f}"
)
comparison_data.
append
(
row
)
Print the table
headers
=
[
"Model name"
]
list
(
self
.
evaluation_results
.
values
(
)
)
[
0
]
.
keys
(
)
(
"\t"
.
join
(
headers
)
)
for
row
in
comparison_data:
(
"\t"
.
join
(
row
)
)
Usage examples
evaluator
=
ModelEvaluator
(
)
Evaluate classification models
y_pred_class
=
best_model.
predict
(
X_test
)
y_prob_class
=
best_model.
predict_proba
(
X_test
)
evaluator.
evaluate_classification
(
y_test
,
y_pred_class
,
y_prob_class
,
"Best classification model"
)
Compare all models
evaluator.
compare_models
(
)
Phase 6: Model Deployment
Deployment Strategies
Model deployment is the process of putting a model into practical use, just like bringing a developed product to market.
Deployment method
- Batch prediction: process large amounts of data regularly
- Real-time prediction: online service with immediate response
- Embedded deployment: integrate the model into existing systems
- Edge deployment: run the model on the device
Model Deployment Example
Example
Model Deployment Example
import
pickle
import
json
from
datetime
import
datetime
class
ModelDeployer:
def
init
(
self
)
:
self
.
deployed_models
=
{
}
self
.
deployment_logs
=
[
]
def
save_model
(
self
,
model
,
model_name
,
filepath
=
None
)
:
"""Save the model"""
if
filepath
is
None
:
filepath
=
f
"{model_name}.pkl"
with
open
(
filepath
,
'wb'
)
as
f:
pickle
.
dump
(
model
,
f
)
(
f
"Model {model_name} saved to {filepath}"
)
Log the deployment
log_entry
=
{
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
,
'action'
:
'save_model'
,
'model_name'
: model_name
,
'filepath'
: filepath
}
self
.
deployment_logs
.
append
(
log_entry
)
return
filepath
def
load_model
(
self
,
model_name
,
filepath
)
:
"""Load the model"""
with
open
(
filepath
,
'rb'
)
as
f:
model
=
pickle
.
load
(
f
)
self
.
deployed_models
[
model_name
]
=
model
(
f
"Model {model_name} loaded from {filepath}"
)
Log the deployment
log_entry
=
{
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
,
'action'
:
'load_model'
,
'model_name'
: model_name
,
'filepath'
: filepath
}
self
.
deployment_logs
.
append
(
log_entry
)
return
model
def
create_prediction_service
(
self
,
model_name
,
encoders
=
None
,
scaler
=
None
)
:
"""Create a prediction service"""
if
model_name
not
in
self
.
deployed_models
:
raise
ValueError
(
f
"Model {model_name} is not deployed"
)
model
=
self
.
deployed_models
[
model_name
]
def
predict_service
(
input_data
)
:
"""Prediction service function"""
try
:
Data preprocessing
if
encoders:
for
col
,
encoder
in
encoders.
items
(
)
:
if
col
in
input_data.
columns
:
input_data
[
col
]
=
encoder.
transform
(
input_data
[
col
]
)
if
scaler:
numeric_cols
=
input_data.
select_dtypes
(
include
=
[
'number'
]
)
.
columns
input_data
[
numeric_cols
]
=
scaler.
transform
(
input_data
[
numeric_cols
]
)
Predict
prediction
=
model.
predict
(
input_data
)
If it is a classification model, also return the probability
if
hasattr
(
model
,
'predict_proba'
)
:
probability
=
model.
predict_proba
(
input_data
)
return
{
'prediction'
: prediction.
tolist
(
)
,
'probability'
: probability.
tolist
(
)
,
'status'
:
'success'
,
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
}
else
:
return
{
'prediction'
: prediction.
tolist
(
)
,
'status'
:
'success'
,
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
}
except
Exception
as
e:
return
{
'error'
:
str
(
e
)
,
'status'
:
'error'
,
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
}
Log the service creation
log_entry
=
{
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
,
'action'
:
'create_service'
,
'model_name'
: model_name
}
self
.
deployment_logs
.
append
(
log_entry
)
return
predict_service
def
monitor_model
(
self
,
model_name
,
input_data
,
true_labels
=
None
)
:
"""Monitor model performance"""
if
model_name
not
in
self
.
deployed_models
:
raise
ValueError
(
f
"Model {model_name} is not deployed"
)
predict_service
=
self
.
create_prediction_service
(
model_name
)
Get prediction results
result
=
predict_service
(
input_data
)
Monitoring information
monitoring_info
=
{
'timestamp'
:
datetime
.
now
(
)
.
isoformat
(
)
,
'model_name'
: model_name
,
'input_shape'
: input_data.
shape
,
'prediction_count'
:
len
(
result.
get
(
'prediction'
,
[
]
)
)
,
'status'
: result.
get
(
'status'
,
'unknown'
)
}
If true labels are available, calculate performance metrics
if
true_labels
is
not
None
and
'prediction'
in
result:
predictions
=
result
[
'prediction'
]
if
len
(
predictions
)
==
len
(
true_labels
)
:
accuracy
=
accuracy_score
(
true_labels
,
predictions
)
monitoring_info
[
'accuracy'
]
=
accuracy
(
"Model monitoring information:"
)
for
key
,
value
in
monitoring_info.
items
(
)
:
(
f
" {key}: {value}"
)
return
monitoring_info
def
get_deployment_logs
(
self
)
:
"""Get deployment logs"""
return
self
.
deployment_logs
Usage examples
deployer
=
ModelDeployer
(
)
Save the best model
model_path
=
deployer.
save_model
(
best_model
,
"best_classification_model"
)
Load model
deployer.
load_model
(
"best_classification_model"
,
model_path
)
Create a prediction service
prediction_service
=
deployer.
create_prediction_service
(
"best_classification_model"
,
encoders
,
scaler
)
Use the prediction service
test_input
=
X_test.
head
(
5
)
prediction_result
=
prediction_service
(
test_input
)
(
"\nPrediction results:"
)
(
json.
dumps
(
prediction_result
,
indent
=
2
,
ensure_ascii
=
False
)
)
Monitor the model
deployer.
monitor_model
(
"best_classification_model"
,
test_input
,
y_test.
head
(
5
)
.
values
)
Complete Workflow Example
Example
A complete machine learning workflow example
class
MLProjectPipeline:
def
init
(
self
)
:
self
.
data_collector
=
DataCollector
(
)
self
.
data_preparer
=
None
self
.
model_trainer
=
ModelTrainer
(
)
self
.
model_evaluator
=
ModelEvaluator
(
)
self
.
model_deployer
=
ModelDeployer
(
)
def
run_complete_pipeline
(
self
,
target_column
)
:
"""Run the complete machine learning pipeline"""
(
"="
60
)
(
"Complete Machine Learning Project Workflow"
)
(
"="
60
)
1. Data Collection
(
"\nStep 1: Data Collection"
)
(
"-"
30
)
user_data
=
self
.
data_collector
.
collect_user_data
(
1000
)
behavior_data
=
self
.
data_collector
.
collect_behavior_data
(
5000
)
Merge the data (simplified example)
merged_data
=
pd.
merge
(
user_data
,
behavior_data
,
on
=
'user_id'
,
how
=
'inner'
)
Create the target variable (example: whether purchased)
merged_data
[
'purchased'
]
=
(
merged_data
[
'behavior_type'
]
==
'Purchase'
)
.
astype
(
int
)
2. Data preparation
(
"\nStep 2: Data Preparation"
)
(
"-"
30
)
Select feature columns
feature_columns
=
[
'age'
,
'gender'
,
'city'
,
'duration'
]
if
all
(
col
in
merged_data.
columns
for
col
in
feature_columns
)
:
data_for_ml
=
merged_data
[
feature_columns +
[
'purchased'
]
]
.
copy
(
)
Handle categorical variables
data_for_ml
[
'gender'
]
=
data_for_ml
[
'gender'
]
.
map
(
{
'male'
:
0
,
'female'
:
1
}
)
data_for_ml
[
'city'
]
=
data_for_ml
[
'city'
]
.
map
(
{
'Beijing'
:
0
,
'Shanghai'
:
1
,
'Guangzhou'
:
2
}
)
Data preparation
self
.
data_preparer
=
DataPreparer
(
data_for_ml
)
splits
,
encoders
,
scaler
=
self
.
data_preparer
.
prepare_pipeline
(
'purchased'
)
3. Model Training
(
"\nStep 3: Model Training"
)
(
"-"
30
)
Register models
self
.
model_trainer
.
register_model
(
'Logistic Regression'
,
LogisticRegression
(
random_state
=
42
)
,
'classification'
)
self
.
model_trainer
.
register_model
(
'Random Forest'
,
RandomForestClassifier
(
n_estimators
=
100
,
random_state
=
42
)
,
'classification'
)
Train the model
trained_models
=
self
.
model_trainer
.
train_all_models
(
splits
[
'X_train'
]
,
splits
[
'y_train'
]
)
4. Model Evaluation
(
"\nStep 4: Model Evaluation"
)
(
"-"
30
)
results
=
self
.
model_trainer
.
evaluate_models
(
splits
[
'X_test'
]
,
splits
[
'y_test'
]
)
best_name
,
best_model
=
self
.
model_trainer
.
get_best_model
(
results
)
5. Model deployment
(
"\nStep 5: Model Deployment"
)
(
"-"
30
)
Save the model
model_path
=
self
.
model_deployer
.
save_model
(
best_model
,
"production_model"
)
Create a prediction service
prediction_service
=
self
.
model_deployer
.
create_prediction_service
(
"production_model"
)
Test the prediction service
test_input
=
splits
[
'X_test'
]
.
head
(
3
)
prediction_result
=
prediction_service
(
test_input
)
(
"\nPrediction service test results:"
)
(
json.
dumps
(
prediction_result
,
indent
=
2
,
ensure_ascii
=
False
)
)
(
"\n"
"="
60
)
(
"Machine learning project workflow complete!"
)
(
"="
60
)
return
{
'data'
: data_for_ml
,
'splits'
: splits
,
'best_model'
: best_model
,
'best_model_name'
: best_name
,
'evaluation_results'
: results
,
'prediction_service'
: prediction_service
}
else
:
(
"Data columns are incomplete; cannot continue the workflow"
)
return
None
Run the complete workflow
pipeline
=
MLProjectPipeline
(
)
project_results
=
pipeline.
run_complete_pipeline
(
'purchased'
)