Troubleshooting common problems
As machine learning projects move from lab prototypes to production environments, they often encounter a series of unexpected challenges.
A model performs excellently on the training set but poorly after actual deployment, or even fails completely—this is a dilemma experienced by many machine learning engineers and beginners.
This article systematically reviews the most common types of problems encountered during the optimization and engineering of machine learning models, and provides clear troubleshooting ideas and solutions to help you build more robust and reliable machine learning systems.
I. Model Performance Issues: Good in Training, Poor in Production
This is the most classic and most headache-inducing problem. Your model achieves 95% accuracy in a Jupyter Notebook, but once deployed online, its performance plummets.
1. Inconsistent Data Distribution
This is the "number one killer" causing performance degradation. There are differences in the statistical distribution between the training data and the online real-time data.
Common Scenarios and Troubleshooting Points:
Inconsistent Feature Engineering: The code for offline feature processing (such as normalization, binning, and missing value imputation) is not completely consistent with the online service code.
StandardScaler) uses the parameters fitted offline on the online side (scaler.mean_, scaler.scale_), rather than being re-fitted.Data Collection Time Bias: The training data is from the past three months, while the online data comes from the present; user behavior and market conditions may have changed (concept drift).
Sample selection bias: The training data is not representative of all users. For example, training a recommendation model using only data from active users will fail for new or inactive users.
Solutions: Establish a comprehensivedata monitoringandmodel monitoringsystem. Not only should you monitor the model's outputs (such as AUC and accuracy), but even more so the distribution of input features. Once drift is detected, an alert should be triggered and updating the training data or retraining the model should be considered.
Example
Example: Using a Sliding Window to Monitor Feature Mean Drift
import
numpy
as
np
import
pandas
as
pd
Suppose these are the values of the feature "feature_a" received online in real time
online_feature_values
=
[
0.1
,
0.5
,
1.2
,
0.8
,
1.5
,
2.0
,
2.5
]
training_mean
=
0.5
The mean of "feature_a" on the training set
training_std
=
0.3
The standard deviation of "feature_a" on the training set
current_online_mean
=
np.
mean
(
online_feature_values
[
100
:
]
)
The mean of the most recent 100 points
Compute the Z-score to simply determine whether significant drift has occurred
z_score
=
(
current_online_mean - training_mean
)
/ training_std
(
f
"Current online feature mean: {current_online_mean:.3f}"
)
(
f
"Z-score with respect to the training set mean: {z_score:.3f}"
)
if
abs
(
z_score
)
3
:
Threshold, for example 3 standard deviations
(
"Warning: Possible distribution drift detected for feature 'feature_a'!"
)
2. Data Leakage
The model "peeks" at information that should only be known at prediction time during training, leading to inflated evaluation results.
Common Scenarios:
- Before splitting the training/test set,,global normalization or missing value imputation was performed (using information from the test set).
- In time series problems, using future data to predict the past.
- Features contain "future information" that is strongly correlated with the target variable (for example, using "whether a complaint was received today" to predict "whether the order will be cancelled today").
Troubleshooting and Solutions: Strictly follow the machine learning workflow.Any operation that learns parameters from data (such as fitting a Scaler, imputing missing values, and feature selection) must be performed on the training set, and then these parameters should be used only to transform the validation and test sets. Use sklearn 's Pipeline can effectively avoid this problem.
Example
Incorrect Example: Process globally first, then split the dataset (causing data leakage)
from
sklearn.
preprocessing
import
StandardScaler
from
sklearn.
model_selection
import
train_test_split
X, y are the raw data and labels
scaler
=
StandardScaler
(
)
X_scaled
=
scaler.
fit_transform
(
X
)
Wrong! All the data was used here to fit the scaler
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X_scaled
,
y
,
test_size
=
0.2
)
At this point, the information from X_test has "leaked" into the scaler, thereby affecting the transformation of X_train
Correct Example: Split first, then process separately
X_train_raw
,
X_test_raw
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
)
scaler
=
StandardScaler
(
)
X_train
=
scaler.
fit_transform
(
X_train_raw
)
Fit using only the training set
X_test
=
scaler.
transform
(
X_test_raw
)
Transform the test set using the parameters fitted on the training set
II. Engineering and Deployment Issues
Turning a model from a file into a stable, highly available API involves countless pitfalls along the way.
1. Environment Dependencies and Version Conflicts
"It works on my machine!"—a classic problem. The Python version and library versions of the training environment and the online inference environment are inconsistent.
Troubleshooting Checklist:
- Python major version (3.7 vs 3.9)
- Core library versions (
tensorflow==2.8vstensorflow==2.12) - System dependencies (such as certain libraries depending on specific C++ runtime libraries)
- Model serialization format (models saved with
pickle, if the Python version gap is large, may fail to load)
Solutions:
- Containerization: Use Docker to package the model and all its dependencies into an image. This is the gold standard for ensuring environment consistency.
- Dependency Management: When using
requirements.txtorenvironment.ymlPrecisely record all packages and their versions. - Model Format: Consider using cross-language, cross-environment model formats such as ONNX or PMML, or framework-native secure formats (such as
TensorFlow SavedModel,PyTorch TorchScript)。
2. Poor Online Inference Performance
The API response time is too long and throughput (TPS) cannot be increased, failing to meet business requirements.
Common Bottlenecks and Optimizations:
- High cost per prediction: The model itself is complex (such as a large deep learning model).
- Optimize the: Model pruning, quantization, knowledge distillation, or rewriting with a more efficient model architecture.
- Frequent I/O or network calls: Each prediction requires fetching features from a database or remote service.
- Optimize the: Implement feature caching, pre-computation, or serve features as a service to reduce latency.
- Hardware acceleration not utilized: Running a model suited for a GPU on a CPU.
- Optimize the: Select the correct inference hardware (CPU/GPU/dedicated AI chip) and inference framework based on the model type (such as
TensorRT,OpenVINO)。
- Inefficient serving framework: Using Flask to load the model directly, with weak concurrency handling.
- Optimize the: Use high-performance ML serving frameworks such as TensorFlow Serving, TorchServe, or Triton Inference Server. They support advanced features such as hot model updates, dynamic batching, and multi-model hosting.

Figure: An example of a high-performance model serving architecture, including load balancing, feature caching, and dedicated model servers.
3. Improper Resource Management
The model service has a memory leak, or occupies more and more memory over time, eventually causing the service to crash.
Troubleshooting:
- Model loading method: Is the model reloaded on every request? The correct approach is to load it into memory once at service startup and share it for subsequent requests.
- Global variable accumulation: Does the service code have global Lists or Dicts that keep accumulating data without being cleaned up?
- Large prediction results: Do the returned prediction results (such as images or large texts) occupy large amounts of memory without being released in time?
Solution:
- Use
gunicorn、uvicornWhen using multi-process/asynchronous servers, understand their Worker model. - Periodically restart the service process (through process management tools such as
systemdorsupervisor)。 - Use professional memory analysis tools (such as
memory_profiler) to locate the leak.
III. Model and Algorithm Issues
1. Overfitting and Underfitting
This is a fundamental problem of model capability.
| Problem | Symptom | Possible cause | Solution |
|---|---|---|---|
| Underfitting | Training and validation set performanceare both poor | Model too simple (low complexity), insufficient features, too few training epochs | Increase model complexity, add more effective features, increase training epochs |
| Overfitting | Training set performanceVery good, validation set performancepoor | Model too complex, too little training data, too much noise | Increase training data, use regularization (L1/L2/Dropout), reduce model complexity, early stopping |
Troubleshooting: Plotting learning curves is the best way to judge the fitting situation.
2. Vanishing/Exploding Gradients
Common when training deep neural networks, causing the model to fail to converge or training to be unstable.
Symptoms:
- Model loss becomes
NaN。 - Weight values become extremely large or small.
- In the early stage of training, the loss value no longer changes.
Solutions:
- Weight initialization: When using
He初始化(ReLU activation function) orXavier初始化(Tanh/Sigmoid)。 - Gradient clipping: Set a threshold and clip the gradient when it exceeds it.
- Batch normalization: Add a
BatchNormlayer before the activation function, which can stabilize training and allow the use of a higher learning rate. - Adjust the network structure: Use structures such as residual connections in ResNet.
IV. Establish a Systematic Troubleshooting Process
When an online model has problems, a systematic troubleshooting process can help you quickly locate them.
- Confirm the problem: Are all predictions wrong, or only for specific groups/scenarios? What is the error rate?
- Check the input: Obtain a batch of erroneous online request data and check whether the input features are complete, whether the format is correct, and whether the values are within a reasonable range (such as the appearance of
NaN,Infor extreme values). - Reproduce locally: Using the erroneous online input data, in the local development environment usethe same model and codeto make predictions and see whether the problem can be reproduced.
- Compare the data: Compare the data distribution of online requests with the training data distribution to check whether drift exists.
- Check the code and configuration: Verify that the code version, model file version, and configuration files of the online service are consistent with the environment that passed testing.
- Check logs and monitoring: Check whether the service logs contain abnormal errors, and whether the monitoring system's CPU, memory, and response time metrics are abnormal.
- Simplify and Locate: If possible, try using a minimal model or rule-based system to process the erroneous input, to determine whether it is a data problem or a model problem.