Source

Module 12 · System design: from operational need to a working AI system

Time: about 6 hours with readings · Lab: python course/labs/lab12_system.py

You need: Module 1 (the system around the model), Module 4 §1 and §6 (regression and gradient-boosted trees, for predictive analytics), Module 9 (data quality, leakage, distribution shift) and Module 10 (MAE and baselines).

By the end you can:

  • turn an operational requirement into a precise data requirement and a measurable question;
  • draw a current and a proposed process map, and say where an AI component changes the work;
  • explain TrayCheck's architecture: the offline and online paths, module boundaries, and model versioning;
  • explain why each record is a data trail, and which fields must never be overwritten;
  • design a dashboard for two audiences, and say what good AI reporting must show;
  • spot opportunities for predictive analytics in food service and say how to test one against a baseline;
  • name the main ways an ML system fails in production (training/serving skew, drift) and how they are monitored.

Why this matters for the internship

The position description asks you to "help translate operational requirements into meaningful data and technology use cases", "develop simple process maps", "prepare simple dashboards, visualisations and project updates" and "identify opportunities where machine learning could improve prediction, automation or operational decision-making". It also asks you to "work with ISS and technology partners to understand how machine learning models are being applied within the solution". That means knowing how such a system is put together well enough to ask the vendor good questions. This module covers both halves, using TrayCheck as the worked example.


1. From operational requirement to data requirement

Stakeholders state needs in operational language: "we want to reduce plate waste". A system can only act on something measurable. The translation goes through four steps:

Step Question Example: plate waste
Need What does the business want to improve? Reduce plate waste on the wards
Question What precisely do we need to know to act? Which dishes, wards and meal periods have the highest share of food returned uneaten, and is it changing?
Data requirement What must be recorded, how, and how accurately? Per tray: date, meal period, ward, dish (confirmed by a person if the model is unsure), served grams and returned grams from a scale, with the source of each value
Measure What number answers the question, and what would count as a change? Returned ÷ served grams, per dish and per ward, weekly, with the number of trays behind each figure

Do the same for each item in the PoC scope:

PoC scope item Precise question Data required Hardest part
AI-enabled food identification Does the system name the dish correctly, per dish? Photo, model's answer and score, person-confirmed dish Getting reliable ground truth during a busy service
Food and portion recognition Is the estimated amount close enough to the weighed amount for its intended use? Model's estimate and a weighed reference for a sample of trays Weighing enough trays (Module 10 §6)
Food waste identification and analysis Where and when is food wasted, and why? Served and returned amounts per tray, with ward, dish and time Missing weights that aren't random (Module 9 §1)
Nutritional and consumption data Did the patient eat enough of what they needed? Amount eaten per item, linked to the menu's nutrition data Linking to patient records raises privacy questions (Module 13)
Compliance and audit Was each tray plated as specified? Photo at plating, the intended menu item and portion Defining "compliant" precisely enough to check
Predictive analytics Can we forecast meals needed, or waste, better than current practice? History of meals ordered, served and returned, by day and ward Beating a simple baseline (§6)

The last column is where most PoCs struggle, and it is usually a data problem, not a model problem.


2. Process maps: current and proposed

A process map shows who does what, in what order. For an AI PoC, draw two: the current process and the proposed one with the AI component in place. The difference between them is what staff will experience, and what training, UAT (Module 11) and evaluation must cover.

A simple swimlane layout gives each role its own row:

CURRENT (illustrative)
 Kitchen        plate meal ──► send tray
 Ward staff                       deliver ──► collect tray
 Kitchen hand                                         scrape plate ──► (estimate waste by eye, sometimes) ──► wash

PROPOSED, with TrayCheck
 Kitchen        plate meal ──► send tray
 Ward staff                       deliver ──► collect tray
 Kitchen hand                                         photo ──► weigh ──► confirm dish if flagged ──► scrape ──► wash
 TrayCheck                                             score photo ─► flag? ─► save record
 Food service manager                                                                  weekly dashboard ──► menu and portion decisions

Questions the comparison forces you to answer:

  • Who does more work, and when? Photographing and weighing add seconds per tray at the busiest point of the shift. Is that realistic?
  • What decisions change? If nothing on the right-hand side changes, the PoC produces reports no one acts on.
  • What happens when the AI is unavailable or wrong? The proposed map needs a fallback path.

Draw the current map with the people who do the work, on site. Written procedures and real practice often differ, and the real practice is what the AI has to fit into.


3. TrayCheck's architecture

                        OFFLINE (run occasionally, outputs committed to git)
 vision_prepare.py ──► photos + manifest.csv ──► vision_train.py ──► food_classifier.keras + metrics.json
                                                        │
                                       vision_score.py ─┴─► scores_val.csv, scores_test.csv, review_policy.json
                                                                                     │
 ────────────────────────────────────────────────────────────────────────────────────┼────────────
                        ONLINE (the app, every photo)                                 ▼
  browser ──► app.py ──► food_model.py ──► review_rules.py ──► (person decides) ──► records.py ──► SQLite
     ▲          │          score photo       flag or not, why                         save / load
     └──────────┴────────── dashboard: metrics.json + scores_test.csv + records ◄──────────────────┘

Offline vs online. Expensive, occasional work (training, scoring 240 photos, choosing the threshold) runs offline and produces fixed files, artefacts, that are saved with the code: the model file, score tables and the review policy. The online app only reads them. Most real systems are split the same way, and it explains a common vendor answer: "the model is updated quarterly". Between updates, the model doesn't learn from new data, whatever the marketing says.

Module boundaries follow one principle: separate things that change for different reasons.

Module Responsibility Depends on
food_model.py Load the model, score one photo, compute the model version TensorFlow
review_rules.py Business rules: flag reasons, threshold table, Wilson interval Nothing heavy: pure logic
records.py Storage: schema, save, load, data checks SQLite, pandas
app.py User interface and dashboard All of the above
vision_score.py Offline batch scoring and threshold choice food_model, review_rules
simulate_service.py Labelled simulated operations data review_rules, records

Because the review rules depend on neither the model nor the interface, they can be tested in milliseconds and changed by someone who knows nothing about TensorFlow.

Model versioning. model_version() returns mobilenetv2-4dish- plus the first 8 characters of the model file's SHA-256 fingerprint, and every saved record stores it. If the model is retrained, old and new records stay distinguishable, so you can compare correction rates before and after. In a PoC, ask the vendor: does every output record carry the model version that produced it? If not, a mid-pilot model update makes before-and-after comparisons impossible.


4. A record is a data trail

Lab 12 prints one record's full trail:

  predicted_dish   bread_pudding        ← the model's answer, never overwritten
  predicted_score  0.5543
  review_reasons   low_score,not_on_menu  ← why a person was asked
  checked          1                    ← derived: flagged, or the person changed the answer
  final_dish       baby_back_ribs       ← what the person decided
  corrected        1                    ← derived: final_dish != predicted_dish
  served_g         324.0
  returned_g       44.0
  quantity_source  simulated            ← where the grams came from
  model_version    mobilenetv2-4dish-2e9f5ef4

Design decisions worth defending, and worth checking for in a vendor's system:

  • Keep the original prediction. Overwriting it with the correction destroys the evidence needed to measure the model. Original and final values sit side by side.
  • Derive, don't type. checked and corrected are computed from other fields when the record is made, so they can never contradict them.
  • Record provenance. record_source (app or simulated) and quantity_source (measured or simulated) let every report say where its numbers came from.
  • Let the database enforce rules. CHECK (record_source IN ('app', 'simulated')) makes the database itself reject invalid values.
  • Empty means unknown. A missing value stays missing (NULL). Never fill in a value you didn't record.

Why SQLite? It is a full SQL database in a single file, with no server to run, which suits one laptop. Lab 12 measures about 96,000 inserts per second; a kitchen saves a few hundred records a day. With several kitchens writing at once, user accounts or central reporting, a server database such as PostgreSQL would replace it, and records.py's save/load interface would stay the same.


5. Dashboards and reporting

TrayCheck's dashboard has two tabs for two audiences:

Tab Audience Shows
Model performance (test photos) Evaluators, vendor, project team Confusion matrix; results by dish; review workload vs mistakes that slip through (the threshold table); examples the model got right; confident mistakes
Operations (saved records) Food service managers, dietitians Why photos were flagged; what people corrected; confident mistakes caught by people; hidden mistakes estimated from spot checks; not-on-menu alerts; missing or inconsistent data; trends by day; food waste

Principles that make AI reporting trustworthy:

  1. Separate model quality from operational results. "How good is the model?" and "what is happening in the kitchen?" are different questions with different audiences.
  2. Show uncertainty. A range ("3.6%, plausibly 1% to 12%") instead of a bare number. Show how many trays each figure rests on.
  3. Show what was excluded. TrayCheck lists records with missing or impossible weights rather than averaging them silently.
  4. Label simulated or test data unmistakably. TrayCheck shows a banner and a filter whenever simulated records are included.
  5. Lead with the decision. Put the figure a manager acts on first (waste by dish and meal period), and the technical detail behind it.
  6. Show examples, not just numbers. The confident-mistakes table with photos convinces stakeholders faster than any metric, and shows them what "wrong" looks like.

6. Predictive analytics: opportunities and how to test them

Predictive analytics means using historical records to forecast something useful. Food service has several natural targets:

Target Type Data needed Who acts on it
Meals needed per ward and meal period tomorrow Regression (a count) Past orders and occupancy by day Production planning
Plate waste per dish next week Regression (a share) Past served and returned weights by dish, menu cycle Menu and portion planning
Whether a patient's tray will come back mostly uneaten Classification Past consumption, diet type, time of day (privacy review needed) Dietitians, for early follow-up
Unusual days Anomaly detection Daily totals Managers, to investigate causes

The key test: beat a simple baseline. A forecast is only useful if it beats what people can already do with almost no effort. The standard baselines are a seasonal naive forecast ("same as the same day last week") or an average by weekday. The repo's older analyze.py does exactly this on synthetic demand data. It holds out the most recent 20 days and compares two forecasts of meals prepared, scored by mean absolute error (MAE: the average size of a miss, Module 10 §6). The model is gradient-boosted trees: many small decision trees, each fitted to the errors left by the ones before it (Module 4 §6).

weekday-history baseline (average for that kitchen, meal and weekday)   MAE 5.3 meals
gradient boosting model                                                 MAE 4.2 meals

The model's typical error is about one meal smaller than the baseline's. Whether that is worth building and maintaining a model is an operational question: what does one meal of error cost, and how often does it matter? Note the split: training on earlier dates and testing on later ones, because a forecast is always used on the future (Module 9's temporal leakage).

Data is synthetic: these numbers show the method, not real kitchen performance.


7. How ML systems fail in production, and how to watch for it

Two failures are specific to ML and worth asking any vendor about:

  • Training/serving skew: the live system prepares inputs differently from how training did (another resize method, missing normalisation, different camera settings), and accuracy silently drops. TrayCheck guards against it three ways: the same resize in both paths; the preprocessing saved inside the model file; and vision_score.py checking that its scores match the training run's saved predictions.
  • Drift: the world changes after deployment: new dishes, new crockery, new lighting (Module 9 §6). Nothing in the code breaks; the model just gets worse.

Neither shows up as an error message, so they have to be monitored:

Signal What a change suggests
Share of trays flagged Inputs have changed (drift) or the threshold no longer fits
Correction rate among reviewed trays The model is wrong more often
Spot-check error estimate Hidden errors among unreviewed trays are rising
Not-on-menu alerts Menu changes, or the model confusing new dishes
Missing-weight count The workflow isn't being followed

TrayCheck shows all five on its operations tab. A rise in any of them after a menu change is the system telling you the model is out of its depth.

Testing. TrayCheck has tests at several levels: the rules (tests/test_review_workflow.py), the saved scores and splits (tests/test_evaluation.py), and the real app driven without a browser (tests/test_app.py). A useful checklist when asking a vendor how their system is tested is to group ML tests into four kinds: data tests (are inputs valid and as expected?), model tests (does it meet its targets, including per slice?), infrastructure tests (does the pipeline run the same way every time?) and monitoring (would we notice if it got worse in use?).


8. If it were real: a production sketch

 tablets at the tray line ──HTTPS──► API service ──► model server ──► review rules
          ▲  (login, offline queue)       │                               │
          │                               ▼                               ▼
     review screen  ◄────────────── server database (records, audit log) ◄── corrections
                                          │
              ┌───────────────────────────┼───────────────────────────┐
              ▼                           ▼                           ▼
     BI dashboard for staff      monitoring: flag rate, corrections,   retraining: new labelled photos →
     (waste, workload)           spot checks, alerts after changes     train → evaluate on held-out wards
                                                                       → approve → staged rollout

What changes from the demo: logins and roles; a server database with backups and an audit log; photos kept only if approved, with retention rules; monitoring with alerts; and retraining with an evaluation gate before any new model goes live. Sculley et al.'s Hidden Technical Debt in Machine Learning Systems (2015) is the classic warning that everything around the model grows complex.


Check your understanding

1. A stakeholder says "we want the AI to improve nutrition". Turn that into a data requirement.

Make it a question first: for example, "which patients on texture-modified diets eat less than half of their main meal, and at which meal periods?" Then the data: per tray, patient diet type, items served and amounts eaten (weighed or estimated against a validated scale), meal period and date, linked to the menu's nutrition data, with privacy approval for any patient link. Then the measure: share of trays below 50% eaten, by diet type and meal period, weekly, with counts.

2. Why draw the current process with the people who do the work, rather than from the written procedure?

Real practice often differs from the documented procedure, and the AI has to fit real practice. Drawing it on site also surfaces constraints (time pressure, where trays physically go) and builds trust with the staff who will use the system.

3. Why keep predicted_dish when final_dish holds the corrected answer?

Without the original prediction you can't measure how often the model is wrong, which dishes it confuses, or whether a new model is better. Corrections are evidence; overwriting destroys it.

4. A forecasting model has MAE 4.2 meals; "same as last week" has MAE 5.3. Should the PoC recommend it?

Not on accuracy alone. Ask what a meal of error costs, whether the improvement holds across wards and seasons (test on later periods), and what it costs to run and maintain. A simple baseline that staff understand may be the better recommendation if the gain is small.

5. What is training/serving skew, and why won't it show up as an error message?

When inputs are prepared differently in use than in training, the model still produces confident outputs; they are just wrong more often. Only comparing live outputs with ground truth (spot checks, correction rates) or checking preprocessing consistency reveals it.

6. Three kitchens will each run a tablet and want one shared dashboard. What would you change first?

Replace the local SQLite file with a server database behind an API, add logins, and serve the model from one place, so all kitchens write to and read from one source of truth. The rules and record design can stay largely as they are.


Go deeper

Short on time? The study guide says which of these to read first.

Core (free)

Optional

  • Stanford CS329S, Machine Learning Systems Design (Chip Huyen), lecture notes on data engineering, deployment and monitoring. Free at stanford-cs329s.github.io.
  • Huyen, Designing Machine Learning Systems (2022), Chapters 1–2 (ML systems and their design), Chapter 7 (deployment) and Chapter 8 (distribution shifts and monitoring). Paid.
  • Breck et al. (2017), The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction, IEEE Big Data: the four test categories, as a vendor checklist.
  • Hyndman & Athanasopoulos, Forecasting: Principles and Practice, 3rd ed., §5.2 Some simple forecasting methods (naive and seasonal naive baselines) and §5.8 Evaluating point forecast accuracy. Free at otexts.com/fpp3.
  • SQLite, Appropriate Uses For SQLite (sqlite.org/whentouse.html).
  • Streamlit documentation, Main concepts and App testing, if you want to understand how the demo app works (docs.streamlit.io).

Interview angle

"I'd start from the operational need and turn it into a measurable question and a data requirement. For plate waste that means per-tray served and returned weights with ward, dish and time, and the source of every number. Then I'd map the current process with the staff who do it and the proposed one, so we know exactly what changes for whom.

On the technical side, TrayCheck separates offline training from the online app, stamps every record with the model version, and never overwrites the model's original answer, so the model can be measured over time. Its dashboard separates model quality from operations, shows ranges and excluded records, and labels simulated data. For predictive analytics, the first test is always whether a model beats a simple baseline like 'same as last week' by enough to matter."