Dralkh commited on
Commit
6bf5da2
·
verified ·
1 Parent(s): 6ca5e0a

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +134 -0
README.md ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: pytorch
4
+ base_model: google/siglip2-base-patch16-224
5
+ tags:
6
+ - nutrition-estimation
7
+ - calorie-estimation
8
+ - food
9
+ - nutrition5k
10
+ - image-regression
11
+ datasets:
12
+ - Nutrition5k
13
+ language:
14
+ - en
15
+ metrics:
16
+ - mae
17
+ ---
18
+
19
+ # kcalorie — food-photo calorie & macro estimation
20
+
21
+ A single RGB food photo in, five numbers out: **calories (kcal), mass (g), protein (g), carbohydrate (g), fat (g)**.
22
+ kcalorie is a SigLIP2-base vision tower with a small regression head, fine-tuned end-to-end and evaluated
23
+ under a strict, leakage-audited Nutrition5k protocol.
24
+
25
+ ![Comparison on the locked Nutrition5k test set](comparison.png)
26
+
27
+ ## Headline result — locked Nutrition5k test set (608 dishes, official test split, never seen)
28
+
29
+ | Metric | kcalorie | CalorieCLIP (same 608 dishes) |
30
+ |---|---|---|
31
+ | Calorie MAE | **51.4 kcal** (95% CI 35.8–78.9) | 181.2 kcal |
32
+ | Median absolute error | **25.9 kcal** | 137.0 kcal |
33
+ | Within ±50 kcal | **76.8%** | 21.4% |
34
+ | Within ±100 kcal | **92.4%** | 40.6% |
35
+ | Bias | **−0.7 kcal** | +134.8 kcal |
36
+ | Calibrated 90% interval | **±105.9 kcal** (actual coverage 93.6%) | — |
37
+ | Invalid predictions | 0 / 608 | 0 / 608 |
38
+
39
+ Every test image is a deterministic central frame from the official Nutrition5k camera-A side-angle
40
+ video of an official *test-split* dish — selected by dish ID, never by image quality. Evaluation is
41
+ dish-level (`physical_meal_id`).
42
+
43
+ ## Comparison with open VLMs (paired 304-dish subset, seed 17)
44
+
45
+ Each model answered the same calorie question on the same dishes
46
+ (prompt: *"Estimate the total calories in this food image. Return exactly one integer number in kcal…"*).
47
+
48
+ | Model | n | MAE (kcal) | Median AE | Within ±100 kcal | Bias |
49
+ |---|---|---|---|---|---|
50
+ | **kcalorie (ours)** | 304 | **64.4** | **23.5** | **92.4%** | −13.6 |
51
+ | Qwen3.5-2B | 304 | 116.4 | 65.0 | 69.4% | −48.1 |
52
+ | MiniCPM-V 4.6 (1.3B) | 304 | 163.3 | 97.0 | 52.6% | +75.5 |
53
+ | Gemma-4-12B † | 100 | 176.8 | 90.5 | 58.0% | −43.3 |
54
+ | CalorieCLIP | 304 | 196.2 | 133.2 | 42.1% | +121.1 |
55
+
56
+ † Gemma-4-12B was scored on a seeded 100-dish paired subset of the same 304 dishes (compute budget);
57
+ all parse rates were 100%.
58
+
59
+ ## Training method
60
+
61
+ - **Architecture**: `google/siglip2-base-patch16-224` vision tower (92M params) → LayerNorm →
62
+ MLP head (768→768→256→5) with softplus outputs. Trained with Huber loss, per-task, quality-weighted.
63
+ - **Schedule**: 15 epochs × 20,000 samples, batch 256 (bf16), head LR 1e-4 / trunk LR 2e-5,
64
+ cosine schedule with 5% warmup, first 5% head-only, last 4 vision blocks unfrozen, weight decay 0.05, seed 17.
65
+ - **Checkpoint selection**: best validation MAE on 80 held-out camera-A dishes (validation MAE 39.2 kcal).
66
+ Training ran ~34 minutes on one RTX PRO 6000 Blackwell (CUDA 13).
67
+ - **Calibration**: a conformal radius fitted on 86 held-out calibration dishes gives 90% prediction
68
+ intervals of ±105.9 kcal, with 93.6% actual coverage on the locked test set (`calibration.json`).
69
+
70
+ ![Training loss](loss_curve.png)
71
+
72
+ ## Training data (20,000 samples, leakage-audited)
73
+
74
+ | Source | Samples | Notes |
75
+ |---|---|---|
76
+ | [`pinkieseb/nutrition_dataset`](https://huggingface.co/datasets/pinkieseb/nutrition_dataset) (Nutrition5k video frames) | 19,734 | only dishes provably in the **official Nutrition5k train split** (matched by exact nutrition signature), ≤16 frames per dish |
77
+ | [`aryachakraborty/Food_Calorie_Dataset`](https://huggingface.co/datasets/aryachakraborty/Food_Calorie_Dataset) | 266 | human-estimated labels, down-weighted (0.4) |
78
+
79
+ Leakage controls, all enforced programmatically before training:
80
+ - **Group separation**: splits partition by physical dish (`physical_meal_id`); no dish appears in two splits.
81
+ - **Exact-media**: SHA-256 disjointness across fit / validation / calibration / test.
82
+ - **Near-duplicate**: perceptual-hash disjointness; 2 fit images visually colliding with held-out frames were dropped and backfilled.
83
+ - **Official-split proof**: a Nutrition5k registry maps nutrition signatures to official train/test IDs;
84
+ ambiguous signatures are excluded. The audit trail (SHA-256 of every manifest and the source tree) ships in the results.
85
+
86
+ ## Usage
87
+
88
+ ```python
89
+ import torch, torch.nn as nn, torch.nn.functional as F
90
+ from transformers import AutoImageProcessor, SiglipVisionModel
91
+ from huggingface_hub import hf_hub_download
92
+ from PIL import Image
93
+
94
+ class NutritionHead(nn.Module):
95
+ def __init__(self, input_dim: int = 768):
96
+ super().__init__()
97
+ self.net = nn.Sequential(
98
+ nn.LayerNorm(input_dim), nn.Linear(input_dim, 768), nn.GELU(), nn.Dropout(.15),
99
+ nn.Linear(768, 256), nn.GELU(), nn.Dropout(.10), nn.Linear(256, 5))
100
+ def forward(self, x): return F.softplus(self.net(x))
101
+
102
+ MODEL_ID = "google/siglip2-base-patch16-224"
103
+ processor = AutoImageProcessor.from_pretrained(MODEL_ID)
104
+ vision = SiglipVisionModel.from_pretrained(MODEL_ID)
105
+ head = NutritionHead()
106
+ state = torch.load(hf_hub_download("Dralkh/kcalorie", "kcalorie.pt"), map_location="cpu", weights_only=False)
107
+ vision.load_state_dict(state["vision_state"]); head.load_state_dict(state["head_state"])
108
+ vision.eval(); head.eval()
109
+
110
+ image = Image.open("meal.jpg").convert("RGB")
111
+ pixels = processor(images=image, return_tensors="pt").pixel_values
112
+ with torch.inference_mode():
113
+ out = vision(pixel_values=pixels)
114
+ feats = out.pooler_output if out.pooler_output is not None else out.last_hidden_state[:, 0]
115
+ kcal, mass_g, protein_g, carb_g, fat_g = head(feats.float())[0].tolist()
116
+ print(f"{kcal:.0f} kcal ± 106 (90% interval), {mass_g:.0f} g, P{protein_g:.0f}/C{carb_g:.0f}/F{fat_g:.0f}")
117
+ ```
118
+
119
+ ## Limitations
120
+
121
+ - **Domain**: trained and evaluated on Nutrition5k-style plated single dishes photographed from the side;
122
+ accuracy on multi-plate scenes, packaged food, or drinks is untested.
123
+ - **Heavy tail**: RMSE (327) is far above MAE (51) — very high-calorie dishes are occasionally missed badly.
124
+ Use the calibrated interval, not the point estimate, for anything that matters.
125
+ - **Frames, not meals**: training frames come from videos of ~1,250 distinct dishes; visual diversity is
126
+ narrower than the sample count suggests.
127
+ - The VLM baselines answered a zero-shot prompt; instruction-tuned prompting or few-shot could improve them.
128
+
129
+ ## Provenance
130
+
131
+ Full pipeline (data prep, leakage audit, training, evaluation, benchmark) and all raw results with
132
+ SHA-256 checksums: [`Dralkh/ccalorie-siglip2-b0-strict`](https://huggingface.co/datasets/Dralkh/ccalorie-siglip2-b0-strict).
133
+ Trained 2026-07-12 for ≈ $1.20 of GPU time. Base checkpoint: CalorieCLIP comparison uses
134
+ [`jc-builds/CalorieCLIP`](https://huggingface.co/jc-builds/CalorieCLIP) (OpenAI CLIP ViT-B/32 + MLP regressor).