BT San Technology

30 April 2026

Inspection AI Used to Be Accurate and Now Misses: Tracking Model Drift on the Line

26 min read · Machine vision

Illustration: two batches of the same part with slightly different surface colour, a monitor behind showing a chart drifting out of its normal band
AI-generated illustration

An AI inspection system has run for months without trouble. Then one day the shift supervisor says an unusual number of parts are being rejected, or defective parts are reaching the end of the line that the system used to catch. The first question everyone asks is whether the model has degraded. But a model is a file that does not change by itself. What can change is the images fed into it, and the products moving past the camera.

This article makes that question answerable with numbers. It starts by separating two kinds of drift, then builds a Python script using plain numpy that compares each week's data against a reference window using PSI and KS, and looks at the reject rate alongside samples confirmed by an inspector. It runs on 11 weeks of made-up data with two events built in: a lighting shift and a new product variant. Managers can read the explanations and tables to get the picture, and engineers can run the code and follow along.

The real problem: inspection results change and nobody touched the model

Consider three hypothetical scenarios. They are not projects of any BT San customer.

  • A plastic parts factory: the lamp above the conveyor ages slowly and the images get a little darker each week, until one day the model becomes less confident. The reject rate barely moves, so nobody notices until defective parts escape.
  • A cap and packaging factory: production adds a new color variant to the existing line. The model never saw this color during training and rejects several times as many good parts. Inspectors have to open the pile of rejected parts every shift.
  • A metal parts assembly line: the raw material supplier changes, and the surface finish of the parts is slightly different. The model's confidence drops across the whole lot, although the parts pass the customer's criteria as usual.

These three cases differ in cause, but the only number visible right away is usually the reject rate, which is slow and in some cases does not move at all. So you need to watch the distribution of the input data and the model's outputs together, and you need people to confirm real samples as an anchor.

Two kinds of drift: the data changes, or the meaning changes

Data drift means the distribution of incoming data has changed from what it was at training time. In image inspection that means images that are brighter or darker, a different surface color, or a new product variant. The Evidently documentation defines it this way: data drift, or feature drift, means a change in the distribution of the input data. Concept drift means the relationship between the input and the target changes. The image looks the same but the meaning of "defective" has changed, for example when a customer becomes stricter and no longer accepts a scratch of this size.

data driftconcept drift
What changesThe incoming images (light, color, product variant, camera shifted)The meaning of defective versus good (standards, customer requirements)
How you see itImage statistics and model confidence compared with a reference window, with no need to wait for labelsYou need new labels from people, compared against the model's answers
Example on a lineA lamp that has aged, a new color variantThe dent requirement changes from 1 mm to 0.5 mm
First fixCheck the lighting, camera and fixture first, then consider adding training dataReview the criteria with QC, then relabel the data to the new criteria
The definitions follow the Evidently documentation (accessed 2026-11-21). The example and fix columns are the author's summary.

The two can happen together, and the same documentation states that concept drift can occur without data drift. The script in this article catches data drift directly. Concept drift is caught only through samples confirmed by an inspector. If nobody checks, the system has no way of knowing the criteria have changed.

What the documentation says: what we know and what we must not assume

