FreshGuard
Calibrating the lens · 0%
FreshGuard
Try the demo
Marco Ortiz TogashiIntro
00:00
IE University · Deep Learning Final Project

FreshGuard

A camera that reads freshness and turns it into a price.

Point a phone at loose produce. A two-stage computer-vision pipeline grades it in real time, a forecaster predicts next week's spoilage, and every verdict becomes a markdown and a reorder signal. One FastAPI service, running on hardware stores already own.

ANN · CNN · RNN · all three, on purpose
FRAME 0001 · reading…
spectral lab · lab/spectral
Scroll to read
02 The problem Sebastião

An apple with no expiry date.

Supermarkets lose 4–6% of produce revenue to shrink every year. Most of it is not spoilage you could never prevent. It is margin that walked out the back door because the markdown decision arrived a day too late.

An apple graded "sell soon" on Tuesday is marked down and sold. The same apple found Wednesday, past the window, is a total loss. The fruit barely changed. The clock did. And the hardest data point in the store is this: loose produce carries no printed expiry date. No barcode, no lot number. The only signal of how close it is to the end of its life is how it looks.

4–6%
of produce revenue lost to shrink, yearly
Spain's Law 1/2025 now legally requires retailers to discount or donate produce nearing end of life, not bin it. A margin nice-to-have became a compliance obligation.
The catch. The law applies to all produce, but loose produce is exactly the category with no date to drive compliance. Visual condition is the only available signal, and that is precisely what a CNN reads.
NO_SKU · no barcode NO_EXPIRY · no date code window 1 day
03 Teaching it to see Sebastião

27,700 images, one locked preprocessing contract, and a finding we did not expect.

23,537 examples of fresh and rotten.

FreshGuard learns from the Kaggle "Fruit & Vegetable Disease" dataset: ~27,700 images across 20 balanced classes, ten produce types each split fresh and rotten. We hold out 15% for an honest test, leaving 23,537 train / 4,140 test. The interesting part is not the size. It is two decisions about how to feed it.

Negative finding. We expected aggressive augmentation to help. It backfired: the from-scratch CNN collapsed to ~29%. Rot is a fine-grained signal of colour and texture, and violent augmentation erases exactly the cue the model needs. We kept augmentation moderate and pushed robustness to inference instead.
The preprocessing contract. Every image is locked through the same mobilenet_v2.preprocess_input ([-1, 1]) at train and serve. Train/serve skew is the classic invisible ML bug, a model that looks great offline and quietly rots in production. We designed it out from day one.
23,537 train · 4,140 test 20 classes · 85/15 aggressive aug → ~29%

10 produce × {fresh, rotten}. Apple · banana · orange · carrot · tomato · potato · cucumber · bell pepper · mango · strawberry.

class distributionbalance
augmentationaugment
preprocessingpreprocess
04 Three brains, one verdict Yaxin

Three architectures, one controlled experiment, a 3× accuracy jump on 5.5× fewer parameters.

We didn't pick the model. We ran the bake-off.

The same data and task went to three architectures of rising structural cleverness. The result is one of the cleanest stories in applied deep learning, and it runs against our own intuition about size.

The ANN flattens each image into a vector before its first layer, and that single act is fatal: a bruise three rows up becomes two unrelated numbers in a list of thousands. Convolution fixes the geometry, sliding shared filters so the model sees local patches everywhere. Transfer learning wins outright by importing a MobileNetV2 backbone pretrained on ImageNet's 1.4M images, then learning only the last mile.

The model with the most parameters lost by the widest margin. Capacity was never the bottleneck. The right inductive bias was.
ANN 31.9% · 14.3M CNN 75.0% · 8.5M MobileNetV2 95.8% · 2.6M
live · scroll

Accuracy races to value; the param chip morphs down (14.3M → 2.6M). More accurate and smaller.

05 Nudge, don't wreck Yaxin

Freeze first to set the head, then unfreeze the top with a 100× smaller learning rate.

Borrow the features, then nudge them.

A fresh classification head fires large, noisy gradients in its first steps. Leave the powerful backbone trainable at that moment and those gradients tear apart the ImageNet features you imported. So we fine-tune in two deliberate phases.

Transfer learning + fine-tuning This is the standard recipe, to the letter: freeze the ImageNet backbone, attach a GlobalAveragePooling → Dense → Dropout → Dense(softmax) head, then unfreeze the layers past a cutoff and fine-tune. We swapped ResNet50 for the lighter MobileNetV2 and dropped the fine-tune LR 100×.
Functional API Built un-nested on purpose. The model is Model(base.input, out), using the Functional API, not a nested Sequential, so the last conv layer out_relu stays addressable. That single choice is what makes Grad-CAM possible two chapters from now.

