Car Crash Fix Amount Predictor

How the neural networks are built, how data is parsed, trained, and turned into a repair-cost estimate. Every diagram is drawn live on <canvas> and reflects the code on this branch.

ResNet-50YOLOv8 Mask R-CNN (car gate)XGBoostPyTorch · torchvision
build: checkpoint-16 · gate + identifier + Variant A/B · runs on v0.2.0 weights

01 End-to-end code flow

One photo flows through four models. A car-presence gate runs first; then a make/model identifier and a damage model run; their signals feed an XGBoost cost regressor that is calibrated to a swappable parts-price catalog and converted to the chosen currency. The dots below animate the data actually moving between stages.

CNN / detector classifier head gradient-boosted trees non-ML stage
About this build (checkpoint-16): Mask R-CNN appears only as the car-presence gate (COCO weights, inference only — it answers "is there a car, and where?"). Damage itself is recognised by the ResNet-50 multi-label classifier (Variant A) and the YOLOv8 detector (Variant B). A dedicated Mask R-CNN damage segmenter exists on a separate branch and is not part of this deployable build.

02 How the data is parsed

Two datasets, two parsers, one canonical pipeline. Stanford Cars trains the identifier; CarDD (COCO format) trains the damage models. Every image is decoded, cropped, augmented, tensorised and normalised to ImageNet statistics before it touches a network.

Real samples from the data

Left: Stanford Cars (make/model/year). Right: CarDD (damage types). Thumbnails embedded from the local datasets.

Stanford Cars sample
Audi Tts · 2012
Stanford Cars sample
Acura Tl · 2012
Stanford Cars sample
Dodge Dakota Club · 2007
CarDD sample
CarDD · scratch, tire_flat
CarDD sample
CarDD · crack, tire_flat
CarDD sample
CarDD · dent, scratch

Datasets at a glance

DatasetRole in ccdpSizeClassesAnnotationLicense
Stanford Cars
Krause et al. 2013
Make/model/year identifier16,185 imgs 196 (make·model·year)bbox + class (.mat devkit)research / academic
CarDD
Wang et al. 2023
Damage classifier (A) + detector (B)~4,000 imgs 6 damage typesCOCO-format bbox + masksacademic (verify)

These two are the only datasets trained on. CarDD's 6 damage types: dent · scratch · crack · glass_shatter · lamp_broken · tire_flat. (CarDD ships its labels in COCO format — that's the file format, not the COCO dataset.) Full attributions in the Citations section.

Pretrained weights — not a training set: the car gate uses torchvision's COCO-pretrained Mask R-CNN (weights only), run at inference to find car/truck/bus. Nothing in this project downloads or trains on the COCO dataset.

Stanford Cars → identifier

Class names and per-image boxes live in MATLAB .mat devkit files, read with scipy.io.loadmat. Each car is cropped to its annotation box, then transformed. A deterministic stratified 90/10 split makes train/val.

CarDD → damage models

COCO JSON (instances_*2017.json) is parsed into canonical Records. Variant A uses the whole image with a multi-label target; Variant B uses normalised YOLO boxes derived from the COCO bboxes.

The transform pipeline (training)

Resize/RandomResizedCrop → RandAugment(2,9) → MixUp/CutMix → ToTensor → Normalize(μ,σ)

03 Network architecture

The identifier and the Variant A damage classifier share the same skeleton: an ImageNet ResNet-50 backbone (conv1 → layer1…layer4 → avgpool) with the final fully-connected layer replaced by a small custom head. The two-stage fine-tune controls which blocks receive gradients.

Custom head — identifier (196 classes)

Dropout(0.2) → Linear(2048 → 512) → ReLU → Dropout(0.3) → Linear(512 → 196) → Softmax

The 2048-d vector after avgpool is also reused as a frozen feature extractor for the XGBoost cost regressors.

Custom head — damage classifier A (6 types)

Dropout(0.3) → Linear(2048 → 512) → ReLU → Dropout(0.4) → Linear(512 → 6) → Sigmoid

Multi-label: each damage type fires independently, so the output is a sigmoid per class, not a softmax.

Variant B — YOLOv8 detector

A single-stage detector: a CSP-Darknet backbone + PAN neck + a decoupled head predicts boxes, objectness and the 6 damage classes in one pass. Trained on CarDD via Ultralytics.

The car gate — COCO Mask R-CNN (ResNet-50-FPN)

Same ResNet-50 family, wrapped in a Feature Pyramid Network + Region Proposal Network. Used only at inference to find car/truck/bus — masks are ignored, the box is used to crop.

04 Activation functions

Four non-linearities appear across the models. Hover a plot to read its value.

ReLU hidden layers (ResNet + heads)

f(x) = max(0, x)

Sigmoid Variant A multi-label output

σ(x) = 1 / (1 + e−x)

Softmax identifier output (196-way)

softmax(x)i = exi / Σj exj

SiLU YOLOv8 detector (internal)

silu(x) = x · σ(x)

05 How the model is trained

The CNNs use a two-stage transfer-learning recipe; YOLOv8 trains end-to-end via Ultralytics. Below: the freeze schedule, optimisers, and the augmentation that fights overfitting on small datasets.

Optimisers

Identifier / classifier (A)

AdamW, lr 1e-3 → 1e-4, wd 1e-4, ReduceLROnPlateau

Detector (B)

Ultralytics SGD/AdamW auto, cosine LR, mosaic aug

Regularisation

Dropout (0.2–0.4), weight decay, label smoothing 0.1, gradient clipping (‖g‖ ≤ 5.0), early stopping on val metric.