TopicWhat the documentation saysEffect on what we write
Data drift and how to measure itUltralytics explains that data drift is when the data the model meets differs from what it was trained on, and recommends detection methods such as the Kolmogorov-Smirnov test and the Population Stability IndexUse these two statistics as the core
Two-sample KS guideSciPy states that ks_2samp compares the distributions of two independent samples. The statistic is the maximum absolute difference between the empirical CDFs, and it assumes the data come from a continuous distributionCan be written ourselves with sort and searchsorted. Data with only a few distinct integer values is not suitable
Critical value of KSWikipedia gives the criterion that D is greater than c(alpha) times the square root of (n+m)/(n m), where c(alpha) equals the square root of (-ln(alpha/2)/2), and notes that it is an approximation and is not accurate when samples are smallUsed in the script, and weeks with too few samples are skipped
Large samples make it too sensitiveEvidently reports that large datasets make small differences look statistically significant even though they may not matter in practice. KS is too sensitive, while PSI gives results that do not depend on sample sizeLet PSI decide the ALERT level and use KS only for WARN
PSI thresholdsThe Evidently article cites the common rule: below 0.1 no change, 0.1 to 0.2 moderate change, 0.2 and above large change. Elsewhere 0.25 may be used, so these are semi-convention values, not a standardSet 0.10 and 0.20 as defaults, then tune per line
Baseline and alertVertex AI Model Monitoring compares new data against a baseline with a distance score and alerts when it exceeds a user-set threshold per feature, with a default of 0.3Same idea as the script, but one vendor's default cannot be applied directly to our line
RetrainingUltralytics recommends monitoring performance continuously, setting alerts for anomalies, retraining when performance drops significantly or data drift is found, and checking the new model on a separate test setConsistent with the pre-retraining gate at the end of the article
Summarized from the Ultralytics, SciPy, Wikipedia, Evidently and Google Cloud documentation as of the access date 2026-11-21. For the real details, read the documentation of the tool you use.

Overview of the example

All the code is in the folder examples/ai-model-drift-production-monitoring/. It uses only Python 3 with numpy, with no scipy or sklearn and no internet connection. Every row of data was made up by a data generator with a fixed seed. It does not come from a real camera or line.

FilePurpose
drift.pyPSI, KS and the KS critical value, written with numpy
simulate.pyGenerates 11 weeks of data with a lighting shift, a new product variant, a low-image week and corrupted rows
weekly_samples.csvThe resulting data, 4,044 rows (including 4 deliberately corrupted rows)
monitor.pyReads the data, checks for corrupted rows, compares against the reference weeks, and produces a report and alerts
test_drift.pyA unittest suite of 10 cases

Events in the data: weeks 1 to 4 are normal and serve as the reference window. In week 5 only 40 images were collected. In weeks 6 to 7 the brightness shifts up by 8 levels (from a mean of 128 with a standard deviation of 6). Week 8 returns to normal after the lighting is fixed. In weeks 9 to 11, 35% of the products are a new variant the model does not recognize.

Step 1, PSI: how far has the distribution moved

PSI divides values into bins and compares the proportion of new data against the reference data in each bin. It is the sum of (new proportion minus old proportion) times ln(new proportion divided by old proportion). The larger it is, the more the distribution differs from before. The bin edges in the example come from quantiles of the reference window, giving 10 bins with roughly equal amounts of data, and the two ends are open. Values outside the reference range therefore fall into the end bins instead of disappearing.

drift.py · lines 7–21
def make_bins(reference, n_bins=10):
    """ขอบ bin จากควอนไทล์ของชุดอ้างอิง ปลายทั้งสองเปิดเป็น -inf/+inf"""
    ref = np.asarray(reference, dtype=float)
    edges = np.unique(np.quantile(ref, np.linspace(0, 1, n_bins + 1)[1:-1]))
    return np.concatenate(([-np.inf], edges, [np.inf]))


def psi(reference, current, n_bins=10):
    """Population Stability Index = sum((cur% - ref%) * ln(cur% / ref%))"""
    edges = make_bins(reference, n_bins)
    ref_p = np.histogram(reference, edges)[0] / len(reference)
    cur_p = np.histogram(current, edges)[0] / len(current)
    ref_p = np.clip(ref_p, EPS, None)
    cur_p = np.clip(cur_p, EPS, None)
    return float(np.sum((cur_p - ref_p) * np.log(cur_p / ref_p)))
drift.py: bin edges from quantiles, and PSI

A point to watch: an empty bin makes ln infinite. The example therefore sets a minimum proportion of 0.0001, a simple method that carries a simplified: warning in the code. A real system might use another kind of smoothing or merge bins that hold too little data, and it must use the same bin edges every week. If you recompute the edges each week, the numbers cannot be compared.

Step 2, KS: the maximum distance between two CDFs

