{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Benjamin Nweke",
  "title_listed": "How to Catch Data Drift When Every Feature Looks Normal",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/how-to-catch-data-drift-when-every-feature-looks-normal/",
  "publish_date": "2026-09-28",
  "corpus_stage": "",
  "notes": "",
  "id": "59575d822940",
  "collected_at": "2026-10-02T07:25:25",
  "title": "How to Catch Data Drift When Every Feature Looks Normal | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# How to Catch Data Drift When Every Feature Looks Normal\nDetect hidden shifts in feature relationships with adversarial validation and scikit-learn\n[Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nSeptember 28, 202610 min read\n![Conceptual illustration of machine learning drift monitoring showing three feature distribution charts marked as normal, while a central scatter plot highlights a hidden change in feature relationships affecting model performance.](../images/000.webp)\nImage by author (Generated with ChatGPT)\nA conceptual cover image illustrating hidden data drift in machine learning, where individual feature checks pass but changing relationships between features cause model performance to degrade in production.\nA specific kind of quiet follows a good validation run. Numbers on the screen, AUC at 0.91, and everyone nodding along in the morning meeting because, for once, nobody had a reason to ask a follow-up question.\nTrust me, it's a good feeling. But It's also one I've learned not to hold on to or trust so much.\nThe model finally went live that Friday. Nothing dramatic about it, no war room, no late night. Just a deploy that looked exactly like the dozen before it.\nBy Tuesday, something had gone wrong in a way that took a while to even notice. Precision on flagged cases had quietly gotten worse, and nothing about that showed up as an error. \nNo crash, no alert, no red line on any dashboard anyone was actually watching. \nIt just sat there getting worse, until a downstream team got tired of a review queue full of garbage flags and asked why. That's how it got found. Not a system catching itself. A person, annoyed enough to go looking.\nAnd here's the part that still bugs me a little: nothing in the code had changed. The model and the pipeline were exactly what they'd been the day before.\nWhat changed was the world underneath them. A new pricing tier had launched a few days earlier, and customers on it were transacting more often, at lower amounts each time. \nI checked one feature at a time, and none of it looked wrong: transaction value sat in a normal range, and so did transaction frequency. It was only when I looked at the two together that the data clearly became something else, and there was no check anywhere in the pipeline built to catch that.\nI had already set up drift monitoring before this and I genuinely thought I was covered. \nWell, it turned out I wasn't. \nThe check I had was doing exactly what I'd asked it to do, watching every feature individually, just as I'd built it to, and it would have sat there reporting green through the entire thing.\nWhich is a strange thing to sit with, honestly. The monitoring wasn't broken. And it wasn't lazy or half-built either. It was just answering a narrower question than the one that actually mattered.\n## The part that goes wrong quietly\nThat narrower question is the one most drift monitoring asks, mine included at the time. Has any single feature's distribution shifted? Take this week's values and training-time values, line them up as histograms, and get a number out.\nOn paper, that's not a bad idea. \nIt's just an incomplete one. \nIt works right up until the failure isn't in any single feature, but in how two features move _together_ , and that's a much easier way for real data to break than most write-ups admit.\nThe pricing tier thing is a clean example because nothing about it looks wrong in isolation. Run PSI on `avg_transaction_value` alone, fine. Run it on `num_transactions_30d` alone, also fine. The relationship between the two flipped, and PSI, by design, never looks at two columns at once. It can't. That's not a flaw in the metric so much as a boundary it was never built to cross.\nSo the question becomes: how do you check a relationship instead of a distribution? Turns out the answer isn't some exotic statistics you have to go learn. It's just asking a model to do the noticing for you.\n## Let a classifier do the noticing\nThe trick has a name, [adversarial validation](http://kdnuggets.com/2016/10/adversarial-validation-explained.html), and it makes it sound fancier than it is.\nLabel your training rows `0`, label a fresh batch of production rows `1`, and train a classifier to tell them apart. \nIf the two batches are really drawn from the same distribution, it can't do better than guessing, AUC near 0.5. If it _can_ separate them, something moved, and because the classifier gets every feature at once, it picks up exactly the kind of joint shift a column-by-column check walks straight past.\nHere's the setup, with a synthetic dataset so you can run it yourself instead of trusting me on faith:\npython\n\n```\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_selection import mutual_info_classif\n\nnp.random.seed(42)\n\nn = 5000\ndf = pd.DataFrame({\n    \"avg_transaction_value\": np.random.normal(150, 40, n),\n    \"num_transactions_30d\": np.random.poisson(12, n),\n    \"account_age_days\": np.random.exponential(400, n),\n    \"device_risk_score\": np.random.beta(2, 5, n),\n})\n\ndf[\"target\"] = (df[\"device_risk_score\"] * 3 + np.random.normal(0, 0.3, n) > 1.2).astype(int)\n# this is the kind of feature that sneaks into real datasets constantly -\n# a flag count that got backfilled after the outcome was already known\ndf[\"post_hoc_flag_count\"] = df[\"target\"] * np.random.poisson(2, n)\n\nX = df.drop(columns=[\"target\"])\ny = df[\"target\"]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n```\n\n## Before drift even matters, check for leakage\nIf you skip this part, you're monitoring drift on a model that was never trustworthy to begin with, so it goes first, even though it's less interesting.\nA feature with suspiciously high mutual information against the target is usually a feature that got computed using information that wouldn't have existed yet at prediction time. `post_hoc_flag_count` above is exactly that, the kind of column that looks predictive because it's cheating.\nThe first version of this guard I wrote just hard-raised on anything past a threshold, full stop, no exceptions. That lasted about one retrain. `device_risk_score` kept tripping it, and it's genuinely just a strong feature, not a leaky one. \nI'd go back and forth arguing with my own code every single run, until I got annoyed enough to fix it properly instead of just lowering the threshold, which was the lazy fix I almost shipped.\npython\n\n```\nimport logging\n\nlogger = logging.getLogger(\"pipeline.guards\")\n\n\nclass LeakageGuard(BaseEstimator, TransformerMixin):\n    \"\"\"\n    Hard-fails on features that look too good to be true. Deliberately\n    aggressive - the point is to make leakage annoying to ignore, not to\n    be a polite linter.\n    \"\"\"\n\n    def __init__(self, mi_threshold=0.5, corr_threshold=0.85, allowlist=None):\n        self.mi_threshold = mi_threshold\n        self.corr_threshold = corr_threshold\n        # columns already investigated and confirmed strong-not-leaky -\n        # without this every retrain re-triggers the same argument\n        self.allowlist = allowlist or []\n\n    def fit(self, X, y=None):\n        if y is None:\n            raise ValueError(\"LeakageGuard needs y - can't check leakage against nothing\")\n\n        numeric_cols = X.select_dtypes(include=np.number).columns.tolist()\n        skipped = set(X.columns) - set(numeric_cols)\n        if skipped:\n            # mutual_info_classif on object columns just gives you garbage\n            # scores, not an error, which is worse - loud > silent\n            logger.warning(\"LeakageGuard skipping non-numeric columns: %s\", skipped)\n\n        checkable = [c for c in numeric_cols if c not in self.allowlist]\n        if not checkable:\n            self.mi_scores_, self.corr_scores_ = {}, {}\n            return self\n\n        mi = mutual_info_classif(X[checkable], y, random_state=42)\n        self.mi_scores_ = dict(zip(checkable, mi))\n        self.corr_scores_ = {\n            c: abs(np.corrcoef(X[c], y)[0, 1]) for c in checkable\n        }\n\n        flagged = [\n            c for c in checkable\n            if self.mi_scores_[c] > self.mi_threshold or self.corr_scores_[c] > self.corr_threshold\n        ]\n        if flagged:\n            raise ValueError(\n                f\"Possible leakage in {flagged}. If any of these are legit strong \"\n                f\"predictors, add them to `allowlist` after you've actually checked.\"\n            )\n        return self\n\n    def transform(self, X):\n        return X\n```\n\n`LeakageGuard().fit(X_train, y_train)` raises on `post_hoc_flag_count` immediately, before anything gets trained. Good, that's the whole point. A model trained on that column reports a validation score that looks great and means nothing, because the leakage survives the split intact. \nIt only shows up once the feature stops existing in production, and by then it's not a code review comment anymore; it's someone asking uncomfortable questions in a retro.\n## Now the actual drift check\nI'll admit that the first draft of this detector didn't handle small batches at all. It just always ran cross-validated AUC, no matter how much data came in. \nThat's fine against a full day of production traffic, but it falls over against a thin canary batch, where a fold can end up with almost no positive examples and either throws an error or spits back a number that's really just noise wearing a lab coat.\nSo below a row threshold, it drops to a single train/test split instead. Less rigorous, and I'd rather admit that outright than pretend the tradeoff isn't there.\npython\n\n```\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import roc_auc_score\n\n\nclass AdversarialDriftDetector(BaseEstimator, TransformerMixin):\n    \"\"\"\n    Trains a classifier to tell reference data apart from new data. If it\n    can, something about the joint distribution moved - not necessarily\n    any single feature.\n    \"\"\"\n\n    def __init__(self, auc_threshold=0.65, cv_folds=5, min_rows_for_cv=200, random_state=42):\n        self.auc_threshold = auc_threshold\n        self.cv_folds = cv_folds\n        # below this, cross_val_score is more likely to error on a thin\n        # fold than tell you anything useful - learned that against a\n        # 90-row canary batch that kept failing for no obvious reason\n        self.min_rows_for_cv = min_rows_for_cv\n        self.random_state = random_state\n\n    def fit(self, X, y=None):\n        self.ref_df_ = X.select_dtypes(include=np.number).copy()\n        self.ref_cols_ = self.ref_df_.columns.tolist()\n        return self\n\n    def check(self, X_new):\n        missing = set(self.ref_cols_) - set(X_new.columns)\n        if missing:\n            raise ValueError(f\"X_new is missing columns the detector was fit on: {missing}\")\n\n        new_df = X_new[self.ref_cols_].copy()\n        if new_df.isna().any().any():\n            # don't silently drop rows here - a batch that's suddenly full\n            # of nulls is itself a drift signal worth knowing about\n            logger.warning(\n                \"check() got %d rows with NaNs, filling with column medians\",\n                new_df.isna().any(axis=1).sum(),\n            )\n            new_df = new_df.fillna(self.ref_df_.median())\n\n        combined = pd.concat([self.ref_df_, new_df], ignore_index=True)\n        labels = np.r_[np.zeros(len(self.ref_df_)), np.ones(len(new_df))]\n\n        rf = RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=self.random_state)\n\n        if len(new_df) < self.min_rows_for_cv:\n            Xtr, Xte, ytr, yte = train_test_split(\n                combined, labels, test_size=0.3, random_state=self.random_state, stratify=labels\n            )\n            rf.fit(Xtr, ytr)\n            auc = roc_auc_score(yte, rf.predict_proba(Xte)[:, 1])\n        else:\n            auc = cross_val_score(rf, combined, labels, cv=self.cv_folds, scoring=\"roc_auc\").mean()\n\n        drifted = auc > self.auc_threshold\n        top_features = None\n        if drifted:\n            rf.fit(combined, labels)\n            top_features = pd.Series(rf.feature_importances_, index=self.ref_cols_) \\\n                .sort_values(ascending=False).head(3)\n            logger.warning(\"Drift detected, auc=%.3f, top features: %s\", auc, top_features.index.tolist())\n\n        return {\"auc\": auc, \"drift_detected\": drifted, \"top_drift_features\": top_features}\n\n    def transform(self, X):\n        return X\n```\n\nAUC near 0.5, the classifier's guessing; nothing's changed. AUC past roughly 0.65, it found real structure telling the batches apart, and `top_drift_features` names the columns it leaned on, usually not the ones whose histograms moved the most, but the ones whose _relationship_ to everything else quietly flipped.\nReproducing the pricing-tier scenario from the top:\npython\n\n```\nX_train_clean = X_train.drop(columns=[\"post_hoc_flag_count\"])\n\ndetector = AdversarialDriftDetector(auc_threshold=0.65)\ndetector.fit(X_train_clean)\n\nX_production = X_train_clean.sample(1000, random_state=1).reset_index(drop=True)\n# each column's own range stays plausible on its own - it's the relationship\n# between them that flips, which is exactly what a per-feature check misses\nshift_mask = X_production[\"num_transactions_30d\"] > X_production[\"num_transactions_30d\"].median()\nX_production.loc[shift_mask, \"avg_transaction_value\"] *= 0.6\nX_production.loc[~shift_mask, \"num_transactions_30d\"] = (\n    X_production.loc[~shift_mask, \"num_transactions_30d\"] * 1.8\n).astype(int)\n\nresult = detector.check(X_production)\nprint(result[\"auc\"], result[\"drift_detected\"])\nprint(result[\"top_drift_features\"])\n```\n\nThat prints an AUC comfortably past the threshold, `drift_detected: True`, and the two shifted columns sitting right at the top. Not because either one moved dramatically alone. Because together, they told on themselves.\n## What this actually costs you\nI don't love pieces that sell a technique as a strict upgrade with zero downside, so here's where this one bites.\n**Compute is the first thing you'll feel:** A cross-validated classifier on every batch is a lot heavier than comparing two histograms, fine running daily or hourly. \nBut a genuinely bad idea the moment you're tempted to fire it per-request, and I'd bet money someone's already made that mistake somewhere.\n**The threshold isn't settled science:** 0.65 isn't handed down from a textbook the way PSI's [0.1/0.2 bands](https://coralogix.com/ai-blog/a-practical-introduction-to-population-stability-index-psi/) basically are. \nI picked it by trial and error, watched it flag too much at first, walked it up, and I still don't fully trust it on a dataset I haven't run it against. Budget real time here, not five minutes.\n**It's not a replacement for PSI, and I wouldn't want it to be:** Keep something cheap that only checks one feature at a time running as your baseline. \nReach for this the moment that baseline keeps coming back clean while performance keeps slipping anyway, because that specific combination, quiet dashboards paired with results that are quietly getting worse, is usually where a relationship, not a distribution, has shifted underneath you.\n**The leakage guard has its own blind spot too:** High mutual information isn't automatically leakage.\nSometimes it's just a good feature, and the guard genuinely can't tell those apart on its own. \nThat's what the allowlist is for, and it's less a workaround than an admission that this needs a human checking in occasionally, not a fire-and-forget rule.\nNone of this makes the technique not worth using. It just means going in with eyes open about what you're trading, compute and calibration time, for a check that catches something PSI structurally can't.\n···\n## Where this leaves you\nPer-feature drift checks answer one question, and they answer it well: did any single input move. They were never built to answer the harder one: whether the _relationships_ between inputs still hold up.\nThat second question is usually the one that actually breaks something in production, and it breaks it quietly, with every individual dashboard sitting there reporting green the entire time.\nYou don't need to tear out what you've already got. Keep PSI running, keep trusting it for what it's good at. Just stop assuming \"all clear\" means what you think it means, and add this as the thing you reach for the next time it says everything's fine and you don't quite believe it.\n···\n## Before you go!\nI write about the engineering decisions that decide whether a model holds up once it leaves validation. You can [subscribe to my newsletter](https://thatcsguy.substack.com/?r=79lldp&utm_campaign=pub-share-checklist) if you'd like more of that.\n**Connect With Me**\n  * [LinkedIn](http://www.linkedin.com/in/nwekebenjamin)\n  * [Substack](https://thatcsguy.substack.com/)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-4ad89a2fc5e69dde007d.jpeg)\nWritten By\n## [Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nBenjamin Nweke is a Computer Science graduate and technical writer exploring AI, machine learning, and data science. He writes about building reliable AI systems, model evaluation, agentic architectures, and the practical challenges that appear when machine learning moves beyond experiments. His work focuses on making technically complex ideas clear, useful, and grounded in real implementation.\n[See all from Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\n[Data Drift](https://towardsdatascience.com/tag/data-drift/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Mlops](https://towardsdatascience.com/tag/mlops/)[Model Monitoring](https://towardsdatascience.com/tag/model-monitoring/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&title=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&title=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&text=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/001.jpg)](https://towardsdatascience.com/how-ml-relates-to-ai-95a4f2e2c9cf/)\n## [How ML relates to AI](https://towardsdatascience.com/how-ml-relates-to-ai-95a4f2e2c9cf/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow does Machine Learning (ML) fit into the wonderful world of Artificial Intelligence (AI)?\n[John Mackie](https://towardsdatascience.com/author/johnfmackie/)\nJanuary 9, 20215 min read\n  * [![](../images/002.jpg)](https://towardsdatascience.com/sql-users-halve-the-length-of-some-of-your-queries-with-this-one-trick-c3c2c226cb35/)\n## [SQL users: Halve the length of (some of) your queries with this one trick](https://towardsdatascience.com/sql-users-halve-the-length-of-some-of-your-queries-with-this-one-trick-c3c2c226cb35/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThe QUALIFY clause is pure syntactic sugar\n[Matt Chapman](https://towardsdatascience.com/author/mattchapmanmsc/)\nMarch 29, 20235 min read\n  * [![](../images/003.jpg)](https://towardsdatascience.com/from-risk-to-asset-designing-a-practical-data-strategy-that-actually-works/)\n## [From Risk to Asset: Designing a Practical Data Strategy That Actually Works](https://towardsdatascience.com/from-risk-to-asset-designing-a-practical-data-strategy-that-actually-works/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nMake data work for your organization\n[Mike Huls](https://towardsdatascience.com/author/mikehuls/)\nApril 20, 202610 min read\n  * [![](../images/004.jpg)](https://towardsdatascience.com/equivalence-testing-b107979a65ae/)\n## [Evidence for the null hypothesis? A case of equivalence testing](https://towardsdatascience.com/equivalence-testing-b107979a65ae/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA statistical tool to use when the results are not significant (with example in R)\n[Rafael Valdece Sousa Bastos](https://towardsdatascience.com/author/rafavsbastos/)\nJanuary 24, 20215 min read\n  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/latest-picks-from-words-to-vectors-4e5dd8372eb5/)\n## [Latest picks: From Words To Vectors](https://towardsdatascience.com/latest-picks-from-words-to-vectors-4e5dd8372eb5/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nYour daily dose of data science\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nFebruary 9, 20211 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1/)\n## [The Underlying Dangers Behind Large Batch Training Schemes](https://towardsdatascience.com/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe Hows and Whys behind the Generalization Gap and How to Minimize it\n[Andy Wang](https://towardsdatascience.com/author/andy-wang/)\nNovember 12, 202210 min read\n  * [![](../images/007.png)](https://towardsdatascience.com/interactive-map-using-geographical-information-in-plotly-express-362081457600/)\n## [Interactive map using Geographical Information in Plotly Express](https://towardsdatascience.com/interactive-map-using-geographical-information-in-plotly-express-362081457600/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nVisualizations are very powerful tools for any data science project. It helps the reader to understand what is happening. For some dataset...\n[Tamjid Ahsan](https://towardsdatascience.com/author/tamjida/)\nOctober 11, 20212 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0/)\n## [5 Essential Tips to Improve the Readability of Your Python Code](https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0/)\n[](https://towardsdatascience.com/how-to-catch-data-drift-when-every-feature-looks-normal/)\nImproving your Python Code Through Documentation, Type Hinting and Proper Variable Names\n[Andy McDonald](https://towardsdatascience.com/author/andymcdonaldgeo/)\nJuly 22, 20227 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/10-coding-principles-that-no-one-will-teach-you-37d64b5081ef/)\n## [10 Coding principles that no one will teach you](https://towardsdatascience.com/10-coding-principles-that-no-one-will-teach-you-37d64b5081ef/)\n[Programming](https://towardsdatascience.com/category/programming/)\nIntroduction\n[Sreekiran A R](https://towardsdatascience.com/author/sreekiranar/)\nNovember 15, 20207 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "How to Catch Data Drift When Every Feature Looks Normal | Towards Data Science",
    "description": "Detect hidden shifts in feature relationships with adversarial validation and scikit-learn",
    "keywords": null,
    "author": "Benjamin Nweke",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "How to Catch Data Drift When Every Feature Looks Normal",
    "og:description": "Detect hidden shifts in feature relationships with adversarial validation and scikit-learn",
    "og:url": "https://towardsdatascience.com/how-to-catch-data-drift-when-every-feature-looks-normal/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/1790269202772_avp79v.webp",
    "og:image:width": "1672",
    "og:image:height": "941",
    "og:image:type": "image/webp",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Benjamin Nweke",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "10 min read",
    "article:published_time": "2026-09-28T11:00:01.923Z",
    "article:modified_time": "2026-09-28T11:00:01.923Z",
    "article:author": "https://towardsdatascience.com/author/benjaminnweke/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/59575d822940/code/block_000.txt",
      "chars": 988
    },
    {
      "language": "txt",
      "file": "attachments/59575d822940/code/block_001.txt",
      "chars": 2036
    },
    {
      "language": "txt",
      "file": "attachments/59575d822940/code/block_002.txt",
      "chars": 2823
    },
    {
      "language": "txt",
      "file": "attachments/59575d822940/code/block_003.txt",
      "chars": 799
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:01Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:01Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:01Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:01Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/benjaminnweke/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-drift/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/mlops/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/model-monitoring/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-ml-relates-to-ai-95a4f2e2c9cf/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/johnfmackie/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/sql-users-halve-the-length-of-some-of-your-queries-with-this-one-trick-c3c2c226cb35/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/mattchapmanmsc/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/from-risk-to-asset-designing-a-practical-data-strategy-that-actually-works/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/mikehuls/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "http://kdnuggets.com/2016/10/adversarial-validation-explained.html"
    },
    {
      "type": "external",
      "href": "https://coralogix.com/ai-blog/a-practical-introduction-to-population-stability-index-psi/"
    },
    {
      "type": "external",
      "href": "https://thatcsguy.substack.com/?r=79lldp"
    },
    {
      "type": "external",
      "href": "http://www.linkedin.com/in/nwekebenjamin"
    },
    {
      "type": "external",
      "href": "https://thatcsguy.substack.com/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=How+to+Catch+Data+Drift+When+Every+Feature+Looks+Normal&u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=How+to+Catch+Data+Drift+When+Every+Feature+Looks+Normal&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=How+to+Catch+Data+Drift+When+Every+Feature+Looks+Normal&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:30:10Z",
  "source_url": "https://towardsdatascience.com/how-to-catch-data-drift-when-every-feature-looks-normal/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# How to Catch Data Drift When Every Feature Looks Normal\nDetect hidden shifts in feature relationships with adversarial validation and scikit-learn\n[Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nSeptember 28, 202610 min read\n![Conceptual illustration of machine learning drift monitoring showing three feature distribution charts marked as normal, while a central scatter plot highlights a hidden change in feature relationships affecting model performance.](https://assets.insightmediagroup.io/media/1790269202772_avp79v.webp)\nImage by author (Generated with ChatGPT)\nA conceptual cover image illustrating hidden data drift in machine learning, where individual feature checks pass but changing relationships between features cause model performance to degrade in production.\nA specific kind of quiet follows a good validation run. Numbers on the screen, AUC at 0.91, and everyone nodding along in the morning meeting because, for once, nobody had a reason to ask a follow-up question.\nTrust me, it's a good feeling. But It's also one I've learned not to hold on to or trust so much.\nThe model finally went live that Friday. Nothing dramatic about it, no war room, no late night. Just a deploy that looked exactly like the dozen before it.\nBy Tuesday, something had gone wrong in a way that took a while to even notice. Precision on flagged cases had quietly gotten worse, and nothing about that showed up as an error. \nNo crash, no alert, no red line on any dashboard anyone was actually watching. \nIt just sat there getting worse, until a downstream team got tired of a review queue full of garbage flags and asked why. That's how it got found. Not a system catching itself. A person, annoyed enough to go looking.\nAnd here's the part that still bugs me a little: nothing in the code had changed. The model and the pipeline were exactly what they'd been the day before.\nWhat changed was the world underneath them. A new pricing tier had launched a few days earlier, and customers on it were transacting more often, at lower amounts each time. \nI checked one feature at a time, and none of it looked wrong: transaction value sat in a normal range, and so did transaction frequency. It was only when I looked at the two together that the data clearly became something else, and there was no check anywhere in the pipeline built to catch that.\nI had already set up drift monitoring before this and I genuinely thought I was covered. \nWell, it turned out I wasn't. \nThe check I had was doing exactly what I'd asked it to do, watching every feature individually, just as I'd built it to, and it would have sat there reporting green through the entire thing.\nWhich is a strange thing to sit with, honestly. The monitoring wasn't broken. And it wasn't lazy or half-built either. It was just answering a narrower question than the one that actually mattered.\n## The part that goes wrong quietly\nThat narrower question is the one most drift monitoring asks, mine included at the time. Has any single feature's distribution shifted? Take this week's values and training-time values, line them up as histograms, and get a number out.\nOn paper, that's not a bad idea. \nIt's just an incomplete one. \nIt works right up until the failure isn't in any single feature, but in how two features move _together_ , and that's a much easier way for real data to break than most write-ups admit.\nThe pricing tier thing is a clean example because nothing about it looks wrong in isolation. Run PSI on `avg_transaction_value` alone, fine. Run it on `num_transactions_30d` alone, also fine. The relationship between the two flipped, and PSI, by design, never looks at two columns at once. It can't. That's not a flaw in the metric so much as a boundary it was never built to cross.\nSo the question becomes: how do you check a relationship instead of a distribution? Turns out the answer isn't some exotic statistics you have to go learn. It's just asking a model to do the noticing for you.\n## Let a classifier do the noticing\nThe trick has a name, [adversarial validation](http://kdnuggets.com/2016/10/adversarial-validation-explained.html), and it makes it sound fancier than it is.\nLabel your training rows `0`, label a fresh batch of production rows `1`, and train a classifier to tell them apart. \nIf the two batches are really drawn from the same distribution, it can't do better than guessing, AUC near 0.5. If it _can_ separate them, something moved, and because the classifier gets every feature at once, it picks up exactly the kind of joint shift a column-by-column check walks straight past.\nHere's the setup, with a synthetic dataset so you can run it yourself instead of trusting me on faith:\npython\n\n```\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_selection import mutual_info_classif\n\nnp.random.seed(42)\n\nn = 5000\ndf = pd.DataFrame({\n    \"avg_transaction_value\": np.random.normal(150, 40, n),\n    \"num_transactions_30d\": np.random.poisson(12, n),\n    \"account_age_days\": np.random.exponential(400, n),\n    \"device_risk_score\": np.random.beta(2, 5, n),\n})\n\ndf[\"target\"] = (df[\"device_risk_score\"] * 3 + np.random.normal(0, 0.3, n) > 1.2).astype(int)\n# this is the kind of feature that sneaks into real datasets constantly -\n# a flag count that got backfilled after the outcome was already known\ndf[\"post_hoc_flag_count\"] = df[\"target\"] * np.random.poisson(2, n)\n\nX = df.drop(columns=[\"target\"])\ny = df[\"target\"]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n```\n\n## Before drift even matters, check for leakage\nIf you skip this part, you're monitoring drift on a model that was never trustworthy to begin with, so it goes first, even though it's less interesting.\nA feature with suspiciously high mutual information against the target is usually a feature that got computed using information that wouldn't have existed yet at prediction time. `post_hoc_flag_count` above is exactly that, the kind of column that looks predictive because it's cheating.\nThe first version of this guard I wrote just hard-raised on anything past a threshold, full stop, no exceptions. That lasted about one retrain. `device_risk_score` kept tripping it, and it's genuinely just a strong feature, not a leaky one. \nI'd go back and forth arguing with my own code every single run, until I got annoyed enough to fix it properly instead of just lowering the threshold, which was the lazy fix I almost shipped.\npython\n\n```\nimport logging\n\nlogger = logging.getLogger(\"pipeline.guards\")\n\n\nclass LeakageGuard(BaseEstimator, TransformerMixin):\n    \"\"\"\n    Hard-fails on features that look too good to be true. Deliberately\n    aggressive - the point is to make leakage annoying to ignore, not to\n    be a polite linter.\n    \"\"\"\n\n    def __init__(self, mi_threshold=0.5, corr_threshold=0.85, allowlist=None):\n        self.mi_threshold = mi_threshold\n        self.corr_threshold = corr_threshold\n        # columns already investigated and confirmed strong-not-leaky -\n        # without this every retrain re-triggers the same argument\n        self.allowlist = allowlist or []\n\n    def fit(self, X, y=None):\n        if y is None:\n            raise ValueError(\"LeakageGuard needs y - can't check leakage against nothing\")\n\n        numeric_cols = X.select_dtypes(include=np.number).columns.tolist()\n        skipped = set(X.columns) - set(numeric_cols)\n        if skipped:\n            # mutual_info_classif on object columns just gives you garbage\n            # scores, not an error, which is worse - loud > silent\n            logger.warning(\"LeakageGuard skipping non-numeric columns: %s\", skipped)\n\n        checkable = [c for c in numeric_cols if c not in self.allowlist]\n        if not checkable:\n            self.mi_scores_, self.corr_scores_ = {}, {}\n            return self\n\n        mi = mutual_info_classif(X[checkable], y, random_state=42)\n        self.mi_scores_ = dict(zip(checkable, mi))\n        self.corr_scores_ = {\n            c: abs(np.corrcoef(X[c], y)[0, 1]) for c in checkable\n        }\n\n        flagged = [\n            c for c in checkable\n            if self.mi_scores_[c] > self.mi_threshold or self.corr_scores_[c] > self.corr_threshold\n        ]\n        if flagged:\n            raise ValueError(\n                f\"Possible leakage in {flagged}. If any of these are legit strong \"\n                f\"predictors, add them to `allowlist` after you've actually checked.\"\n            )\n        return self\n\n    def transform(self, X):\n        return X\n```\n\n`LeakageGuard().fit(X_train, y_train)` raises on `post_hoc_flag_count` immediately, before anything gets trained. Good, that's the whole point. A model trained on that column reports a validation score that looks great and means nothing, because the leakage survives the split intact. \nIt only shows up once the feature stops existing in production, and by then it's not a code review comment anymore; it's someone asking uncomfortable questions in a retro.\n## Now the actual drift check\nI'll admit that the first draft of this detector didn't handle small batches at all. It just always ran cross-validated AUC, no matter how much data came in. \nThat's fine against a full day of production traffic, but it falls over against a thin canary batch, where a fold can end up with almost no positive examples and either throws an error or spits back a number that's really just noise wearing a lab coat.\nSo below a row threshold, it drops to a single train/test split instead. Less rigorous, and I'd rather admit that outright than pretend the tradeoff isn't there.\npython\n\n```\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import roc_auc_score\n\n\nclass AdversarialDriftDetector(BaseEstimator, TransformerMixin):\n    \"\"\"\n    Trains a classifier to tell reference data apart from new data. If it\n    can, something about the joint distribution moved - not necessarily\n    any single feature.\n    \"\"\"\n\n    def __init__(self, auc_threshold=0.65, cv_folds=5, min_rows_for_cv=200, random_state=42):\n        self.auc_threshold = auc_threshold\n        self.cv_folds = cv_folds\n        # below this, cross_val_score is more likely to error on a thin\n        # fold than tell you anything useful - learned that against a\n        # 90-row canary batch that kept failing for no obvious reason\n        self.min_rows_for_cv = min_rows_for_cv\n        self.random_state = random_state\n\n    def fit(self, X, y=None):\n        self.ref_df_ = X.select_dtypes(include=np.number).copy()\n        self.ref_cols_ = self.ref_df_.columns.tolist()\n        return self\n\n    def check(self, X_new):\n        missing = set(self.ref_cols_) - set(X_new.columns)\n        if missing:\n            raise ValueError(f\"X_new is missing columns the detector was fit on: {missing}\")\n\n        new_df = X_new[self.ref_cols_].copy()\n        if new_df.isna().any().any():\n            # don't silently drop rows here - a batch that's suddenly full\n            # of nulls is itself a drift signal worth knowing about\n            logger.warning(\n                \"check() got %d rows with NaNs, filling with column medians\",\n                new_df.isna().any(axis=1).sum(),\n            )\n            new_df = new_df.fillna(self.ref_df_.median())\n\n        combined = pd.concat([self.ref_df_, new_df], ignore_index=True)\n        labels = np.r_[np.zeros(len(self.ref_df_)), np.ones(len(new_df))]\n\n        rf = RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=self.random_state)\n\n        if len(new_df) < self.min_rows_for_cv:\n            Xtr, Xte, ytr, yte = train_test_split(\n                combined, labels, test_size=0.3, random_state=self.random_state, stratify=labels\n            )\n            rf.fit(Xtr, ytr)\n            auc = roc_auc_score(yte, rf.predict_proba(Xte)[:, 1])\n        else:\n            auc = cross_val_score(rf, combined, labels, cv=self.cv_folds, scoring=\"roc_auc\").mean()\n\n        drifted = auc > self.auc_threshold\n        top_features = None\n        if drifted:\n            rf.fit(combined, labels)\n            top_features = pd.Series(rf.feature_importances_, index=self.ref_cols_) \\\n                .sort_values(ascending=False).head(3)\n            logger.warning(\"Drift detected, auc=%.3f, top features: %s\", auc, top_features.index.tolist())\n\n        return {\"auc\": auc, \"drift_detected\": drifted, \"top_drift_features\": top_features}\n\n    def transform(self, X):\n        return X\n```\n\nAUC near 0.5, the classifier's guessing; nothing's changed. AUC past roughly 0.65, it found real structure telling the batches apart, and `top_drift_features` names the columns it leaned on, usually not the ones whose histograms moved the most, but the ones whose _relationship_ to everything else quietly flipped.\nReproducing the pricing-tier scenario from the top:\npython\n\n```\nX_train_clean = X_train.drop(columns=[\"post_hoc_flag_count\"])\n\ndetector = AdversarialDriftDetector(auc_threshold=0.65)\ndetector.fit(X_train_clean)\n\nX_production = X_train_clean.sample(1000, random_state=1).reset_index(drop=True)\n# each column's own range stays plausible on its own - it's the relationship\n# between them that flips, which is exactly what a per-feature check misses\nshift_mask = X_production[\"num_transactions_30d\"] > X_production[\"num_transactions_30d\"].median()\nX_production.loc[shift_mask, \"avg_transaction_value\"] *= 0.6\nX_production.loc[~shift_mask, \"num_transactions_30d\"] = (\n    X_production.loc[~shift_mask, \"num_transactions_30d\"] * 1.8\n).astype(int)\n\nresult = detector.check(X_production)\nprint(result[\"auc\"], result[\"drift_detected\"])\nprint(result[\"top_drift_features\"])\n```\n\nThat prints an AUC comfortably past the threshold, `drift_detected: True`, and the two shifted columns sitting right at the top. Not because either one moved dramatically alone. Because together, they told on themselves.\n## What this actually costs you\nI don't love pieces that sell a technique as a strict upgrade with zero downside, so here's where this one bites.\n**Compute is the first thing you'll feel:** A cross-validated classifier on every batch is a lot heavier than comparing two histograms, fine running daily or hourly. \nBut a genuinely bad idea the moment you're tempted to fire it per-request, and I'd bet money someone's already made that mistake somewhere.\n**The threshold isn't settled science:** 0.65 isn't handed down from a textbook the way PSI's [0.1/0.2 bands](https://coralogix.com/ai-blog/a-practical-introduction-to-population-stability-index-psi/) basically are. \nI picked it by trial and error, watched it flag too much at first, walked it up, and I still don't fully trust it on a dataset I haven't run it against. Budget real time here, not five minutes.\n**It's not a replacement for PSI, and I wouldn't want it to be:** Keep something cheap that only checks one feature at a time running as your baseline. \nReach for this the moment that baseline keeps coming back clean while performance keeps slipping anyway, because that specific combination, quiet dashboards paired with results that are quietly getting worse, is usually where a relationship, not a distribution, has shifted underneath you.\n**The leakage guard has its own blind spot too:** High mutual information isn't automatically leakage.\nSometimes it's just a good feature, and the guard genuinely can't tell those apart on its own. \nThat's what the allowlist is for, and it's less a workaround than an admission that this needs a human checking in occasionally, not a fire-and-forget rule.\nNone of this makes the technique not worth using. It just means going in with eyes open about what you're trading, compute and calibration time, for a check that catches something PSI structurally can't.\n···\n## Where this leaves you\nPer-feature drift checks answer one question, and they answer it well: did any single input move. They were never built to answer the harder one: whether the _relationships_ between inputs still hold up.\nThat second question is usually the one that actually breaks something in production, and it breaks it quietly, with every individual dashboard sitting there reporting green the entire time.\nYou don't need to tear out what you've already got. Keep PSI running, keep trusting it for what it's good at. Just stop assuming \"all clear\" means what you think it means, and add this as the thing you reach for the next time it says everything's fine and you don't quite believe it.\n···\n## Before you go!\nI write about the engineering decisions that decide whether a model holds up once it leaves validation. You can [subscribe to my newsletter](https://thatcsguy.substack.com/?r=79lldp&utm_campaign=pub-share-checklist) if you'd like more of that.\n**Connect With Me**\n  * [LinkedIn](http://www.linkedin.com/in/nwekebenjamin)\n  * [Substack](https://thatcsguy.substack.com/)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657271062_x78p7k.jpeg)\nWritten By\n## [Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nBenjamin Nweke is a Computer Science graduate and technical writer exploring AI, machine learning, and data science. He writes about building reliable AI systems, model evaluation, agentic architectures, and the practical challenges that appear when machine learning moves beyond experiments. His work focuses on making technically complex ideas clear, useful, and grounded in real implementation.\n[See all from Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\n[Data Drift](https://towardsdatascience.com/tag/data-drift/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Mlops](https://towardsdatascience.com/tag/mlops/)[Model Monitoring](https://towardsdatascience.com/tag/model-monitoring/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&title=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&title=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-catch-data-drift-when-every-feature-looks-normal%2F&text=How%20to%20Catch%20Data%20Drift%20When%20Every%20Feature%20Looks%20Normal)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0h7jstXkkmH5L5S-U-scaled.jpg)](https://towardsdatascience.com/how-ml-relates-to-ai-95a4f2e2c9cf/)\n## [How ML relates to AI](https://towardsdatascience.com/how-ml-relates-to-ai-95a4f2e2c9cf/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHow does Machine Learning (ML) fit into the wonderful world of Artificial Intelligence (AI)?\n[John Mackie](https://towardsdatascience.com/author/johnfmackie/)\nJanuary 9, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/0w1sjIIYFNNweLetm.jpg)](https://towardsdatascience.com/sql-users-halve-the-length-of-some-of-your-queries-with-this-one-trick-c3c2c226cb35/)\n## [SQL users: Halve the length of (some of) your queries with this one trick](https://towardsdatascience.com/sql-users-halve-the-length-of-some-of-your-queries-with-this-one-trick-c3c2c226cb35/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThe QUALIFY clause is pure syntactic sugar\n[Matt Chapman](https://towardsdatascience.com/author/mattchapmanmsc/)\nMarch 29, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/datastrategy.jpg)](https://towardsdatascience.com/from-risk-to-asset-designing-a-practical-data-strategy-that-actually-works/)\n## [From Risk to Asset: Designing a Practical Data Strategy That Actually Works](https://towardsdatascience.com/from-risk-to-asset-designing-a-practical-data-strategy-that-actually-works/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nMake data work for your organization\n[Mike Huls](https://towardsdatascience.com/author/mikehuls/)\nApril 20, 202610 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0-_dQCp9evWQ2yQlw-scaled.jpg)](https://towardsdatascience.com/equivalence-testing-b107979a65ae/)\n## [Evidence for the null hypothesis? A case of equivalence testing](https://towardsdatascience.com/equivalence-testing-b107979a65ae/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA statistical tool to use when the results are not significant (with example in R)\n[Rafael Valdece Sousa Bastos](https://towardsdatascience.com/author/rafavsbastos/)\nJanuary 24, 20215 min read\n  * [![](https://towardsdatascience.com/images/fallback-image.jpg)](https://towardsdatascience.com/latest-picks-from-words-to-vectors-4e5dd8372eb5/)\n## [Latest picks: From Words To Vectors](https://towardsdatascience.com/latest-picks-from-words-to-vectors-4e5dd8372eb5/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nYour daily dose of data science\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nFebruary 9, 20211 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/0-0R43xTwwjG-E_G-scaled.jpg)](https://towardsdatascience.com/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1/)\n## [The Underlying Dangers Behind Large Batch Training Schemes](https://towardsdatascience.com/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe Hows and Whys behind the Generalization Gap and How to Minimize it\n[Andy Wang](https://towardsdatascience.com/author/andy-wang/)\nNovember 12, 202210 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/1otXaBLw4hOAKp8Ou2YWQqA.png)](https://towardsdatascience.com/interactive-map-using-geographical-information-in-plotly-express-362081457600/)\n## [Interactive map using Geographical Information in Plotly Express](https://towardsdatascience.com/interactive-map-using-geographical-information-in-plotly-express-362081457600/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nVisualizations are very powerful tools for any data science project. It helps the reader to understand what is happening. For some dataset...\n[Tamjid Ahsan](https://towardsdatascience.com/author/tamjida/)\nOctober 11, 20212 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/0N8XFZSa9ls_kO5El-scaled.jpg)](https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0/)\n## [5 Essential Tips to Improve the Readability of Your Python Code](https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0/)\n[](https://towardsdatascience.com/how-to-catch-data-drift-when-every-feature-looks-normal/)\nImproving your Python Code Through Documentation, Type Hinting and Proper Variable Names\n[Andy McDonald](https://towardsdatascience.com/author/andymcdonaldgeo/)\nJuly 22, 20227 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1UeiEZ1ttWidisLX_vw9SSQ.png)](https://towardsdatascience.com/10-coding-principles-that-no-one-will-teach-you-37d64b5081ef/)\n## [10 Coding principles that no one will teach you](https://towardsdatascience.com/10-coding-principles-that-no-one-will-teach-you-37d64b5081ef/)\n[Programming](https://towardsdatascience.com/category/programming/)\nIntroduction\n[Sreekiran A R](https://towardsdatascience.com/author/sreekiranar/)\nNovember 15, 20207 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/59575d822940/pages/",
  "body_markdown_path": "attachments/59575d822940/pages/archived-body.md",
  "local_html": "attachments/59575d822940/pages/archived-body.html",
  "body_source": "prior_capture"
}