Augmentation

RandAugment(2 ops, mag 9), MixUp(α=0.2) & CutMix(α=1.0) per-batch with probability 0.8 — targets become soft labels.

MixUp / CutMix — what the network actually sees

Two images and their labels are blended (MixUp) or one is pasted into the other (CutMix); the loss is computed against the mixed soft target — which is why training uses a soft cross-entropy.

06 Backpropagation logic

PyTorch autograd records the forward graph; loss.backward() walks it in reverse, multiplying local gradients via the chain rule. Frozen blocks (Stage 1) get no gradient; gradients are clipped and applied by the optimiser.

The chain rule, per layer

∂L/∂Wk = ∂L/∂aout · (∂ai+1/∂ai) · ∂ak/∂Wk

Stage 1 freezes layer1…layer4 (requires_grad=False) so the product stops at the head. Stage 2 unfreezes layer3+layer4 and gradients flow deeper.

Stabilisers in the loop

StepCall
Zero gradsoptimizer.zero_grad()
Backwardloss.backward()
Clipclip_grad_norm_(…, 5.0)
Stepoptimizer.step()
Schedulescheduler.step(val_loss)

07 Loss / error functions

Each task minimises a different objective. The plots show how loss grows as the prediction drifts from the truth.

Identifier — Cross-Entropy (+ label smoothing)

L = − Σc yc · log( softmax(x)c )

Damage classifier A — Binary Cross-Entropy

L = − Σc [ yc log σ(xc) + (1−yc) log(1−σ(xc)) ]

Detector B — YOLOv8 multi-part loss

L = λbox·LCIoU + λcls·LBCE-cls + λdfl·LDFL

Box regression uses Complete-IoU, classification uses BCE per class, and distribution focal loss sharpens box edges. Ultralytics sums them per image.

XGBoost cost — squared error

L = Σi ( ŷi − yi )²  ·  objective = reg:squarederror

The target is a synthetic, catalog-derived repair cost; the booster fits residuals stage by stage with early stopping on validation RMSE.

08 How accuracy is measured

Different heads need different metrics. These are the production numbers reported in the repo.

ModelMetricWhy this metricValue
Make/model identifierTop-1 accuracysingle correct class out of 19677.0%
Damage classifier (A)Macro-F1multi-label, class-imbalanced0.834
Damage detector (B)mAP@50 / @50-95localisation quality0.687 / 0.540
Cost regressor XGBoost(A)R² · MAPEregression fit & % error0.642 · 32.9%
Cost regressor XGBoost(B)R² · MAPE+ bbox features0.736 · 24.4%
Macro-F1 = mean over classes of F1 = 2·P·R/(P+R). mAP = area under precision–recall averaged over IoU thresholds. R² = 1 − SSres/SStot. MAPE = mean(|ŷ−y| / |y|).

09 The final output & how the image is shown

The Gradio app returns an annotated image plus structured text. The original photo is redrawn with a green car-box (from the gate) and coloured damage boxes (Variant B); a JSON blob carries full provenance. The boxes below draw in sequence to mirror how the result is assembled.

Annotated image (animated)

car box (gate) dent scratch glass

Returned payload

{ "car_check": { "label": "car", "score": 0.99 }, "identified": { "make": "audi", "model": "tts", "year": 2012, "confidence": 0.51 }, "variant_b": { "damage_types": ["dent","scratch"], "parts": ["front_bumper","hood"], "detections": [ {"damage_type":"dent","confidence":0.88}, … ] }, "cost_usd": 1284.0, "cost": 107312.0, "currency": "INR", "tier": "exact", "provenance": "xgb_b(exact); calibrated to …" }

If the identifier's confidence is below the 0.30 floor, make becomes null and the cost falls back to body-type/segment pricing instead of a wrong label.

10 Citations & credits

This project is built entirely on others' datasets and tools. Full credit to the sources below; the project's CITATIONS.md carries the complete list and license notes.

Datasets

Stanford Cars — Krause, J., Stark, M., Deng, J., & Fei-Fei, L. (2013). 3D Object Representations for Fine-Grained Categorization. 4th IEEE Workshop on 3D Representation and Recognition (3dRR-13), Sydney, Australia. stanford.edu/cars · mirror: Kaggle. License: research/academic use.
CarDD: A New Dataset for Vision-Based Car Damage Detection — Wang, X., Li, W., & Pan, Z. (2023). IEEE Transactions on Intelligent Transportation Systems, 24(7), 7202–7214. doi:10.1109/TITS.2023.3258480 · mirror: Kaggle. License: academic research.
COCO (gate weights) — Lin, T.-Y., et al. (2014). Microsoft COCO: Common Objects in Context. ECCV. cocodataset.org. Images CC BY 4.0.

Models & frameworks

Mask R-CNN — He, K., Gkioxari, G., Dollár, P., & Girshick, R. (2017). Mask R-CNN. ICCV. (Car-presence gate, via torchvision COCO weights.)
Deep Residual Learning (ResNet) — He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR. (Identifier + Variant A backbone.)
YOLOv8 / Ultralytics — Jocher, G., Chaurasia, A., & Qiu, J. (2023). Ultralytics YOLOv8. github.com/ultralytics. (Variant B detector.)
XGBoost — Chen, T., & Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting System. KDD. (Cost regressors A/B.)
PyTorch / torchvision — Paszke, A., et al. (2019). PyTorch: An Imperative Style, High-Performance Deep Learning Library. NeurIPS.