KS needs no bins. It takes the empirical cumulative distribution functions of the two sets and finds the point where they are farthest apart. The value is between 0 and 1. The advantage is that there is no bin parameter. The disadvantage, as the table above says, is that it becomes too sensitive when there are many samples, so we compare it with a critical value that depends on sample size and use it only for the WARN level.

drift.py · lines 24–37
def ks_stat(reference, current):
    """ระยะห่างสูงสุดระหว่าง CDF เชิงประจักษ์ของสองชุด (ไม่ต้องสมมติรูปแจกแจง)"""
    a = np.sort(np.asarray(reference, dtype=float))
    b = np.sort(np.asarray(current, dtype=float))
    grid = np.concatenate((a, b))
    cdf_a = np.searchsorted(a, grid, side="right") / len(a)
    cdf_b = np.searchsorted(b, grid, side="right") / len(b)
    return float(np.max(np.abs(cdf_a - cdf_b)))


def ks_critical(n, m, alpha=0.01):
    """ค่าวิกฤตแบบ asymptotic: c(alpha) * sqrt((n+m)/(n*m))"""
    c = np.sqrt(-0.5 * np.log(alpha / 2))
    return float(c * np.sqrt((n + m) / (n * m)))
drift.py: two-sample KS and the asymptotic critical value

This critical value is an approximation for large samples and assumes continuous data. Model confidence that is squeezed close to 1 on almost every image, or pixel counts that are integers with few distinct values and many repeats, will make the result inaccurate. Always read it together with PSI.

Step 3: read the data, check for corrupted rows, and set the thresholds

Data from cameras and logging systems is occasionally corrupted: empty values, nan, a confidence above 1, or a week column that is text. If these go into the PSI calculation, the whole week breaks, or worse, it gives numbers that look reasonable but are wrong. The reader therefore checks row by row, drops corrupted rows while counting the reasons, and prints them in the report.

monitor.py · lines 10–44
CONFIG = {
    "ref_weeks": (1, 2, 3, 4),
    "min_samples": 100,      # น้อยกว่านี้ไม่ตัดสิน
    "psi_warn": 0.10, "psi_alert": 0.20,
    "ks_alpha": 0.01,
    "reject_rel_alert": 0.5,  # อัตราคัดออกเพิ่มจากอ้างอิงเกิน 50% เทียบสัดส่วน
    "min_confirmed": 10, "precision_alert": 0.7,
}
FEATURES = ("confidence", "brightness", "defect_area")


def load(path):
    """คืน (ข้อมูลตามสัปดาห์, จำนวนแถวที่ถูกทิ้ง พร้อมเหตุผล)"""
    weeks, dropped = {}, {}
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            try:
                week = int(row["week"])
                vals = [float(row[k]) for k in FEATURES]
                rejected = int(row["rejected"])
                if not all(math.isfinite(v) for v in vals):
                    raise ValueError("ไม่ใช่ตัวเลขจำกัด")
                if not 0 <= vals[0] <= 1:
                    raise ValueError("confidence นอกช่วง 0-1")
                if rejected not in (0, 1):
                    raise ValueError("rejected ต้องเป็น 0/1")
            except (ValueError, KeyError, TypeError) as e:
                # simplified: ใช้ข้อความ error ของ Python เป็นเหตุผล ของจริงควรแยกรหัสเหตุผลเอง
                reason = str(e).split(":")[0][:40]
                dropped[reason] = dropped.get(reason, 0) + 1
                continue
            confirmed = row["confirmed_defect"]
            weeks.setdefault(week, []).append(
                (*vals, rejected, None if confirmed == "" else int(confirmed)))
    return weeks, dropped
monitor.py: the thresholds (CONFIG) and the CSV reader that drops corrupted rows

All the values in CONFIG are demonstration values. See the section on per-line thresholds below for why you must tune them.

Step 4: weekly evaluation: the distribution, the reject rate, and samples confirmed by a person

