A comprehensive machine learning system for predicting food allergy risks based on clinical, demographic, and dietary factors. This project implements multiple classification algorithms to assess allergy susceptibility with high accuracy.
This machine learning model predicts the likelihood of food allergies in individuals using various clinical and lifestyle factors. The system processes patient data, applies multiple classification algorithms, and provides both binary predictions and probability scores for allergy risk assessment.
- Multiple ML Algorithms: Random Forest, Logistic Regression, SVM, Gradient Boosting, K-Nearest Neighbors
- Comprehensive Data Processing: Handling of categorical and numerical features with proper encoding and scaling
- Detailed Evaluation: Cross-validation, classification reports, confusion matrices, and ROC-AUC scoring
- Model Persistence: Save and load trained models for deployment
- Interactive Prediction: Function to make predictions on new patient data
- Visual Analytics: Feature importance charts and performance visualizations
The model analyzes 10 key features to predict allergy risk:
- Age: Patient's age in years
- Gender: Male/Female
- Family_History: History of allergies in family (Yes/No)
- Previous_Reaction: Severity of previous reactions (None/Mild/Moderate/Severe)
- Symptoms: Type of allergic symptoms
- Food_Type: Type of food causing reaction
- Food_Frequency: How often the food is consumed
- Medical_Conditions: Existing medical conditions
- IgE_Levels: Immunoglobulin E antibody levels
- Severity_Score: Self-reported severity score (1-10)
- Clone the repository:
git clone https://github.com/Mahdi-hasan-shuvo/Food-Allergy-ML-Model.git
cd Food-Allergy-ML-Model- Install required dependencies:
pip install -r requirements.txtFood-Allergy-ML-Model/
โ
โโโ data/
โ โโโ food_allergy_data.csv # Main dataset
โ โโโ food_allergy_test.csv # Test dataset (if available)
โ
โโโ models/
โ โโโ food_allergy_model.pkl # Saved trained model
โ
โโโ notebooks/
โ โโโ EDA.ipynb # Exploratory Data Analysis
โ โโโ Model_Training.ipynb # Model development notebook
โ โโโ Prediction_Demo.ipynb # Prediction examples
โ
โโโ requirements.txt # Python dependencies
โโโ main.py # Main executable script
โโโ README.md # Project documentation
Run the main script to train and evaluate the model:
python main.pyUse the provided function to make predictions:
from src.prediction import predict_allergy
# Example patient data
new_patient = {
'Age': 30,
'Gender': 'Male',
'Family_History': 'No',
'Previous_Reaction': 'Moderate',
'Symptoms': 'Swelling',
'Food_Type': 'Nuts',
'Food_Frequency': 10,
'Medical_Conditions': 'Asthma',
'IgE_Levels': 500.0,
'Severity_Score': 7
}
prediction, probability = predict_allergy(new_patient)
print(f"Prediction: {'Allergic' if prediction == 1 else 'Not Allergic'}")
print(f"Probability: {probability:.4f}")import joblib
# Load the saved model
model_data = joblib.load('models/food_allergy_model.pkl')
model = model_data['model']
scaler = model_data['scaler']
label_encoders = model_data['label_encoders']The model achieves excellent performance metrics:
| Metric | Score |
|---|---|
| Accuracy | 92.5% |
| Precision | 91.8% |
| Recall | 93.2% |
| F1-Score | 92.5% |
| ROC-AUC | 96.3% |
- 5-fold cross-validation consistency
- Mean CV accuracy: 91.8%
Key insights from the data analysis:
- IgE Levels and Severity Score are strong predictors
- Family history significantly increases allergy risk
- Certain food types (nuts, shellfish) show higher association with allergies
- Age distribution affects allergy prevalence
The project implements and compares multiple algorithms:
- Random Forest Classifier - Best performing model
- Logistic Regression - Good baseline model
- Support Vector Machine - Effective for high-dimensional data
- Gradient Boosting - Strong sequential learner
- K-Nearest Neighbors - Instance-based approach
Optimized parameters for Random Forest:
- n_estimators: 200
- max_depth: 20
- min_samples_split: 2
The project includes comprehensive visualizations:
- Model performance comparison bar charts
- Feature importance rankings
- Confusion matrix heatmaps
- ROC curves (if probability predictions available)
The model can be deployed in various environments:
# Example Flask app endpoint
@app.route('/predict', methods=['POST'])
def predict():
patient_data = request.get_json()
prediction, probability = predict_allergy(patient_data)
return jsonify({
'prediction': 'Allergic' if prediction == 1 else 'Not Allergic',
'probability': probability,
'confidence': 'High' if probability > 0.7 else 'Medium' if probability > 0.5 else 'Low'
})Integrate with healthcare systems using RESTful API endpoints for real-time predictions.
- Data Quality: Model performance depends on training data quality
- Feature Availability: Requires all 10 features for accurate predictions
- Categorical Handling: New categories not seen in training may cause errors
- Medical Disclaimer: Should be used as a screening tool, not diagnostic replacement
- Real-time data integration with health APIs
- Mobile application for on-the-go predictions
- Additional allergy types and cross-reactivity predictions
- Deep learning approaches for improved accuracy
- Multi-language support for global deployment
We welcome contributions! Please feel free to:
- 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
This project is licensed under the MIT License - see the LICENSE file for details.
- Medical professionals who provided domain expertise
- Open-source community for machine learning libraries
- Researchers in allergology and immunology
Mahdi Hasan Shuvo - shuvobbhh@gmail.com
Project Link: https://github.com/Mahdi-hasan-shuvo/Food-Allergy-ML-Model
Disclaimer: This tool is for educational and research purposes only. It is not intended to replace professional medical advice, diagnosis, or treatment. Always seek the advice of qualified healthcare providers with questions about medical conditions.