The callbacks: EarlyStopping (patience 3, restore best) · ModelCheckpoint (best val_acc) · ReduceLROnPlateau (×0.3, min 1e-6) · TensorBoard. Validation stayed below training throughout, with no overfitting.

🔒
Phase 1 · train the headBackbone frozen · GAP → Dropout → Dense256 → Dense20 · 5 epochs
LR 1e-3
🔓
Phase 2 · fine-tune the topUnfreeze top 30 layers · early layers stay frozen · 4 epochs
LR 1e-5
MobileNetV2 training curvesval ≤ train · no overfit
06 The decision that matters Bassem

Near-perfect on the in-store call, and candid about the one class it finds hard.

0.996 on fresh versus rotten.

A single accuracy number hides sins, so we evaluated on the dimension a store actually cares about. On the binary fresh-vs-rotten decision, the model scores a ROC-AUC of 0.996. That value, this close to 1.0, means the rotten signal and the fresh signal almost never overlap. It is the decision behind every price action in the store.

The 20×20 confusion matrix tells the reassuring half: it is diagonal-dominant, and the errors that remain are intra-produce-type (sell-soon apple vs fresh apple), not across the fresh/rotten boundary. The model rarely makes the expensive mistake of calling rotten produce fresh.

Named out loud. The weakest class is rotten bell pepper at recall 0.73: peppers wrinkle rather than discolour, so "rotten" is visually subtler. We feature it, not hide it. Fresh mango and fresh strawberry reach recall 1.0.
AUC 0.996 weakest 0.73 bellpepper errors stay intra-type
Then a transformer. A Vision Transformer (DeiT-tiny) fine-tuned on the same photos reaches 98.4% against MobileNetV2's 95.8%, and lifts rotten bell pepper from 0.72 to 0.97 recall. Self-attention lets a wrinkle and a soft spot far apart on the pepper inform each other from the first layer. The price: 3.6x the compute and 1.6x the CPU time per photo, so the CNN stays the default on phones.
Evaluation toolkit Measured with the confusion_matrix, classification_report and ROC-AUC tooling.
hover cells

20×20 confusion. Lime diagonal = correct; coral = error, clustered inside the cyan produce-family boxes.

draws on scroll

ROC traces to AUC 0.996 against the random-chance diagonal.

07 Show your work Bassem

A heatmap that lands on the actual bruise, not the background, at zero extra cost.

A model that points at what it saw.

A model that is right for the wrong reasons is a liability under a food-waste law. Grad-CAM answers "where did it look?" by turning the network's own gradients into a heatmap. Bright regions are the pixels that pushed the verdict. When that brightness lands on a brown patch, staff trust the call and an auditor sees the evidence.

1 · backprop class score → last conv out_relu 2 · pooled_grads = mean(grads over H,W) 3 · heatmap = ReLU(Σ feature_maps × pooled_grads) 4 · normalise [0,1] → overlay on fruit
Essentially free. It reuses activations and gradients from a normal forward/backward pass, so it adds ~0 inference cost. That is what makes the auditability Law 1/2025 implies cheap enough to run on every flagged item.
Grad-CAM gallerybright = drove the verdict

The heatmap is computed from the last convolutional layer the un-nested model exposed in chapter 05. Explainability is not a second model auditing the first; it is the same model, made to point.

08 From softmax to shelf-edge Bassem

Probabilities become a price, with a built-in "I don't know."

It is allowed to abstain.

We collapse 20 numbers into the one that matters: rotten_prob, the probability mass summed over all rotten classes. A sell-soon band of (0.40, 0.65) sorts the item, which flows straight to a markdown. And below 0.70 confidence the model does not guess: it abstains to a review tier and hands the item to a human.

Abstention is a feature. Low-confidence crops route to a review queue, a human relabels them, and they fold into the next training run. The model improves on its own weak spots: safety today, a self-improving loop over time.

Also reported: top-3 classes and a normalised entropy (0 certain → 1 uniform) as an out-of-distribution alarm.

drag me
freshsellreject
rotten_prob = 0.22 · conf 0.91
FRESH
full price

Push toward 0.65 for reject, or drop confidence under 0.70 (drag near the band edges) to trigger the human-review gate.

09 Five tricks, zero retraining Yaxin

Each defense fixes a specific way a real store breaks a clean model.

Robustness lives at inference, not in the weights.

A

White balance

Gray-world neutralises warm aisle lighting so a fresh apple stops drifting toward "orange." Clip 0.7–1.5: correct the cast, don't invent one.

B

Test-time aug

Classify the crop and its mirror, average the softmaxes. One odd viewpoint can't sway the verdict.

C

Saliency crop