The evaluate function takes one week of data and the reference data. It computes PSI and KS for three variables: the model's confidence, the mean brightness of the image, and the fraction of area detected as a defect. It then looks at the reject rate (prediction rate) and at the precision of the rejected items, taken from samples confirmed by an inspector.

monitor.py · lines 51–78
def evaluate(week_rows, ref_rows, cfg=CONFIG):
    """คืน (ตัวเลขของสัปดาห์, รายการแจ้งเตือน) สำหรับสัปดาห์เดียว"""
    n = len(week_rows)
    if n < cfg["min_samples"]:
        return {"n": n}, [("SKIP", f"ตัวอย่างน้อยเกินไป ({n} < {cfg['min_samples']}) ไม่ตัดสิน")]
    m, alerts = {"n": n}, []
    for i, name in enumerate(FEATURES):
        ref, cur = column(ref_rows, i), column(week_rows, i)
        m[f"psi_{name}"] = psi(ref, cur)
        m[f"ks_{name}"] = ks_stat(ref, cur)
        crit = ks_critical(len(ref), n, cfg["ks_alpha"])
        if m[f"psi_{name}"] >= cfg["psi_alert"]:
            alerts.append(("ALERT", f"PSI {name} = {m[f'psi_{name}']:.2f}"))
        elif m[f"psi_{name}"] >= cfg["psi_warn"]:
            alerts.append(("WARN", f"PSI {name} = {m[f'psi_{name}']:.2f}"))
        if m[f"ks_{name}"] > crit:
            alerts.append(("WARN", f"KS {name} = {m[f'ks_{name}']:.3f} > {crit:.3f}"))
    ref_rate = column(ref_rows, 3).mean()
    m["reject_rate"] = column(week_rows, 3).mean()
    if m["reject_rate"] > ref_rate * (1 + cfg["reject_rel_alert"]):
        alerts.append(("ALERT", f"อัตราคัดออก {m['reject_rate']:.1%} (อ้างอิง {ref_rate:.1%})"))
    conf = [r[4] for r in week_rows if r[3] == 1 and r[4] is not None]
    m["confirmed_n"] = len(conf)
    if len(conf) >= cfg["min_confirmed"]:
        m["precision"] = sum(conf) / len(conf)
        if m["precision"] < cfg["precision_alert"]:
            alerts.append(("ALERT", f"ผู้ตรวจยืนยันว่าเสียจริงเพียง {m['precision']:.0%} ของที่คัดออก (n={len(conf)})"))
    return m, alerts
monitor.py: evaluate one week, then return the numbers and the list of alerts
  • A week with fewer samples than min_samples is skipped, with the reason given. We do not judge from 40 images, because both PSI and KS swing widely when data is scarce.
  • PSI above 0.10 is a WARN and above 0.20 is an ALERT. KS above the critical value is only a WARN.
  • The reject rate is compared with the reference window as a ratio, not as a direct difference, because 2% going to 3% is already an increase of one half.
  • The precision of rejected items is the proportion that the inspector confirms as truly defective. It is computed only when there are at least min_confirmed confirmed samples. 3 defective out of 3 does not mean perfect precision.

The real run: eleven weeks, two events

output.txt
ข้อมูลที่ถูกทิ้ง: {'confidence นอกช่วง 0-1': 1, 'could not convert string to float': 1, 'invalid literal for int() with base 10': 1, 'ไม่ใช่ตัวเลขจำกัด': 1}
ช่วงอ้างอิง: สัปดาห์ (1, 2, 3, 4) รวม 1600 ภาพ

