AI & Machine Learning guides, explanations and reader checklists on whilenetworking.com

Interactive Tutorial: Using SHAP Values to Interpret Black-Box Decisions During SD-WAN Path Selection Failures

In modern Software-Defined Wide Area Network (SD-WAN) architectures, path selection algorithms often rely on complex machine learning models to optimize…

In modern Software-Defined Wide Area Network (SD-WAN) architectures, path selection algorithms often rely on complex machine learning models to optimize latency, jitter, and packet loss. When these “black-box” models fail to select the optimal path, network engineers are left guessing why traffic was routed suboptimally. The solution lies in SHapley Additive exPlanations (SHAP), a game-theoretic approach that assigns each feature an importance value for a particular prediction. This tutorial guides IT students and junior engineers through building a reproducible Python environment to diagnose SD-WAN path selection failures using SHAP values.

Prerequisites and Environment Setup

Before analyzing network data, you must establish a safe, isolated lab environment. Do not attempt these steps on production hardware. We will assume a Linux-based environment (Ubuntu 22.04 LTS) or a Docker container running Python 3.10. Ensure you have access to pip and the git command line tools.

First, create a dedicated directory for your project to maintain reproducibility:

mkdir sdwan-ml-lab
cd sdwan-wan-lab
python -m venv shap-env
source shap-env/bin/activate  # On macOS: source shap-env/bin/activate
pip install --upgrade pip
pip install pandas numpy scikit-learn xgboost shap matplotlib networkx

This command installs the core data manipulation libraries (pandas, numpy), machine learning tools (scikit-learn, xgboost), and the specific SHAP library. The virtual environment ensures that dependencies do not conflict with system packages. Always verify your installation by running a simple import check:

# Verify imports in a fresh Python session
python -c "import shap; print('SHAP version:', shap.__version__)"

Constructing a Synthetic SD-WAN Dataset

Real-world network logs are often proprietary. For educational purposes, we will generate a synthetic dataset that mimics real telemetry data: interface names, latency (ms), jitter (ms), packet loss (%), and current load. We will also include a “target” column representing the model’s decision to route traffic through Interface A or Interface B.

import pandas as pd
import numpy as np

# Set random seed for reproducibility in this tutorial only
np.random.seed(42)

# Generate 1000 synthetic samples
n_samples = 1000
data = {
    'latency_ms': np.random.uniform(5, 150, n_samples),
    'jitter_ms': np.random.uniform(0, 30, n_samples),
    'packet_loss_pct': np.random.uniform(0, 5, n_samples),
    'interface_load': np.random.uniform(0.1, 0.9, n_samples),
    'is_primary_path': np.random.choice([0, 1], n_samples) # Target variable (Black Box Decision)
}

df = pd.DataFrame(data)
# Save to CSV for later use in verification steps
df.to_csv('sdwan_telemetry.csv', index=False)
print("Dataset created successfully.")

This script creates a CSV file named sdwan_telemetry.csv. In a real workplace scenario, you would replace this block with code that reads actual NetFlow or SNMP export data. The target column is_primary_path represents the output of your trained model (e.g., 1 for primary path selected, 0 for secondary).

Training a Simple Black-Box Model

To demonstrate interpretation, we will train an XGBoost classifier. XGBoost is popular in SD-WAN controllers because it handles tabular data efficiently and often outperforms linear models in non-linear routing scenarios.

from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
import shap

# Split data into training and testing sets (80/20)
X = df.drop('is_primary_path', axis=1)
y = df['is_primary_path']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize and train the model
model = XGBClassifier(n_estimators=100, max_depth=4, learning_rate=0.1)
model.fit(X_train, y_train)

# Evaluate accuracy to ensure the model is not broken
score = model.score(X_test, y_test)
print(f"Model Accuracy: {score:.2f}")

At this stage, the model acts as a black box. It makes predictions, but it offers no insight into why a specific packet was routed to a backup link despite low latency. This is where SHAP becomes critical for debugging.

Generating SHAP Explainer Objects

SHAP calculates the contribution of each feature to the prediction. We will use shap.TreeExplainer because XGBoost uses tree structures, which SHAP can interpret efficiently. For neural networks or other black-box models, you would use shap.KernelExplainer, though it is computationally more expensive.

explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# Create a summary plot to see feature importance globally
shap.summary_plot(shap_values, X_test)

The command above generates a waterfall-style plot. In a real lab session, you would observe which features (e.g., packet_loss_pct) have the highest global impact on the model’s decision. If jitter_ms appears dominant, it suggests your SD-WAN policy prioritizes stability over raw speed, which might be intentional or a misconfiguration depending on the business requirement.

Diagnosing Specific Path Selection Failures

The most valuable use of SHAP in troubleshooting is analyzing individual predictions. Suppose a specific flow should have used Interface A (low latency) but was routed to Interface B (high latency). We can extract the SHAP values for that specific row to find the culprit.

# Select a specific sample where prediction might be unexpected
# In a real scenario, you would filter by IP address or timestamp
sample_index = 50 
sample_data = X_test.iloc[sample_index]
pred = model.predict(X_test.iloc[sample_index:])
pred_prob = model.predict_proba(X_test.iloc[sample_index:])[0]

print(f"Sample Prediction (Primary Path): {pred[0]}")
print(f"Probability of Primary Path: {pred_prob[1]:.2%}")

# Get SHAP values for this specific sample
shap_sample = shap.values(shap_values, X_test.iloc[sample_index:])

# Create a force plot to visualize why the model made this decision
shap.force_plot(explainer.expected_value, shap_sample, feature_names=X.columns)

The force_plot output visually separates features pushing the prediction toward “Primary Path” (green values) and those pushing it toward “Secondary Path” (red values). If you see a large red bar next to packet_loss_pct, it confirms that high packet loss on the preferred link forced the model to switch paths, validating the decision rather than treating it as an error.

Common Errors and Verification Steps

When implementing this in a lab or production debugging workflow, several errors may occur:

  1. Data Type Mismatches: SHAP expects numeric data. If your CSV contains string representations of numbers (e.g., “50.5” instead of 50.5), the model will fail.
    • Fix: Use pd.to_numeric() on columns before training.
  2. Categorical Features: XGBoost and SHAP handle categorical data poorly if not encoded.
    • Fix: Convert interface names to integers using LabelEncoder or one-hot encoding before passing to the model.
  3. Version Incompatibility: SHAP versions change frequently. An older shap library may not support newer XGBoost output formats.
    • Fix: Check compatibility matrices on the official documentation sites. Always pin specific versions in your requirements.txt.

Student Practice Task

To solidify understanding, students should perform the following mini-project:
1. Download a public dataset of network latency logs (e.g., from Kaggle or a university repository).
2. Preprocess the data to handle missing values and normalize continuous features.
3. Train a random forest model to predict “Optimal Path.”
4. Generate SHAP summary plots for both global importance and individual instance explanation.
5. Write a brief report identifying one scenario where the model’s decision contradicts simple heuristics (like “lowest latency first”) and explain the SHAP-based reason why.

Conclusion

Interpreting black-box models in SD-WAN is no longer optional for advanced network engineers; it is essential for maintaining trust in automated routing decisions. By using SHAP values, you move from blind debugging to data-driven diagnosis. You can verify whether a path selection failure was caused by a genuine network anomaly (like a sudden spike in jitter) or a model bias that requires retraining. Remember that while this tutorial provides a robust technical framework, real-world deployment must consider local jurisdiction laws regarding data privacy and specific vendor API limitations when integrating these tools into commercial SD-WAN controllers. Always validate your findings against authoritative documentation before applying changes to live production networks.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.