An AI/ML-powered system for gram-precise net carbohydrate estimation and glycemic load prediction from meal photos, designed to support safer insulin dosing decisions for Type 1 diabetics.
- Problem Statement
- Key Features
- Performance Metrics
- Dataset
- Model Architecture
- Installation
- Quick Start
- Usage Guide
- Project Structure
- Clinical Context
- Safety & Disclaimers
- Future Enhancements
- Contributing
- License
Type 1 diabetes requires precise insulin dosing based on carbohydrate intake. The standard rule is:
- 1 unit of insulin per 10-15g of carbohydrates
However, manual carbohydrate counting has significant limitations:
- ยฑ20-30% error rate in typical manual counting
- Each 5g error can cause 25-50 mg/dL blood glucose fluctuations
- Poor estimation increases risks of:
- Hypoglycemia (low blood sugar)
- Hyperglycemia (high blood sugar)
- Long-term diabetic complications
This system uses computer vision and deep learning to:
- Identify Indian dishes from meal photos
- Estimate net carbohydrates with ยฑ10g accuracy (v1 target)
- Calculate glycemic load for better blood sugar management
- Provide insulin dosing recommendations as a decision support tool
-
Dish Classification: Identifies 6 Indian dishes with 89% accuracy
- Biryani, Dal, Halwa, Poha, Rasgulla, Roti
-
Carbohydrate Estimation: Predicts net carbs with 82% accuracy within ยฑ10g
- Mean Absolute Error: 5.92g
- Median Error: 3.05g
-
Glycemic Load Calculation:
- Computes GL from GI and net carbs
- Classifies as Low/Medium/High GL
- Provides blood sugar impact warnings
-
Insulin Recommendations:
- Customizable insulin-to-carb ratios (default: 1 unit per 12g)
- Individual ratio support (10-15g per unit)
-
Clinical Context:
- Blood glucose impact estimates
- Safety warnings and disclaimers
- Comparison to manual counting accuracy
- Enhanced Data Augmentation: Rotation, shear, zoom, brightness adjustments
- Robust Training: Early stopping, learning rate scheduling, model checkpointing
- Comprehensive Evaluation: MAE, RMSE, Rยฒ, error distribution, per-class analysis
- Production-Ready: Modular code structure, error handling, validation
- Accuracy: 89.0%
- Top-K Accuracy: 98.5%
- Per-Class Performance:
- Biryani: 90% precision, 90% recall
- Dal: 91% precision, 100% recall
- Halwa: 100% precision, 100% recall
- Poha: 89% precision, 80% recall
- Rasgulla: 100% precision, 100% recall
- Roti: 100% precision, 90% recall
- Mean Absolute Error (MAE): 5.92g โ (Target: <10g)
- Root Mean Squared Error (RMSE): 8.97g
- Rยฒ Score: 0.77
- Mean Absolute Percentage Error (MAPE): 18.61%
- Within ยฑ5g: 58.5%
- Within ยฑ10g: 82.0% โ (Target: >80%)
- Within ยฑ15g: 89.5%
- Min Error: 0.03g
- Max Error: 29.03g
- Median Error: 3.05g
- 75th Percentile: 8.00g
- 95th Percentile: 22.52g
| Dish | True Carbs | Predicted | Error | MAE |
|---|---|---|---|---|
| Biryani | 45.0g | 39.9g | 7.4g | 7.4g |
| Dal | 12.0g | 13.3g | 2.7g | 2.7g |
| Halwa | 60.0g | 52.4g | 10.6g | 10.6g |
| Poha | 28.0g | 30.1g | 4.0g | 4.0g |
| Rasgulla | 35.0g | 38.4g | 7.5g | 7.5g |
| Roti | 18.0g | 19.2g | 3.5g | 3.5g |
- Target Accuracy: ยฑ10g for safe insulin dosing โ ACHIEVED
- Blood Glucose Impact: Average error (5.9g) โ 30-59 mg/dL change
- Comparison: Manual counting typically has ยฑ20-30% errors
- Status: Model meets v1 target accuracy threshold
- Total Images: 1,000 images
- Classes: 6 Indian dishes
- Split: 80% training (800 images), 20% validation (200 images)
- Source: Custom dataset + Indian Food Images dataset
| Dish | Images | Status |
|---|---|---|
| Biryani | 150 | |
| Dal | 250 | โ Good |
| Halwa | 250 | โ Good |
| Poha | 150 | |
| Rasgulla | 50 | |
| Roti | 150 |
Each dish has associated nutrition information:
| Dish | Net Carbs (g) | Glycemic Index |
|---|---|---|
| Biryani | 45 | 70 |
| Dal | 12 | 30 |
| Halwa | 60 | 75 |
| Poha | 28 | 65 |
| Rasgulla | 35 | 65 |
| Roti | 18 | 55 |
- Diversity: Various lighting, angles, backgrounds, portion sizes
- Validation: All images validated for readability and quality
- Augmentation: Enhanced augmentation during training
Input (224ร224ร3)
โ
MobileNetV2 (ImageNet pretrained, frozen)
โ
Global Average Pooling (GAP)
โ
Batch Normalization
โ
Dense(256) + ReLU + Dropout(0.5)
โ
Dense(128) + ReLU + Dropout(0.3)
โ
Dense(6) + Softmax
โ
Output: Dish Classification
Training Details:
- Optimizer: Adam (lr=0.001)
- Loss: Categorical Crossentropy
- Callbacks: Early Stopping, ReduceLROnPlateau, ModelCheckpoint
- Epochs: 30 (with early stopping)
- Data Augmentation: Rotation, shear, zoom, brightness, horizontal flip
Input (224ร224ร3)
โ
Frozen Classifier Feature Extractor (GAP layer)
โ
Batch Normalization
โ
Dense(256) + ReLU + Dropout(0.4)
โ
Dense(128) + ReLU + Dropout(0.3)
โ
Dense(64) + ReLU + Dropout(0.2)
โ
Dense(1) + Linear
โ
Output: Net Carbohydrates (grams)
Training Details:
- Optimizer: Adam (lr=0.001)
- Loss: Huber Loss (robust to outliers)
- Metrics: MAE, MSE
- Callbacks: Early Stopping, ReduceLROnPlateau, ModelCheckpoint
- Epochs: 50 (with early stopping)
- Transfer Learning: MobileNetV2 pretrained on ImageNet for feature extraction
- Frozen Base: Prevents overfitting on small dataset
- Huber Loss: More robust to outliers than MSE
- Progressive Dropout: Higher dropout in deeper layers
- Feature Reuse: Regressor uses classifier features for efficiency
- Python 3.9 or higher
- pip package manager
- 4GB+ RAM (8GB recommended)
- GPU optional but recommended for faster training
git clone https://github.com/yourusername/Carbs-ai.git
cd Carbs-aipip install -r requirements.txtRequired Packages:
tensorflow==2.15.0
pandas==2.2.2
numpy==1.26.4
Pillow==10.4.0
scikit-learn==1.5.1
python -c "import tensorflow as tf; print(f'TensorFlow {tf.__version__}')"
python -c "import pandas as pd; print(f'Pandas {pd.__version__}')"Train Classifier (takes ~5-10 minutes):
python src/train_classifier.pyTrain Regressor (takes ~5-10 minutes):
python src/train_regressor.pypython src/predict.py data/images/biryani/0d81432b55.jpgOutput Example:
======================================================================
TYPE 1 DIABETES CARB ESTIMATION - PREDICTION RESULTS
======================================================================
๐ฝ๏ธ Identified Dish: BIRYANI
Confidence: 99.0%
๐ Net Carbohydrates: 30.9g
๐ Glycemic Index (GI): 70
๐ Glycemic Load (GL): 21.7
High GL โ Rapid blood sugar rise โ ๏ธ
๐ Insulin Recommendation:
Suggested dose: 2.6 units
(Based on 1 unit per 12g carbs)
python src/evaluate.pypython src/predict.py <image_path>python src/predict.py <image_path> --insulin-ratio 10(Default is 12g per unit; adjust for individual needs)
# Biryani
python src/predict.py data/images/biryani/0d81432b55.jpg
# Dal
python src/predict.py data/images/dal/006aeeea8d.jpg
# Rasgulla
python src/predict.py data/images/rasgulla/<image_name>.jpgpython src/train_classifier.pyWhat it does:
- Loads images from
data/images/ - Applies data augmentation
- Trains MobileNetV2-based classifier
- Saves model to
models/classifier.h5 - Shows validation accuracy
python src/train_regressor.pyWhat it does:
- Loads trained classifier
- Extracts features from GAP layer
- Trains regression head for carb prediction
- Saves model to
models/regressor.h5 - Shows comprehensive evaluation metrics
python src/evaluate.pyProvides:
- Classification accuracy and confusion matrix
- Regression metrics (MAE, RMSE, Rยฒ, MAPE)
- Accuracy within thresholds (ยฑ5g, ยฑ10g, ยฑ15g)
- Error distribution statistics
- Per-class performance analysis
- Clinical significance assessment
See DATASET_GUIDE.md for detailed instructions on:
- Finding compatible datasets
- Downloading from Kaggle
- Organizing new images
- Validating dataset quality
Quick expansion:
# Organize images from downloaded dataset
python scripts/expand_dataset.py <source_folder> --target data/images
# Check current dataset status
python scripts/expand_dataset.py data/images --count-onlyCarbs-ai/
โโโ data/
โ โโโ images/ # Training images organized by dish
โ โ โโโ biryani/
โ โ โโโ dal/
โ โ โโโ halwa/
โ โ โโโ poha/
โ โ โโโ rasgulla/
โ โ โโโ roti/
โ โโโ nutrition.csv # Net carbs and GI data
โ โโโ raw/ # Raw downloaded datasets
โ
โโโ models/ # Trained model files
โ โโโ classifier.h5
โ โโโ classifier_best.h5
โ โโโ regressor.h5
โ โโโ regressor_best.h5
โ
โโโ src/
โ โโโ train_classifier.py # Classifier training script
โ โโโ train_regressor.py # Regressor training script
โ โโโ predict.py # Prediction script
โ โโโ evaluate.py # Model evaluation script
โ โโโ utils/
โ โโโ __init__.py
โ โโโ diabetic_check.py # Utility functions
โ
โโโ scripts/
โ โโโ expand_dataset.py # Dataset expansion utility
โ
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
โโโ DATASET_GUIDE.md # Dataset expansion guide
Insulin Dosing Rule:
- 1 unit of insulin per 10-15g carbohydrates (individual varies)
Impact of Errors:
- 5g error โ 25-50 mg/dL blood glucose change
- 10g error โ 50-100 mg/dL blood glucose change
- 15g error โ 75-150 mg/dL blood glucose change
Current System Performance:
- Average error: 5.9g (30-59 mg/dL impact)
- 82% of predictions within ยฑ10g
- Better than manual counting (ยฑ20-30% errors)
- Low GL (โค10): Gradual blood sugar rise โ Safe
- Medium GL (11-19): Moderate blood sugar rise
โ ๏ธ Caution - High GL (โฅ20): Rapid blood sugar rise
โ ๏ธ High caution
Formula: GL = (GI ร Net Carbs) / 100
- Use as Decision Support: Always verify with healthcare provider
- Individual Ratios: Adjust insulin ratio based on personal needs
- Monitor Blood Sugar: Track actual vs. predicted impact
- Continuous Learning: System improves with more data
- This system is a research/decision support tool only
- NOT FDA approved for medical use
- NOT a substitute for professional medical advice
- Always consult with healthcare providers for insulin dosing
- Individual insulin ratios vary (10-15g per unit)
- Blood sugar responses vary by person
- Limited Dataset: Trained on 6 dishes, 1000 images
- Portion Size: Assumes standard serving sizes
- Variability: Different preparations may vary in carbs
- Accuracy: 82% within ยฑ10g (not 100% accurate)
- Clinical Validation: Not clinically validated
- โ Use as a starting point for carb estimation
- โ Verify predictions with nutrition labels when available
- โ Monitor blood sugar after meals
- โ Adjust based on personal experience
- โ Don't rely solely on predictions
- โ Don't use without healthcare provider consultation
- Expand dataset to 200+ images per dish
- Add more Indian dishes (10+ total)
- Portion size estimation
- Multi-dish meal support
- Real-time mobile app
- Clinical validation study
- User feedback loop for continuous improvement
- Personalization based on user history
- Integration with CGM (Continuous Glucose Monitor)
- Meal planning recommendations
- Multi-cuisine support (beyond Indian food)
- Real-time video analysis
- Community dataset contributions
- FDA approval pathway exploration
- Integration with insulin pumps
We welcome contributions! Areas where help is needed:
- Dataset Expansion: More images, more dishes
- Model Improvements: Better architectures, hyperparameter tuning
- Code Quality: Bug fixes, documentation, testing
- Clinical Validation: Real-world testing and feedback
- Feature Development: New features from roadmap
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow PEP 8 style guide
- Add docstrings to new functions
- Include tests for new features
- Update documentation as needed
This project is licensed under the MIT License - see the LICENSE file for details.
- Dataset: Indian Food Images dataset from Kaggle
- Framework: TensorFlow/Keras for deep learning
- Architecture: MobileNetV2 for efficient feature extraction
- Community: Open source ML community for tools and inspiration
- Issues: Report bugs or request features via GitHub Issues
- Discussions: Join discussions in GitHub Discussions
- DATASET_GUIDE.md - Comprehensive guide for dataset expansion
- Type 1 Diabetes Foundation - Resources for Type 1 diabetes
- Carb Counting Guide - Manual carb counting resources
Made with โค๏ธ for the Type 1 diabetes community
Remember: This tool is for decision support only. Always consult with healthcare providers for medical decisions. Contributor fix test