wk    n  psi_conf psi_bright psi_area  reject  prec  สถานะ
 1  400    0.013      0.020    0.021    6.8%     -  ok
 2  400    0.030      0.019    0.018    5.0%     -  ok
 3  400    0.053      0.014    0.024    5.2%     -  ok
 4  400    0.011      0.016    0.021    4.2%     -  ok
 5   40  ตัวอย่างน้อยเกินไป (40 < 100) ไม่ตัดสิน
 6  400    0.464      1.741    0.038    4.5%     -  ALERT
      - ALERT: PSI confidence = 0.46
      - WARN: KS confidence = 0.282 > 0.091
      - ALERT: PSI brightness = 1.74
      - WARN: KS brightness = 0.520 > 0.091
 7  400    0.440      1.641    0.035    4.5%     -  ALERT
      - ALERT: PSI confidence = 0.44
      - WARN: KS confidence = 0.256 > 0.091
      - ALERT: PSI brightness = 1.64
      - WARN: KS brightness = 0.518 > 0.091
 8  400    0.023      0.043    0.020    6.0%  100%  ok
 9  400    0.407      0.029    0.013   15.5%   22%  ALERT
      - ALERT: PSI confidence = 0.41
      - WARN: KS confidence = 0.264 > 0.091
      - ALERT: อัตราคัดออก 15.5% (อ้างอิง 5.3%)
      - ALERT: ผู้ตรวจยืนยันว่าเสียจริงเพียง 22% ของที่คัดออก (n=23)
10  400    0.521      0.037    0.036   17.8%   45%  ALERT
      - ALERT: PSI confidence = 0.52
      - WARN: KS confidence = 0.296 > 0.091
      - ALERT: อัตราคัดออก 17.8% (อ้างอิง 5.3%)
      - ALERT: ผู้ตรวจยืนยันว่าเสียจริงเพียง 45% ของที่คัดออก (n=22)
11  400    0.430      0.024    0.019   12.5%   30%  ALERT
      - ALERT: PSI confidence = 0.43
      - WARN: KS confidence = 0.277 > 0.091
      - ALERT: อัตราคัดออก 12.5% (อ้างอิง 5.3%)
      - ALERT: ผู้ตรวจยืนยันว่าเสียจริงเพียง 30% ของที่คัดออก (n=23)
Output from an actual run on 2026-11-21 with python3 monitor.py (numpy 2.3.5)

Reading the result point by point

  1. The first line says 4 corrupted rows were dropped: confidence above 1, a blank brightness, a week that is not a number, and a nan value, one of each. The remaining 4,040 rows go into the calculation.
  2. Weeks 1 to 4 are the reference window. Every PSI is below 0.06, and compared against themselves they stay under 0.10. This is the normal noise level of this example data and can be used to set thresholds.
  3. Week 5 has 40 images and is skipped, with the reason given. Without a minimum sample threshold here, we would get numbers that look real from far too little data.
  4. In weeks 6 to 7 the brightness shifts. The brightness PSI is 1.74 and 1.64, and the model's confidence changes along with it, but the reject rate stays at 4.5%, no different from normal. If you looked only at the reject rate, you would not see this at all. The precision column shows a dash because there are fewer than 10 samples confirmed by the inspector.
  5. In week 8, after the lighting is fixed, every value returns to low and the status is ok. This is evidence that the cause was the lighting and not the model, since the model was never touched.
  6. In weeks 9 to 11 the new product variant arrives. Brightness does not change (brightness PSI below 0.04) but the confidence PSI jumps to between 0.41 and 0.52. The reject rate jumps from 5.3% to between 12.5% and 17.8%, and the inspector confirms that only 22% to 45% of the rejected items are truly defective, so most of what is rejected is good parts. This pattern points to training data that does not cover the new variant, not to lighting.

The observation comes from the pattern of the numbers, not from the names of the weeks. If brightness changes and confidence changes, suspect the lighting or the camera. If brightness is steady but confidence and the reject rate change, suspect the product or the raw material. If every number is steady but inspectors say the answers are wrong more often, review the criteria for concept drift.

The test suite

test_drift.py has 10 cases. Running python3 -m unittest test_drift gives OK for all 10. It tests that PSI is low when the distributions are the same, high when they are shifted, and that values outside the reference range do not produce infinity. It tests KS on values with known answers (identical gives 0, fully separated gives 1, and a hand-computed example gives 0.5), a critical value that matches the formula, a reader that must drop exactly 4 corrupted rows and leave 4,040, a low-image week that must be skipped, a normal week that must have no ALERT, a brightness shift that must ALERT even though the reject rate is constant, and precision that must not be judged when the confirmed samples are below the threshold.

