TensorFlow Model Evaluation and Monitoring
I. Basic Concepts of Model Evaluation
In machine learning projects, model evaluation is a critical step to validate model performance. It helps us understand how the model behaves in real-world scenarios and guides us in model optimization.
1.1 Why Model Evaluation Is Needed
- Performance validation: Confirm whether the model meets expected results
- Model selection: Compare the strengths and weaknesses of different models
- Parameter tuning: Guide the direction of hyperparameter tuning
- Avoid overfitting: Detect whether the model is overfitted to the training data
1.2 Types of Evaluation Metrics
| Metric type | Applicable scenarios | Common metrics |
|---|---|---|
| Classification metrics | Classification problems | Accuracy, precision, recall, F1 score |
| Regression metrics | Regression problems | MSE、MAE、R² |
| Clustering metrics | Unsupervised learning | Silhouette coefficient, Davies-Bouldin index |
II. TensorFlow Evaluation Tools
TensorFlow provides a variety of tools and methods to evaluate model performance.
2.1 Built-in Evaluation Metrics
Example
import
tensorflow
as
tf
Common classification metrics
metrics
=
[
tf.
keras
.
metrics
.
BinaryAccuracy
(
)
,
tf.
keras
.
metrics
.
Precision
(
)
,
tf.
keras
.
metrics
.
Recall
(
)
,
tf.
keras
.
metrics
.
AUC
(
)
]
Common regression metrics
metrics
=
[
tf.
keras
.
metrics
.
MeanSquaredError
(
)
,
tf.
keras
.
metrics
.
MeanAbsoluteError
(
)
,
tf.
keras
.
metrics
.
RootMeanSquaredError
(
)
]
2.2 Evaluation Process
1. Specify metrics when compiling the model
Example
model.
compile
(
optimizer
=
'adam'
,
loss
=
'binary_crossentropy'
,
metrics
=
[
'accuracy'
,
tf.
keras
.
metrics
.
AUC
(
)
]
)
2. Evaluate using the evaluate method
Example
test_loss
,
test_acc
,
test_auc
=
model.
evaluate
(
test_images
,
test_labels
,
verbose
=
2
)
3. Custom evaluation functions
Example
import
tensorflow
as
tf
@
tf.
function
def
custom_metric
(
y_true
,
y_pred
)
:
threshold
=
0.5
y_pred
=
tf.
cast
(
y_pred
threshold
,
tf.
float32
)
Calculate accuracy, not just the positive-example ratio
correct_predictions
=
tf.
cast
(
tf.
equal
(
y_true
,
y_pred
)
,
tf.
float32
)
return
tf.
reduce_mean
(
correct_predictions
)
model.
compile
(
optimizer
=
'adam'
,
loss
=
'binary_crossentropy'
,
metrics
=
[
custom_metric
,
'accuracy'
]
You can keep the standard accuracy metric as a reference at the same time
)
III. Model Monitoring and Visualization
1. TensorBoard Integration
TensorBoard is TensorFlow's visualization tool that can monitor the training process in real time.
Example
Set up callbacks
tensorboard_callback
=
tf.
keras
.
callbacks
.
TensorBoard
(
log_dir
=
&
#39;./logs',
histogram_freq
=
1
,
write_graph
=
True
,
write_images
=
True
)
Add callbacks when training the model
model.
fit
(
train_data
,
epochs
=
10
,
validation_data
=
val_data
,
callbacks
=
[
tensorboard_callback
]
)
Launch TensorBoard:
tensorboard --logdir=./logs
2. Key Metrics to Monitor

IV. Advanced Evaluation Techniques
4.1 Cross-Validation
Example
from
sklearn.
model_selection
import
KFold
import
numpy
as
np
Prepare data
X
=
np.
array
(
...
)
y
=
np.
array
(
...
)
5-fold cross-validation
kfold
=
KFold
(
n_splits
=
5
,
shuffle
=
True
)
fold_no
=
1
for
train
,
test
in
kfold.
split
(
X
,
y
)
:
Create the model
model
=
create_model
(
)
Train the model
model.
fit
(
X
[
train
]
,
y
[
train
]
,
epochs
=
10
)
Evaluate the model
scores
=
model.
evaluate
(
X
[
test
]
,
y
[
test
]
)
(
f
'Fold {fold_no} - {model.metrics_names[0]}: {scores[0]}'
)
fold_no +
=
1
4.2 Confusion Matrix Analysis
Example
from
sklearn.
metrics
import
confusion_matrix
import
seaborn
as
sns
import
matplotlib.
pyplot
as
plt
Get prediction results
y_pred
=
model.
predict
(
test_images
)
y_pred_classes
=
np.
argmax
(
y_pred
,
axis
=
1
)
Generate the confusion matrix
conf_mat
=
confusion_matrix
(
test_labels
,
y_pred_classes
)
Visualization
plt.
figure
(
figsize
=
(
10
,
8
)
)
sns.
heatmap
(
conf_mat
,
annot
=
True
,
fmt
=
'd'
)
plt.
xlabel
(
'Predicted'
)
plt.
ylabel
(
'Actual'
)
plt.
show
(
)
V. Post-Deployment Monitoring
5.1 Key Points of Production Monitoring
- Data drift detection: Monitor changes in the input data distribution
- Concept drift detection: Monitor changes in the feature-target relationship
- Performance degradation detection: Regularly evaluate model performance
- Anomalous input detection: Identify abnormal input samples
5.2 Monitoring System Architecture

VI. Practical exercises
6.1 Exercises
- Train a simple CNN model on the MNIST dataset
- Implement the following evaluation features:
- Try implementing custom evaluation metrics
6.2 Reference Code Framework
Example
import
tensorflow
as
tf
from
tensorflow.
keras
import
layers
1. Data Preparation
(
train_images
,
train_labels
)
,
(
test_images
,
test_labels
)
=
tf.
keras
.
datasets
.
mnist
.
load_data
(
)
train_images
=
train_images.
reshape
(
(
60000
,
28
,
28
,
1
)
)
.
astype
(
'float32'
)
/
255
test_images
=
test_images.
reshape
(
(
10000
,
28
,
28
,
1
)
)
.
astype
(
'float32'
)
/
255
2. Model building
model
=
tf.
keras
.
Sequential
(
[
layers.
Conv2D
(
32
,
(
3
,
3
)
,
activation
=
'relu'
,
input_shape
=
(
28
,
28
,
1
)
)
,
layers.
MaxPooling2D
(
(
2
,
2
)
)
,
layers.
Flatten
(
)
,
layers.
Dense
(
10
,
activation
=
'softmax'
)
]
)
3. Compile the model (add the metrics of your choice)
model.
compile
(
...
)
4. Train the model (add TensorBoard callbacks)
history
=
model.
fit
(
...
)
5. Evaluate the model
test_loss
,
test_acc
=
model.
evaluate
(
...
)