Design a drift detection suite combining PSI, KL divergence, and population stability…
- User
Design a drift detection suite combining PSI, KL divergence, and population stability indexes with playbooks.
- Assistant
Design a drift detection suite combining PSI, KL divergence, and population stability indexes with playbooks.
We are to design a drift detection suite that combines PSI (Population Stability Index), KL divergence (Kullback-Leibler divergence), and population stability indexes (note: PSI is a type of population stability index, but we might be referring to other indexes as well? However, the prompt says "PSI, KL divergence, and population stability indexes" which might be redundant. I think it means we should include PSI and KL divergence, and perhaps other stability indexes like the Chi-square statistic or others? But to keep it focused, we can consider PSI and KL as the main two, and then also consider other common stability indexes like the Chi-square test for distribution differences, or the Wasserstein distance? The prompt says "population stability indexes" plural, so we might include multiple.
But note: PSI is already a population stability index. So maybe the intention is to have a suite that includes multiple measures: PSI, KL divergence, and perhaps others like the Population Stability Index (which is PSI) and maybe the Characteristic Stability Index (CSI) or something? Actually, PSI is often used for population stability. So I think we should interpret it as: Use PSI and KL divergence as the two main metrics, and also consider other population stability indexes (like maybe the Jensen-Shannon divergence, or the Hellinger distance) to have a comprehensive suite.
However, the prompt says "combining PSI, KL divergence, and population stability indexes". That phrasing is odd. Possibly it means: combining PSI, KL divergence, and other population stability indexes? Or it might be a list: PSI, KL divergence, and population stability indexes (meaning multiple PSI-like indexes). But then PSI is a population stability index. So I think the intended meaning is to have a suite that uses multiple drift detection metrics, specifically PSI and KL divergence, and also other stability indexes (like maybe the Chi-square test, or the Kolmogorov-Smirnov test for continuous variables?).
But note: PSI is typically used for categorical variables (or binned continuous). KL divergence can be used for both discrete and continuous (with appropriate density estimation). For continuous variables, we might also consider the Kolmogorov-Smirnov statistic. So let's design a suite that can handle both categorical and continuous features, and uses multiple metrics.
We are also to include "playbooks". That likely means we should provide actionable steps or guidelines on what to do when drift is detected, perhaps based on thresholds and the type of drift.
So, design a drift detection suite with:
Metrics:
Thresholds: We need to define thresholds for each metric to flag drift. Common thresholds for PSI: <0.1: no significant change, 0.1-0.2: moderate change, >0.2: significant change. For KL divergence, it depends on the base, but we can set thresholds based on empirical distribution or use percentiles. We might also combine metrics.
Playbooks: For each metric or combination, define actions:
Implementation: We'll design a Python class or set of functions that compute these metrics for given reference and current distributions, and then interpret them.
Let's outline:
Class: DriftDetector Methods:
But the prompt says "combining PSI, KL divergence, and population stability indexes". That might mean we use PSI and KL, and also other population stability indexes (like maybe the Characteristic Stability Index for each feature? Actually, CSI is per feature PSI? Wait, PSI is often computed per feature, and then overall PSI is weighted average? Some define overall PSI as the sum of feature PSI weighted by feature importance. So maybe we also compute an overall drift score.
So we can compute:
Alternatively, we can use the Population Stability Index overall by concatenating all features? That might be high-dimensional and not feasible. So better to aggregate per-feature metrics.
So let's define:
We'll also provide thresholds for each metric and then a combined decision.
Playbooks:
We can also have a playbook that suggests which features are drifting and then check if those features are important for the model. If important features drift, it's more critical.
We can incorporate feature importance from the model if available.
So let's design:
DriftDetectionSuite: reference_data: pandas DataFrame (reference distribution) current_data: pandas DataFrame (current distribution) feature_names: list of features to monitor (all or subset) categorical_features: list of categorical feature names continuous_features: list of continuous feature names model: optional, a trained model with feature_importances_ or coef_ to weight features. thresholds: dict with thresholds for PSI and KL.
Methods: compute_feature_psi(feature): returns PSI value. compute_feature_kl(feature): returns KL divergence (ref || current) after smoothing. compute_all_metrics(): returns a DataFrame with columns: feature, psi, kl, is_categorical. compute_overall_drift(aggregation='weighted'): returns overall score. If model provided, weight by feature importance; else, simple average or max.
generate_report(): returns a dict with:
- per_feature metrics
- overall metrics
- drift_status: 'HIGH', 'MODERATE', 'LOW' based on thresholds.
- playbook_recommendations: list of actions.
We'll also need to handle binning for continuous features for PSI. Common approach: bin the continuous feature into deciles (or based on reference distribution's quantiles). We'll use reference data to define bin edges (e.g., 10 bins with equal frequency). Then apply same bins to current data. Then compute PSI as sum((ref_percent - curr_percent) * log(ref_percent/curr_percent)).
For KL: for categorical, we just use the probability vectors. For continuous, we need to discretize similarly? Or we can use KDE to get densities? But KL for continuous requires density estimation. It's common to bin for both PSI and KL for consistency. So we'll bin continuous features the same way for both metrics. Then we treat the binned distribution as categorical (the bin categories). So we can use the same binned probabilities for KL.
Alternatively, we can compute KL without binning by assuming a parametric distribution? But that's more complex. So we'll bin.
So for continuous features, we'll create bins based on reference data's quantiles (e.g., 10 bins). Then compute frequency in each bin for reference and current. Then use those as probabilities for KL.
We'll also add a small epsilon to avoid zero probabilities.
Thresholds:
Maybe we can compute the KL divergence for each feature and then compare to the 95th percentile of KL divergences computed from two random samples of the reference data? That would give a sense of what is due to sampling variation. But that might be heavy.
Alternatively, we can set a fixed threshold like 0.1 for KL? But if the feature has many categories, KL can be large even with small changes. So perhaps we should normalize by the number of categories? Or use the Jensen-Shannon divergence which is bounded between 0 and 1. But the prompt says KL divergence, so we'll use KL and then try to set a threshold based on the feature's entropy? For example, set threshold as some fraction of the reference entropy? That might be more adaptive.
Let's define: For a feature, let H_ref be the entropy of the reference distribution. Then if KL(ref||current) > c * H_ref, we flag drift. c could be 0.1 or 0.2. But then for a uniform distribution over k categories, H_ref = log(k). So threshold scales with k. That might be reasonable.
Alternatively, we can use the normalized KL divergence: KL / H_ref. Then threshold on that normalized value (e.g., >0.1). That is similar to the idea of relative entropy.
We'll do: normalized_kl = kl / entropy_ref. Then threshold on normalized_kl.
But we need to compute entropy_ref: -sum(p_ref * log(p_ref)).
We'll compute that.
So for each feature, we compute:
But we can also set a threshold for raw kl? Maybe not needed if we use normalized.
So we'll have two metrics: psi and normalized_kl.
Then thresholds:
Now, overall drift: we can compute the proportion of features with high drift, or a weighted average of normalized_kl and psi? But they are on different scales. We can normalize each to [0,1] by their thresholds? For example, for PSI, we know threshold for high is 0.2, so we can compute psi_normalized = psi / 0.2, but cap at 1. Similarly for normalized_kl, we set high threshold at 0.1, so kl_normalized = normalized_kl / 0.1. Then overall score could be average of these normalized scores? But that would mix features.
Alternatively, we can aggregate per-feature drift flags: count of features with high drift, etc.
We'll do: overall_drift_score = (number of features with (psi > 0.2 or normalized_kl > 0.1)) / total_features. Then interpret: >0.3: high overall drift, etc.
But we also want to weight by feature importance. If model provided, we weight each feature by its importance (normalized to sum to 1). Then overall_drift_score = sum(importance_i * (psi_i > threshold or kl_i > threshold)? That gives a weighted proportion of drifting features. Or we can compute a weighted average of the normalized metrics? Let's do:
For each feature, define a drift indicator: drift_flag_i = 1 if (psi_i > 0.2 or normalized_kl_i > 0.1) else 0.
Then overall_drift_score = sum(importance_i * drift_flag_i). If no importance, then simple average of drift_flag_i.
Then we can set thresholds on overall_drift_score: >0.5: high, 0.2-0.5: moderate, <0.2: low.
But we might also want to consider the magnitude of drift, not just binary. So we could combine the normalized metrics into a per-feature drift score, say: feature_drift_score_i = max( psi_i / 0.2, normalized_kl_i / 0.1 ) but cap at 1? Then overall = weighted average of feature_drift_score_i.
That might be better because it captures extent of drift.
So let's do:
For each feature: psi_scaled = min(psi_i / 0.2, 1) # scale psi to [0,1] with 1 at threshold 0.2 kl_scaled = min(normalized_kl_i / 0.1, 1) feature_drift_score_i = max(psi_scaled, kl_scaled) # if either is high, score is high.
Then overall_drift_score = weighted average of feature_drift_score_i.
If no weights, equal weight.
Then thresholds for overall: overall_drift_score < 0.2: low 0.2 <= overall_drift_score < 0.5: moderate
=0.5: high
We can adjust.
Now, playbooks:
For each drift level (low, moderate, high) and also considering if important features are drifting, we give recommendations.
We can have:
Additionally, we can have specific playbooks for each metric: e.g., if PSI is high but KL is low, it might indicate shift in tail behavior? But we are combining.
We'll generate a report that lists:
Implementation details:
We'll write a class DriftDetector.
Steps:
Alternatively, we can treat unseen categories as a separate "other" category. That might be cleaner. So for reference, we have the set of categories that appear in reference. For current, we map any category not in reference to "other". Then we have the same set of categories (original reference categories plus "other"). That's standard.
So for categorical features: categories = reference_categories + ['other'] if current has any unseen. Then compute counts in each bin for reference and current, with current mapping unseen to 'other'.
For continuous, we use the bin edges from reference (quantiles). For current, we bin using those edges, and any value outside the range (if current has values beyond min/max of reference) we assign to the first or last bin? Or create an 'other' bin? Typically, we clip to the range: values below min go to first bin, above max to last bin. That's common.
Now, for PSI formula: psi = sum( (ref_percent - curr_percent) * log(ref_percent / curr_percent) ) We need to add epsilon to percentages to avoid log(0). So we'll compute counts, add epsilon (e.g., 1e-6) to each count, then normalize to get probabilities.
For KL: same probabilities, then kl = sum(ref_prob * log(ref_prob / curr_prob)).
We'll compute these.
Now, code structure:
class DriftDetector: def init(self, reference_data, current_data, feature_names=None, categorical_features=None, continuous_features=None, model=None, n_bins=10, epsilon=1e-6): self.reference_data = reference_data self.current_data = current_data self.n_bins = n_bins self.epsilon = epsilon self.model = model # optional, should have feature_importances_ attribute or coef_ # Determine features to monitor if feature_names is None: self.feature_names = reference_data.columns.tolist() else: self.feature_names = feature_names # Determine categorical and continuous if not provided if categorical_features is None and continuous_features is None: # infer: if dtype is object or category, or low cardinality? self.categorical_features = [f for f in self.feature_names if reference_data[f].dtype in ['object', 'category'] or reference_data[f].nunique() < 10] self.continuous_features = [f for f in self.feature_names if f not in self.categorical_features] else: self.categorical_features = categorical_features self.continuous_features = continuous_features # Prepare bin edges for continuous features self.bin_edges = {} for feat in self.continuous_features: # compute quantile-based bin edges from reference try: edges = np.quantile(reference_data[feat].dropna(), np.linspace(0,1,self.n_bins+1)) except: # if all null? skip? edges = None self.bin_edges[feat] = edges # For categorical, we will compute categories on the fly? Or store reference categories? self.reference_categories = {} for feat in self.categorical_features: cats = reference_data[feat].dropna().unique().tolist() self.reference_categories[feat] = cats
We might also want to include other metrics like chi-square for categorical, KS for continuous? But the prompt specifically says PSI, KL divergence, and population stability indexes. We already have PSI and KL. And we are aggregating. So that should suffice.
We can also add an option to compute other indexes if needed.
Now, we need to present this as a design. The user asked: "Design a drift detection suite combining PSI, KL divergence, and population stability indexes with playbooks."
So we should describe the design, possibly including the class structure, algorithms, thresholds, and playbooks.
We'll write a response that outlines:
Overview: The suite monitors feature distributions between reference (training) and current (production) data using PSI and KL divergence. It aggregates per-feature scores into an overall drift score. It provides playbooks for different drift levels.
Key components:
Thresholds: Explain the chosen thresholds for PSI and normalized KL.
Playbooks: Describe actions for low, moderate, high drift.
Implementation: Provide a Python class as above (or simplified pseudocode) and explain.
We can also mention that the suite can be run periodically (e.g., daily) and integrated with alerting.
Let's write the answer accordingly.
This suite monitors data distribution drift between a reference dataset (typically training data) and a current dataset (production data) using Population Stability Index (PSI) and Kullback-Leibler (KL) divergence. It aggregates per-feature drift signals into an overall drift score and provides actionable playbooks based on severity and feature importance.
1e-6) to all bin counts to avoid division-by-zero in PSI/KL calculations.| Metric | Threshold | Interpretation |
|---|---|---|
| PSI (per feature) | > 0.2 | High drift |
| 0.1–0.2 | Moderate drift | |
| < 0.1 | Low drift | |
| Normalized KL | > 0.1 | High drift |
| 0.05–0.1 | Moderate drift | |
| < 0.05 | Low drift | |
| Overall drift score | ≥ 0.5 | HIGH |
| 0.2–0.5 | MODERATE | |
| < 0.2 | LOW |
overall < 0.2)0.2 ≤ overall < 0.5)overall ≥ 0.5)# Assume `train_df` (reference) and `prod_df` (current) are loaded
# `model` is a trained classifier/regressor with feature_importances_
detector = DriftDetector(
reference_data=train_df,
current_data=prod_df,
model=model,
categorical_features=['cat1', 'cat2'],
continuous_features=['num1', 'num2']
)
report = detector.generate_report()
print(report['overall_drift_level'])
print(report['recommendations'])
overall_drift_level is MODERATE or HIGH._get_binned_counts or adding new methods.This suite provides a robust, interpretable, and actionable framework for monitoring data drift in production ML systems.
def _get_binned_counts(self, feature, data):
if feature in self.categorical_features:
# For categorical, map to categories, add 'other' for unseen
cats = self.reference_categories[feature]
counts = data[feature].fillna('missing').apply(lambda x: x if x in cats else 'other').value_counts()
# Ensure all categories are present
all_cats = cats + ['other'] if 'other' not in cats else cats
# Also include 'missing' if we want? We filled NaN with 'missing', so if 'missing' not in cats, it will be mapped to 'other'? Actually, we filled NaN with 'missing', then if 'missing' not in cats, it becomes 'other'. That might be okay. Alternatively, treat missing as separate? Let's treat missing as a category if it appears? But we filled with 'missing', so it will be a category if we include 'missing' in cats? But reference_categories might not have 'missing'. So we should include 'missing' as a category if there are any missing? But we already filled with 'missing', so we need to include 'missing' in the list if it appears in data? That's messy.
# Instead, we can handle missing by treating them as a separate category 'missing' if they exist in reference? But reference might have missing as NaN? We dropped NaN. So reference_categories doesn't include NaN. So we should treat missing in current as 'other'? That might not be ideal.
# Let's change: For reference, we include NaN as a category? We dropped NaN when computing reference_categories. So reference doesn't have missing. So current missing should be mapped to 'other'? But then if there are many missing, that will show drift. That might be acceptable because missingness is a drift indicator.
# So we'll keep: fillna('missing') and then if 'missing' not in cats, it becomes 'other'. But if we want to treat missing as its own category, we should include 'missing' in the categories if reference has any missing? But we dropped reference missing. So we don't have missing in reference. So it's better to treat missing as 'other'? Or create a separate 'missing' bin? That would be a new category not in reference, so it would go to 'other'. So it's the same.
# So we'll proceed: after mapping, we get counts for each category in all_cats. If a category is missing in counts, set to 0.
counts = counts.reindex(all_cats, fill_value=0)
return counts
else:
# continuous: bin using bin_edges
edges = self.bin_edges[feature]
if edges is None:
return None
# Bin the data
# Use pandas cut with bins=edges, include_lowest=True? But edges include min and max. We want to create n_bins bins.
# cut with bins=edges will give bins (edges[i], edges[i+1]] except possibly first?
# We'll use right=False to have [left, right) but then the last bin is [last, last]? Actually, with quantiles, edges are inclusive. We'll use right=False to have intervals [edges[i], edges[i+1]) and then the last bin includes the rightmost edge.
# But careful: if there are values outside the range, they become NaN. So we need to handle that.
# We'll clip the values to the range of edges? Or we can use `include_lowest=True` and `right=False` and then handle values outside as NaN and then map NaN to the first or last bin? Actually, cut with `include_lowest=True` and `right=False` will put the lowest value in the first bin, but values below the lowest edge become NaN. Similarly for above.
# We can do: bin_labels = pd.cut(data[feature], bins=edges, labels=False, include_lowest=True, right=False)
# This returns integer codes from 0 to len(edges)-2. NaN for out of range.
# Then we can count codes and also count NaNs separately? But we want to include out-of-range in the first and last bin? That is common practice: clip to range.
# Alternatively, we can use `np.digitize` with right=False? Let's do:
# bin_indices = np.digitize(data[feature].values, edges, right=False)
# This returns 0 for values < edges[0], 1 for values in [edges[0], edges[1]), ..., len(edges) for values >= edges[-1].
# So we have indices from 0 to len(edges). But we want bins 0 to n_bins-1? Actually, if we have n_bins+1 edges, we get n_bins+1 possible indices? Wait: for edges = [e0, e1, ..., en] with n+1 edges, digitize returns i such that edges[i-1] <= x < edges[i] (if right=False) but for x < e0, i=0; for x >= en, i=n+1? Actually, documentation: np.digitize(x, bins, right=False) returns i such that bins[i-1] <= x < bins[i]. So for x < bins[0], i=0. For x >= bins[-1], i=len(bins). So we get indices from 0 to len(bins). That gives len(bins)+1 possible values? Actually, if bins has length m, then indices are in [0, m]. So we have m+1 possible indices? That's not right. Let's test: bins=[1,2,3], then for x=0.5 -> i=0, x=1 -> i=1 (since bins[0]<=x<bins[1]? Actually, for right=False, condition is bins[i-1] <= x < bins[i]. So for x=1, we need i such that bins[i-1]<=1<bins[i]. i=1 gives bins[0]=1<=1 and 1<2? 1<2 is true, so i=1. For x=3, i=3 because bins[2]=3<=3 and 3< ? there is no bins[3] so i=3. So indices from 0 to 3 inclusive? That's 4 values for 3 bins? Actually, we have 3 bins: [1,2), [2,3), and then what about x>=3? That's the last bin? Actually, the last bin should be [3, infinity) but we don't have an upper edge. So we have bins defined by edges, we want n_bins bins: bin0: [edges[0], edges[1]), bin1: [edges[1], edges[2]), ..., bin_{n_bins-1}: [edges[n_bins-1], edges[n_bins]]? But edges has n_bins+1 points. So we have n_bins intervals. For values >= edges[n_bins], they are in an extra interval? That's not what we want. We want to cap at the last edge. So we should clip values to the range [edges[0], edges[-1]] before binning? Or we can extend edges to include -inf and +inf? Simpler: clip the data to the min and max of edges. So:
clipped = np.clip(data[feature].values, edges[0], edges[-1])
Then bin using digitize with right=False and bins=edges[1:-1]? Actually, if we clip, then all values are within [edges[0], edges[-1]]. Then we can use bins=edges[1:-1]? That gives n_bins-1 bins? Not exactly.
Let's think: We have edges: [e0, e1, ..., e_n] with n = n_bins. We want bins: [e0, e1), [e1, e2), ..., [e_{n-1}, e_n]. So we have n_bins bins. We can use np.digitize with bins=e1..e_{n-1}? Actually, if we pass bins = edges[1:-1] (i.e., e1 to e_{n-1}), then for x in [e0, e1): i=0? No, digitize with these bins will return 0 for x < e1, but we have e0 <= x < e1, so that's fine? But then for x in [e_{n-1}, e_n], it will return n_bins-1? Because bins has length n_bins-1? Let's see: if edges = [0,1,2,3] (n_bins=3, edges length=4). We want bins: [0,1), [1,2), [2,3]. We can pass bins=[1,2] (edges[1:-1]). Then for x=0.5: since x<1, digitize returns 0. For x=1.5: 1<=1.5<2? Actually, condition for right=False: bins[i-1] <= x < bins[i]. For i=1: bins[0]=1 <= x? 1<=1.5 true, but then x< bins[1]=2? true, so i=1. For x=2.5: bins[1]=2 <=2.5 true, but x< ? there is no bins[2], so i=2? Actually, digitize returns the index of the bin. With bins=[1,2], possible returns are 0,1,2. For x>=2, i=2. But we want x in [2,3] to be bin index 2? That matches. So we get bin indices 0,1,2 for the three bins. But note: for x exactly 1, we have bins[0]=1 <=1 true, and 1<2 true, so i=1. That's correct. For x exactly 3, after clipping, x=3? But we clipped to edges[-1]=3, so x=3. Then 2<=3? For i=2, bins[1]=2 <=3 true, but then we check x< ? there is no bins[2], so by definition, i=2? Actually, the condition for the last bin is x >= bins[-1]? Let's check documentation: np.digitize(x, bins, right=False) returns i such that bins[i-1] <= x < bins[i] for i in 1..len(bins), and i=0 if x < bins[0], i=len(bins) if x >= bins[-1]. So for our bins=[1,2], len(bins)=2. For x=3, we have x>=bins[-1]=2, so i=2. That's what we want: bin index 2. So it works. But we must clip to ensure x < bins[-1]? Actually, we want x in [2,3] to go to bin 2. But if x=3, it goes to bin 2. That's fine. However, what about x exactly 0? After clipping, x=0? But edges[0]=0, so we clipped to 0. Then for x=0, we have x < bins[0]=1, so i=0. That's bin0: [0,1). But we want [0,1) to include 0? Yes. But note: we clipped to edges[0], so if there is a value below edges[0], it becomes edges[0], so it will be in bin0. That's acceptable.
So procedure:
edges = self.bin_edges[feature]
# Clip data to the range [edges[0], edges[-1]]
clipped = np.clip(data[feature].values, edges[0], edges[-1])
# Use bins = edges[1:-1]? Actually, we need to pass the interior edges. For n_bins bins, we have n_bins+1 edges. The bins for digitize should be edges[1:-1]? That gives n_bins-1 edges? Let's derive: if edges = [e0, e1, e2, ..., e_n] with n = n_bins. We want to create bins defined by thresholds at e1, e2, ..., e_{n-1}. Because:
bin0: [e0, e1)
bin1: [e1, e2)
...
bin_{n-1}: [e_{n-1}, e_n]
So we need to pass thresholds = [e1, e2, ..., e_{n-1}]. That's edges[1:n] (i.e., edges[1:-1] if we exclude the last? Actually, edges[1:-1] gives from index 1 to n-1 (since -1 is the last, not included). So for edges=[0,1,2,3] (n=3, indices 0,1,2,3), edges[1:-1] = [1,2] which is correct. So we pass bins = edges[1:-1].
Then digitize returns indices 0 to n_bins (because len(bins) = n_bins-1, so possible returns: 0,1,...,n_bins). That gives exactly n_bins bins? Let's test: with bins=[1,2], returns 0,1,2. That's 3 values, which correspond to 3 bins. So number of bins = len(bins)+1 = n_bins. Good.
So:
thresholds = edges[1:-1]
bin_indices = np.digitize(clipped, thresholds, right=False)
# Then count the bin indices
counts = pd.Series(bin_indices).value_counts().sort_index()
# But we need counts for all bins from 0 to n_bins-1? Actually, bin_indices will be in range 0..n_bins (since digitize can return up to len(thresholds) which is n_bins-1? Wait: with thresholds of length m, digitize returns 0..m. So with m = n_bins-1, returns 0..n_bins-1? Actually, m = n_bins-1, so returns 0..m? That would be 0..n_bins-1? Because m = n_bins-1, so returns from 0 to m inclusive, that's m+1 = n_bins values. Yes, so indices 0 to n_bins-1. But in our example, n_bins=3, thresholds length=2, returns 0,1,2 -> that's 3 values, indices 0,1,2. So we have bins 0,1,2. That's correct.
# However, we must ensure that we have exactly n_bins bins. Sometimes, if some bin has no samples, we need to include it with count 0.
all_bins = np.arange(self.n_bins) # 0 to n_bins-1
counts = counts.reindex(all_bins, fill_value=0)
return counts
except Exception as e:
print(f"Error binning {feature}: {e}")
return None
def compute_psi(self, feature):
ref_counts = self._get_binned_counts(feature, self.reference_data)
curr_counts = self._get_binned_counts(feature, self.current_data)
if ref_counts is None or curr_counts is None:
return np.nan
# Add epsilon to avoid zeros
ref_counts = ref_counts + self.epsilon
curr_counts = curr_counts + self.epsilon
# Normalize to probabilities
ref_probs = ref_counts / ref_counts.sum()
curr_probs = curr_counts / curr_counts.sum()
# Compute PSI
psi = np.sum((ref_probs - curr_probs) * np.log(ref_probs / curr_probs))
return psi
def compute_kl(self, feature):
ref_counts = self._get_binned_counts(feature, self.reference_data)
curr_counts = self._get_binned_counts(feature, self.current_data)
if ref_counts is None or curr_counts is None:
return np.nan
ref_counts = ref_counts + self.epsilon
curr_counts = curr_counts + self.epsilon
ref_probs = ref_counts / ref_counts.sum()
curr_probs = curr_counts / curr_counts.sum()
# KL divergence: ref || curr
kl = np.sum(ref_probs * np.log(ref_probs / curr_probs))
return kl
def compute_entropy(self, feature):
ref_counts = self._get_binned_counts(feature, self.reference_data)
if ref_counts is None:
return np.nan
ref_counts = ref_counts + self.epsilon
ref_probs = ref_counts / ref_counts.sum()
entropy = -np.sum(ref_probs * np.log(ref_probs))
return entropy
def compute_all_metrics(self):
results = []
for feature in self.feature_names:
psi = self.compute_psi(feature)
kl = self.compute_kl(feature)
entropy = self.compute_entropy(feature)
normalized_kl = kl / entropy if entropy > 0 else (kl if kl > 0 else 0)
results.append({
'feature': feature,
'psi': psi,
'kl': kl,
'entropy': entropy,
'normalized_kl': normalized_kl,
'is_categorical': feature in self.categorical_features
})
return pd.DataFrame(results).set_index('feature')
def compute_overall_drift(self, metrics_df=None):
if metrics_df is None:
metrics_df = self.compute_all_metrics()
# Define thresholds
psi_threshold = 0.2
normalized_kl_threshold = 0.1
# For each feature, compute drift score as max(psi/psi_threshold, normalized_kl/normalized_kl_threshold) capped at 1.
metrics_df['psi_scaled'] = metrics_df['psi'] / psi_threshold
metrics_df['kl_scaled'] = metrics_df['normalized_kl'] / normalized_kl_threshold
metrics_df['drift_score'] = metrics_df[['psi_scaled', 'kl_scaled']].max(axis=1)
metrics_df['drift_score'] = metrics_df['drift_score'].clip(upper=1.0)
# Get feature weights
if self.model is not None:
# Try to get feature importances
if hasattr(self.model, 'feature_importances_'):
importances = self.model.feature_importances_
elif hasattr(self.model, 'coef_'):
importances = np.abs(self.model.coef_).flatten()
else:
importances = None
if importances is not None:
# Ensure order matches feature_names
if hasattr(self.model, 'feature_names_in_'):
model_features = self.model.feature_names_in_
else:
model_features = self.feature_names # assume same order
# Create a Series with model_features
imp_series = pd.Series(importances, index=model_features)
# Reindex to our feature_names, fill missing with 0? But should have all.
weights = imp_series.reindex(self.feature_names).fillna(0).values
# Normalize to sum to 1
weights = weights / weights.sum() if weights.sum() > 0 else np.ones(len(self.feature_names))/len(self.feature_names)
else:
weights = np.ones(len(self.feature_names)) / len(self.feature_names)
else:
weights = np.ones(len(self.feature_names)) / len(self.feature_names)
# Overall drift score = weighted average of drift_score
overall = np.dot(metrics_df['drift_score'], weights)
return overall, metrics_df
def generate_report(self):
metrics_df = self.compute_all_metrics()
overall_score, metrics_df_with_drift = self.compute_overall_drift(metrics_df)
# Determine overall level
if overall_score < 0.2:
overall_level = 'LOW'
elif overall_score < 0.5:
overall_level = 'MODERATE'
else:
overall_level = 'HIGH'
# Features with high drift (drift_score=1?) or we can use thresholds on individual metrics?
# For reporting, we can list features where psi>0.2 or normalized_kl>0.1.
high_drift_features = metrics_df[(metrics_df['psi'] > 0.2) | (metrics_df['normalized_kl'] > 0.1)].index.tolist()
# Also, if model provided, get important features that are in high_drift_features.
important_drift_features = []
if self.model is not None and hasattr(self.model, 'feature_importances_'):
# Get top k important features? Or all with importance > threshold?
# We'll just get the feature importances and see which high_drift_features are also important.
if hasattr(self.model, 'feature_names_in_'):
feat_imp = pd.Series(self.model.feature_importances_, index=self.model.feature_names_in_)
else:
feat_imp = pd.Series(self.model.feature_importances_, index=self.feature_names)
# Sort features by importance descending
top_features = feat_imp.nlargest(10).index.tolist() # top 10
important_drift_features = [f for f in high_drift_features if f in top_features]
# Generate recommendations
recommendations = []
if overall_level == 'LOW':
recommendations.append("Drift is low. Continue monitoring at current frequency.")
elif overall_level == 'MODERATE':
recommendations.append("Moderate drift detected. Increase monitoring frequency (e.g., daily).")
if high_drift_features:
recommendations.append(f"Investigate drifting features: {', '.join(high_drift_features)}.")
if important_drift_features:
recommendations.append(f"Important features {important_drift_features} are drifting. Consider model performance evaluation and possible retraining.")
recommendations.append("Collect more data and check data pipeline for changes.")
else: # HIGH
recommendations.append("High drift detected! Immediate investigation required.")
recommendations.append("Check data pipeline for failures or source changes.")
if important_drift_features:
recommendations.append(f"CRITICAL: Important features {important_drift_features} are drifting. Trigger model retraining pipeline if performance degrades.")
else:
recommendations.append("Although non-important features are drifting, still investigate root cause.")
recommendations.append("Consider collecting labeled data for model evaluation on current data.")
recommendations.append("If drift is due to covariate shift, consider retraining model with recent data.")
report = {
'overall_drift_score': overall_score,
'overall_drift_level': overall_level,
'per_feature_metrics': metrics_df.to_dict('index'),
'high_drift_features': high_drift_features,
'important_drift_features': important_drift_features,
'recommendations': recommendations,
'timestamp': pd.Timestamp.now()
}
return report
import numpy as np
import pandas as pd
from typing import List, Optional
class DriftDetector:
def __init__(
self,
reference_data: pd.DataFrame,
current_data: pd.DataFrame,
feature_names: Optional[List[str]] = None,
categorical_features: Optional[List[str]] = None,
continuous_features: Optional[List[str]] = None,
model: Optional[object] = None, # scikit-learn-like model with feature_importances_ or coef_
n_bins: int = 10,
epsilon: float = 1e-6
):
self.reference_data = reference_data
self.current_data = current_data
self.n_bins = n_bins
self.epsilon = epsilon
self.model = model
# Determine features to monitor
self.feature_names = feature_names or reference_data.columns.tolist()
if categorical_features is None and continuous_features is None:
self.categorical_features = [
f for f in self.feature_names
if reference_data[f].dtype in ['object', 'category'] or reference_data[f].nunique() < 10
]
self.continuous_features = [f for f in self.feature_names if f not in self.categorical_features]
else:
self.categorical_features = categorical_features or []
self.continuous_features = continuous_features or []
# Precompute bin edges for continuous features
self.bin_edges = {}
for feat in self.continuous_features:
try:
self.bin_edges[feat] = np.quantile(reference_data[feat].dropna(), np.linspace(0, 1, self.n_bins+1))
except:
self.bin_edges[feat] = None
# Store reference categories for categoricals
self.reference_categories = {
feat: reference_data[feat].dropna().unique().tolist()
for feat in self.categorical_features
}
def _get_binned_counts(self, feature: str, data: pd.DataFrame):
"""Return bin counts for a feature (with smoothing handled externally)."""
if feature in self.categorical_features:
cats = self.reference_categories[feature]
# Map unseen categories to 'other'
mapped = data[feature].fillna('missing').apply(lambda x: x if x in cats else 'other')
counts = mapped.value_counts()
# Ensure all categories present
all_cats = cats + (['other'] if 'other' not in cats else [])
return counts.reindex(all_cats, fill_value=0)
else:
edges = self.bin_edges[feature]
if edges is None:
return None
# Clip to reference range
clipped = np.clip(data[feature].values, edges[0], edges[-1])
# Use interior edges for binning
thresholds = edges[1:-1]
bin_idx = np.digitize(clipped, thresholds, right=False)
counts = pd.Series(bin_idx).value_counts().sort_index()
# Ensure all bins from 0 to n_bins-1
all_bins = np.arange(self.n_bins)
return counts.reindex(all_bins, fill_value=0)
def compute_psi(self, feature: str) -> float:
ref_counts = self._get_binned_counts(feature, self.reference_data)
curr_counts = self._get_binned_counts(feature, self.current_data)
if ref_counts is None or curr_counts is None:
return np.nan
ref_smooth = ref_counts + self.epsilon
curr_smooth = curr_counts + self.epsilon
ref_prob = ref_smooth / ref_smooth.sum()
curr_prob = curr_smooth / curr_smooth.sum()
return np.sum((ref_prob - curr_prob) * np.log(ref_prob / curr_prob))
def compute_kl(self, feature: str) -> float:
ref_counts = self._get_binned_counts(feature, self.reference_data)
curr_counts = self._get_binned_counts(feature, self.current_data)
if ref_counts is None or curr_counts is None:
return np.nan
ref_smooth = ref_counts + self.epsilon
curr_smooth = curr_counts + self.epsilon
ref_prob = ref_smooth / ref_smooth.sum()
curr_prob = curr_smooth / curr_smooth.sum()
return np.sum(ref_prob * np.log(ref_prob / curr_prob))
def compute_entropy(self, feature: str) -> float:
ref_counts = self._get_binned_counts(feature, self.reference_data)
if ref_counts is None:
return np.nan
ref_smooth = ref_counts + self.epsilon
ref_prob = ref_smooth / ref_smooth.sum()
return -np.sum(ref_prob * np.log(ref_prob))
def compute_all_metrics(self) -> pd.DataFrame:
records = []
for feat in self.feature_names:
psi = self.compute_psi(feat)
kl = self.compute_kl(feat)
ent = self.compute_entropy(feat)
norm_kl = kl / ent if ent > 0 else (kl if kl > 0 else 0)
records.append({
'feature': feat,
'psi': psi,
'kl': kl,
'entropy': ent,
'normalized_kl': norm_kl,
'is_categorical': feat in self.categorical_features
})
return pd.DataFrame(records).set_index('feature')
def compute_overall_drift(self, metrics_df: Optional[pd.DataFrame] = None):
if metrics_df is None:
metrics_df = self.compute_all_metrics()
# Scale metrics to [0,1] using thresholds
metrics_df['psi_scaled'] = (metrics_df['psi'] / 0.2).clip(upper=1.0)
metrics_df['kl_scaled'] = (metrics_df['normalized_kl'] / 0.1).clip(upper=1.0)
metrics_df['drift_score'] = metrics_df[['psi_scaled', 'kl_scaled']].max(axis=1)
# Weights from model or uniform
if self.model is not None:
try:
if hasattr(self.model, 'feature_importances_'):
imp = self.model.feature_importances_
elif hasattr(self.model, 'coef_'):
imp = np.abs(self.model.coef_).flatten()
else:
imp = None
if imp is not None:
if hasattr(self.model, 'feature_names_in_'):
feat_names = self.model.feature_names_in_
else:
feat_names = self.feature_names
imp_series = pd.Series(imp, index=feat_names).reindex(self.feature_names).fillna(0)
weights = imp_series / imp_series.sum()
else:
weights = pd.Series(1.0/len(self.feature_names), index=self.feature_names)
except:
weights = pd.Series(1.0/len(self.feature_names), index=self.feature_names)
else:
weights = pd.Series(1.0/len(self.feature_names), index=self.feature_names)
overall = (metrics_df['drift_score'] * weights).sum()
return overall, metrics_df
def generate_report(self) -> dict:
metrics = self.compute_all_metrics()
overall_score, metrics_with_drift = self.compute_overall_drift(metrics)
# Determine overall level
if overall_score < 0.2:
level = 'LOW'
elif overall_score < 0.5:
level = 'MODERATE'
else:
level = 'HIGH'
# Identify high-drift features
high_drift = metrics[
(metrics['psi'] > 0.2) | (metrics['normalized_kl'] > 0.1)
].index.tolist()
# Identify important features among high-drift
important_drift = []
if self.model is not None and hasattr(self.model, 'feature_importances_'):
if hasattr(self.model, 'feature_names_in_'):
imp = pd.Series(self.model.feature_importances_, index=self.model.feature_names_in_)
else:
imp = pd.Series(self.model.feature_importances_, index=self.feature_names)
top10 = imp.nlargest(10).index.tolist()
important_drift = [f for f in high_drift if f in top10]
# Build recommendations
recs = []
if level == 'LOW':
recs.append("Drift is low. Continue monitoring at current frequency.")
elif level == 'MODERATE':
recs.append("Moderate drift detected. Increase monitoring frequency (e.g., daily).")
if high_drift:
recs.append(f"Investigate drifting features: {', '.join(high_drift)}.")
if important_drift:
recs.append(f"Important features {important_drift} are drifting. Evaluate model performance and consider retraining.")
recs.append("Check data pipeline for partial failures or source changes.")
else: # HIGH
recs.append("HIGH DRIFT: Immediate investigation required.")
recs.append("Validate data pipeline integrity (schema, upstream sources, volume).")
if important_drift:
recs.append(f"CRITICAL: Important features {important_drift} are drifting. Trigger model retraining if performance degrades.")
else:
recs.append("Non-important features drifting—still investigate root cause.")
recs.append("Collect fresh labeled data for model evaluation on current distribution.")
recs.append("If covariate shift confirmed, retrain model with recent data.")
return {
'overall_drift_score': overall_score,
'overall_drift_level': level,
'per_feature_metrics': metrics.to_dict('index'),
'high_drift_features': high_drift,
'important_drift_features': important_drift,
'recommendations': recs,
'timestamp': pd.Timestamp.now().isoformat()
}