test_drift.py · lines 58–69
    def test_brightness_shift_alerts_even_if_reject_rate_is_flat(self):
        m, alerts = evaluate(rows(400, mu=10), rows(1000))
        self.assertTrue(any("brightness" in msg and lv == "ALERT" for lv, msg in alerts))
        self.assertAlmostEqual(m["reject_rate"], 0.05, places=2)

    def test_low_precision_needs_enough_confirmed_samples(self):
        week = rows(400, rejected=0.1, confirmed=0)
        _, alerts = evaluate(week, rows(1000))
        self.assertTrue(any("ยืนยัน" in msg for _, msg in alerts))
        few = [r if i % 10 == 0 or r[3] == 0 else r[:4] + (None,) for i, r in enumerate(week)]
        m, _ = evaluate(few, rows(1000))
        self.assertNotIn("precision", m)  # ยืนยันน้อยกว่า min_confirmed ไม่ตัดสิน
test_drift.py: tests that a lighting shift must alert even when the reject rate is constant, and that precision must wait for enough samples

Why thresholds must be tuned per line

The numbers 0.10 and 0.20 are general rules, not rules for your line. There are three reasons.

  • Each line has a different level of normal noise. A line where the room lighting changes with the shift will naturally have a high brightness PSI. With a fixed 0.20 it alerts every day, and people stop reading the alerts.
  • Different variables have different sensitivity. The PSI of confidence squeezed close to 1 has many empty bins, so its value jumps more easily than brightness, which spreads in a bell shape.
  • The cost of the two kinds of error is not equal. Pharmaceutical lines, safety parts or high-priced products would rather over-alert than let a defect escape. A line where re-sorting is cheap may accept fewer alerts.

A practical way to set them: collect at least several weeks of data from a period that QC has confirmed as normal, compute each week's PSI against the other weeks in that period, look at the highest value that occurs on its own, and set WARN slightly above it. Then back-test against past events where you know the lighting or product changed, to see whether the thresholds catch them. After going live, review them every time there is a false alarm.

When there is an alert: the order to follow

This order is a practice summarized by the author and is not taken directly from any documentation. The principle is to check what is cheap and easy to reverse first, and touch the model last.

  1. Check the lighting and camera first. Compare the latest images with a reference image, photograph a color card or reference object at the same position, and check the lamp, dust on the lens, the camera position and the shutter setting. A lighting shift is fixed in hardware and needs no model training (the article on choosing lighting explains more).
  2. See which variable changed, using the pattern above. A change in brightness points to the lighting. Steady brightness with changing confidence points to the product itself.
  3. Ask production what changed in that period: the raw material lot, the product variant, the supplier, the mold. Record it in the event log beside the numbers.
  4. Sample images from the alerted week and have an inspector relabel them, focusing on rejected parts and parts with low confidence, following the labeling guidance in the article on defect datasets. Then compute the false reject and false accept rates (see the article on false accepts and false rejects).
  5. If the new labels confirm that the model really got it wrong, then collect images for additional training. Set a gate before retraining: the new model must pass a separate hold-out test set that was never used in training, containing both old-condition and new-condition images, and it must not be worse than the old model on the old-condition set.
  6. Release in a way that can be reversed. Keep the old model, run the new model in shadow mode so that its results come out at the same time without making real decisions, compare it with the inspector for a while, and then switch over.

A change in the numbers does not prove that the model has degraded. A real change in raw material also changes the numbers while the model is still right. This is why step 4, with a person confirming, cannot be skipped.