Lock onto the most colour-saturated blob so it grades the strawberry, not the grey table beneath it.

D

Majority vote

15-frame softmax history per ByteTrack ID (SMOOTH_WINDOW=15). A glare or motion-blur frame can't flip the call.

E

HSV severity

Classic CV, not the net: dark v<70 or brown h<30,s>60,v<140 → rot_area_fraction → the markdown depth. Auditable by design.

Severity > 0.25 is the −40% trigger. The HSV decay map ties straight back to the decision logic: a transparent, classic-CV number, not a neural guess, sets how deep the markdown goes.
10 Many items, counted once Yaxin

Detection and tracking so each item is graded once and voted over time.

Find it, follow it, then decide.

Finding produce and grading produce are different jobs. YOLOv8n (pretrained on COCO) detects; ByteTrack assigns each physical item a stable ID across frames, so the system accumulates evidence over time and counts each apple exactly once instead of re-grading it thirty times a second.

Honest gap, handled gracefully. COCO only knows 4 of our 10 types (banana, apple, orange, carrot). The other six fall back to a center-crop mode: no bounding box, but still graded and explained with Grad-CAM. Roadmap: fine-tune YOLO on the missing six.
COCO_FRUIT {46,47,49,51} conf 0.25 · bytetrack vote → count once
conveyor

Items drift under the aperture; a stable ID per item accumulates a 15-frame vote, then stamps one verdict and increments the count once.

11 Reading next week Jorge

A spoilage grade is a verdict on today. A forecast is a plan for next week.

28 days in, 7 days out.

The vision model answers "is this apple fresh now?" A manager needs more: how much will rot next week, so they can order the right amount and staff the markdown surge before it arrives. A compact LSTM(64) → Dense(7) reads the last 28 days of flagged-item counts and projects the next 7 in one shot.

Feature engineering is the whole game. Each day carries 7 features, six of them calendar. Day-of-week and day-of-year are encoded as sin/cos pairs so Sunday and Monday sit next to each other on a circle, not six apart on a line. The model reads the calendar instead of fighting it.

Leakage-free. Every calendar feature is known in advance, exactly like exogenous regressors in SARIMAX or Prophet. Feeding tomorrow's day-of-week into today's prediction is not cheating: the calendar for tomorrow is already on the wall.
RNN time-series The same standard RNN time-series recipe, extended: a MinMaxScaler fit on the training split only, fixed-length windows fed to an LSTM, predictions returned through inverse_transform. We made it multivariate with the 6 calendar features and forecast all 7 days in one shot.
cyclical

sin/cos encoding: the 7-day cycle is continuous, no fake jump from Sunday to Monday.

window 28 → horizon 7 7 features · 6 calendar holiday ±1d · promo ≥27
12 When the model lost Jorge

Version one lost to a one-line baseline. That was the most useful day of the project.

A failure, a diagnosis, a near-optimal fix.

The first LSTM took only the count series and lost to a trivial naive baseline by 6.8% MAE. A recurrent network beaten by one line of code that copies last week. The instinct is to hide that. The correct move is to interrogate it.

The naive baseline copies last week's matching weekday, so it cannot anticipate a calendar-keyed shock, a holiday surge or end-of-month markdown block. The count-only LSTM was blind to it too, because nobody told it what day it was. The fix was not a bigger network. It was the six calendar features: input (28,1) → (28,7).

scroll the comeback

Naive 6.26 → LSTM 3.59 MAE, with the irreducible noise floor at 3.19. The gap left is noise, not weakness.

MAE 3.59 vs 6.26 (+42.7%) RMSE +43.8% noise floor 3.19
13 The scanner trains the forecaster Jorge → Marco

A seven-number forecast is not a decision. The action plan is.

Forecast → reorder. Scan → better forecast.

Scan live count
→
append to history
→
LSTM re-forecast
→
action plan
→
order / markdown
↺

compute_action_plan turns the curve into one instruction. Week-over-week delta: down 5%+ → "order less, lighter week"; up 5%+ → "brace for markdowns, tighten ordering"; else "hold steady." The manager never sees a tensor.

The data flywheel. Today's live scan is appended to history before the forecast runs, so the LSTM predicts on data minutes old. The scanner literally trains the forecaster. More scans → better forecast → better ordering → reason to keep scanning. A competitor starting cold cannot match months of a store's own history.
illustrative
200
3,000
2%
recovered margin / year
at 0.60 × €0.55 blended unit
€0
Illustrative · not measured
14 Why it's a business, not a demo Marco

Land on compliance, expand on margin, defend with a data flywheel.

A live mandate, a data gap only AI can fill.

01 · WHY NOW

Compliance, not nice-to-have

Law 1/2025 makes acting on end-of-life produce mandatory, and the obligation lands on loose produce, the one category with no date to drive it. Food-waste regulation is moving EU-wide, repeating the same blind spot.

02 · THE WEDGE

Hardware you already own

A phone or webcam, no special sensor. The best model is 2.6M params. Explainable by construction (Grad-CAM), and self-improving via the review queue and forecast flywheel. Each is useful; together they're hard to copy.

03 · THE BUYER

Two stakeholders, one console

The sustainability officer owns the Law 1/2025 audit trail; the ops lead owns produce margin. FreshGuard is the compliance system and the margin-recovery system in the same deployment.

Unit economics, conservative by construction

We only credit value on sell-soon items marked down and sold, at 60% of retail. Fresh would have sold anyway (zero incremental); reject is already lost (zero). We exclude the two largest buckets on purpose, so the math only ever counts genuinely saveable margin. The point is the leverage: even crediting only the saveable band, the recovered margin comfortably clears a per-store SaaS price, and every rescued unit is also a logged compliance event.

recovery 0.60 ~€7.2k/store/yr illustrative ~€7.2M/yr · 1,000 stores

Market, illustratively sized

TAMlow €B / yr

Global grocery with loose produce. The recoverable-margin pool, of which FreshGuard captures a software slice.

SAMlow €100M / yr

Chains with loose-produce sections in compliance regions, where the buying trigger is live today.

SOM€single–low-double-digit M ARR

A 24–36 month beachhead: Spanish and early EU chains, compliance-exposed and ready to pilot CV.

All three layers illustrative, sized top-down to show the shape of the opportunity, not a measured number.

The moat. Classifiers commoditise; the moat is the compounding data flywheel (review-queue active learning + live forecast history, both keyed to each store's own conditions), explainability that functions as a regulatory barrier, and switching costs that cement once POS-integrated. A new entrant starts from generic accuracy. An incumbent deployment has months of this store's own edge cases baked in, and that gap widens every day it runs.
15 What we don't claim yet Marco

Maturity is credibility. The caveats are stated up front.

The honest lab board.

Domain shift

Clean Kaggle data vs a real store's lighting and cameras. Needs a small per-store calibration set, the review queue is built for it.

Throughput

One laptop CPU can't grade a fast belt. Batch frames or add an edge GPU / Jetson.

POS integration

Today it recommends a markdown; applying it at the shelf label needs POS work, the step that becomes the switching cost.

Projections

The € figures are illustrative, not measured. The pilot exists to replace them.

→ YOLO on the 6 missing types → per-store calibration → POS integration → edge deployment → real per-store history

The stack

request→ FastAPI→ YOLOv8n+ByteTrack→ MobileNetV2→ LSTM

Plus Grad-CAM explainability, classic-CV robustness, and a vanilla-JS 6-tab ops console: Live scan · Manager dashboard · Market prices · Review queue · Model evidence · Lab. No framework.

ROC curveevidence room

Architecture coverage

ANN · Functional API, callbacks, MinMaxScaler CNN · transfer learning & fine-tuning + Grad-CAM RNN · LSTM time-series forecasting Generative (autoencoders / GANs) · out of scope by design

FreshGuard exercises every predictive architecture in scope, and deliberately stays predictive: generative AI is excluded by the project brief.

16 The campaign Marco

A 10-second spot, generated in code with real produce. One line, shelf-edge to social.

Read the fruit, not the date.

4–6% of produce.
Binned. Every year.
the cost of catching decay a day too late
produce being scanned
No label? Read the fruit.
one camera · one verdict
strawberry
Fresh
tomato
Sell soon
cucumber
Reject
Graded in real time.
−40%
Sold, not binned.
Catch decay a day earlier.
Point. Read. Decide.

Auto-plays in view, built entirely in code with your dataset's produce photos (no video file). Screen-record it for a shareable spot, or drop a real clip into a <video> here.

"Read the fruit, not the date."hero line
"Every bin is a missed markdown."retail · B2B
"A day earlier. That's the whole product."social
"Waste less. Recover more. Comply by default."sustainability

Live · point the lens at the room

Point. Read. Decide.

The instrument finally reads the room. Every concept above, firing at once, in the real 6-tab ops console.

Live scanManagerMarketReviewModelLab
01 Live scan: a fresh fruit, then a rotten one. Call the tier and the Grad-CAM patch.
02 Conveyor: the 15-frame majority vote holds steady as frames jitter.
03 Manager: the 7-day LSTM forecast and today's recovered €.
04 Review queue: abstentions waiting to be relabelled, the flywheel, live.
Launch the ops console→ Try the browser demo→

Opens the live app at localhost:8000 (FastAPI backend). Make sure the server is running (uvicorn) so the camera + predictions work.