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

Troubleshooting common problems

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.

  • Troubleshooting: Compare the sample data after offline preprocessing and online preprocessing. Ensure that the Scaler used (such as 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).

    • Troubleshooting: Monitor changes in the distribution of model input features over time. You can periodically calculate the mean, variance, and quantiles of features and compare them with the training set.
      • 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.

      • Troubleshooting: Analyze the user profile distribution of the training set and online requests (such as the ratio of new to old users, geographic distribution, etc.).
      • 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

        print

        (

        f

        "Current online feature mean: {current_online_mean:.3f}"

        )

        print

        (

        f

        "Z-score with respect to the training set mean: {z_score:.3f}"

        )

        if

        abs

        (

        z_score

        )

        3

        :  

        Threshold, for example 3 standard deviations

           

        print

        (

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

        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:

        Solutions:

        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:

        - **Optimization**: Model pruning, quantization, knowledge distillation, or rewriting with a more efficient model architecture. - **Optimization**: Implement feature caching, pre-computation, or serve features as a service to reduce latency. - **Optimization**: Select the correct inference hardware (CPU/GPU/dedicated AI chip) and inference framework based on the model type (such as `TensorRT`, `OpenVINO`). - **Optimization**: 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:

        Solution:


        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:

        Solutions:


        IV. Establish a Systematic Troubleshooting Process

        When an online model has problems, a systematic troubleshooting process can help you quickly locate them.