In real use: databases, large files and continuous running

  • Store only the per-image summary values (confidence, brightness, area, decision, time, line id, product variant id, model version) in a database table. You do not need to keep every image. Keep images only for random samples and rejected parts, along with the time the inspector confirmed them.
  • For CSV files of several hundred megabytes, read one week at a time with a query over a time range instead of loading everything into memory. This example loads the whole file because it is small (the simplified: warning in the code).
  • Compute the bin edges from the reference window once and save them in a versioned file, so that numbers can be compared across weeks. When you change the reference window (for example after training a new model), record when it changed.
  • Keep separate references per product variant and per line, because two variants that naturally differ will make PSI high if you pool them.
  • Run the job on a schedule (cron or a scheduler) and send results to where people already look, such as a dashboard page or a chat group, with links to sample images. An alert without images forces people to hunt for them.
  • A bad image or a camera that dropped off should alert as a different type, not as drift. A reader that drops corrupted rows above a set proportion should warn that the data pipeline has a problem.
  • Log every change (changing a lamp, moving a camera, changing the model, changing the thresholds) with a timestamp, so that you can trace afterwards why the numbers changed.

Hypothetical examples: adapting it to three businesses

Plastic injection molding factory

Useful variables are the mean brightness and the mean color of the part, because the color of plastic pellets can differ between lots. Keep separate reference windows by color or variant, and link the pellet lot records to the weekly numbers.

Packaging and label factory

New variants arrive often, following seasons and promotions. Have production notify you before a variant change, so that you can collect and label images of the new variant in advance and train before it goes on the line, instead of waiting for an alert to tell you.

Electronics assembly line

Conveyor speed or glare from shiny solder can change the image. Track image sharpness (for example the variance of the Laplacian) as a fourth variable, to catch a lens that is starting to blur or a camera that is vibrating. Adding a variable is done by adding its name to FEATURES and a column to the CSV.

Common mistakes and a checklist

  • Looking only at the reject rate, which is slow and does not move when the lighting shifts in both directions that happen to cancel out.
  • Retraining the model the moment an alert fires, when the cause is an aging lamp.
  • Recomputing the bin edges from that week's own data, which makes PSI impossible to compare across weeks.
  • Using thresholds from an article or a tool's documentation without back-testing them against your own line's data.
  • Judging from a week with only a few dozen images.
  • Having no samples confirmed by a person, so you cannot know whether a rising reject rate is real defects or model mistakes.
  • A reference window with abnormal events mixed in, which makes normal things look abnormal.
  • Releasing a new model with no way to roll back and no separate test set.
  1. Record the confidence, brightness, area, decision, model version, product variant and time of every image.
  2. Choose a reference window that QC has confirmed as normal, and save the bin edges as a version.
  3. Set the WARN and ALERT thresholds from the line's normal variation, then back-test against real past events.
  4. Set a minimum number of samples per week, and a minimum number of confirmed samples before using the precision figure.
  5. Have someone confirm a random sample of rejected and passed items every week.
  6. Have a step that checks lighting and camera before concluding the problem is in the model.
  7. A pre-retraining gate: a separate test set, an approver, and a way to roll back.

Caveats of the example: the data is made-up data created so that the events are easy to see. In real life the signals are mixed and not this clean. There is no per-bin analysis, no split by product variant, no test of how accurate the thresholds are, and no coverage of concept drift except through confirmed samples. There is also no connection to cameras or a dashboard. Use it as a learning example, not as code ready for real use.

References

  1. Ultralytics docs: Maintaining your computer vision models after deployment (data drift, KS and PSI, retraining) (accessed 2026-11-21)
  2. SciPy docs: scipy.stats.ks_2samp (two-sample Kolmogorov-Smirnov test) (accessed 2026-11-21)
  3. Wikipedia: Kolmogorov-Smirnov test (two-sample statistic and critical value) (accessed 2026-11-21)
  4. Evidently AI: data drift detection on large datasets (PSI thresholds, KS sensitivity) (accessed 2026-11-21)
  5. Evidently AI: concept drift and data drift definitions (accessed 2026-11-21)
  6. Evidently docs: data drift detection methods and default thresholds (accessed 2026-11-21)
  7. Google Cloud docs: Introduction to Vertex AI Model Monitoring (baseline, drift, thresholds) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer