Machine Learning-based Water Potability Prediction System
Predicts whether a water sample is safe to drink using advanced classification models
π Open the Streamlit App β
To run locally: streamlit run app.py
| Name | GitHub | Responsibilities |
|---|---|---|
| Bainty Kaur | @BaintyKaur | Model Building, Evaluation, Deployment, Feature Engineering |
| Asna Abbas | @asnaabbas763-cyber | Data Collection, Preprocessing, EDA, Explainability |
Access to safe drinking water is a critical global health issue. Over 2 billion people consume contaminated water worldwide, leading to diseases like cholera, typhoid, and dysentery.
Traditional water quality testing is expensive, slow, and requires laboratory equipment. This project builds a machine learning-based binary classifier that predicts whether a water sample is potable (safe to drink) or non-potable based on physicochemical properties β enabling fast, scalable water safety assessment.
| Property | Detail |
|---|---|
| Name | Water Potability Dataset |
| Source | Kaggle β Aditya Kadiwal |
| Size | 3,276 samples Γ 10 features |
| Target | Potability β 1 (Safe), 0 (Not Safe) |
| Class Distribution | ~61% Non-Potable, ~39% Potable (imbalanced) |
| Train-Test Split | 80% training (with SMOTE applied), 20% test |
| Feature | Description | WHO Safe Limit |
|---|---|---|
ph |
pH of water | 6.5 β 8.5 |
Hardness |
Calcium/Magnesium content (mg/L) | < 300 |
Solids |
Total dissolved solids (ppm) | < 500 |
Chloramines |
Disinfectant concentration (ppm) | < 4 |
Sulfate |
Sulfate ions (mg/L) | < 250 |
Conductivity |
Electrical conductivity (ΞΌS/cm) | < 400 |
Organic_carbon |
Organic matter (ppm) | < 2 |
Trihalomethanes |
THM disinfection byproducts (ΞΌg/L) | < 80 |
Turbidity |
Water clarity (NTU) | < 5 |
This project follows a structured 8-stage machine learning pipeline:
- File: 01_problem_definition.ipynb
- Defined binary classification problem: potable (safe) vs. non-potable (unsafe)
- Reviewed water quality standards and health implications
- Set evaluation metrics: F1-score (primary, due to class imbalance), Accuracy, Precision, Recall, ROC-AUC
- File: 02_data_collection.ipynb
- Source: Water Potability Dataset from Kaggle
- Loaded raw data: 3,276 samples Γ 10 features
- Identified missing values:
ph(491),Sulfate(781),Trihalomethanes(162) - Class distribution: ~61% Non-Potable, ~39% Potable (class imbalance detected)
- File: 03_preprocessing.ipynb
- Missing values: Class-wise median imputation (preserves class statistics better than global median)
- Outliers: IQR-based Winsorization (capping extreme values) to preserve data magnitude while reducing influence
- Duplicates: Verified zero duplicate rows
- Output:
data/processed/water_potability_cleaned.csv
- File: 04_eda.ipynb
- Distribution plots with KDE curves (overlaid by Potability class)
- Correlation heatmap (Pearson correlation, visualized with clustermap)
- Violin plots showing feature distributions per class
- Statistical tests: Mann-Whitney U test for all features (identify significant predictors)
- Finding: Features show significant overlap between classes β non-linear models likely needed
- File: 05_feature_engineering.ipynb
- Created 15 new engineered features:
- WHO safety binary flags (9 features) β flag if each parameter meets WHO safe limits
total_who_compliantβ count of WHO-compliant parameters- Ratio features:
hardness_to_conductivity,chloramines_to_thm,organic_to_turbidity ph_deviationβ absolute distance from neutral pH 7.0- Log transforms:
log_solids,log_conductivity
- Feature selection: Random Forest Gini importance (threshold: 0.01) + Mutual Information ranking
- Train-Test Split: 80-20 split with stratification applied here to maintain class balance
- Standardization: StandardScaler applied to numeric features; saved to
models/scaler.pkl - Output:
data/processed/water_potability_engineered.csv,models/selected_features.pkl
- File: 06_model_building.ipynb
- Trained 3 distinct models with GridSearchCV (5-fold cross-validation):
| Model | Hyperparameters Tuned |
|---|---|
| Random Forest | n_estimators: [100, 200, 300], max_depth: [None, 10, 20], min_samples_split: [2, 5], max_features: ["sqrt", "log2"] |
| SVM | C: [0.1, 1, 10], kernel: [rbf, linear], gamma: [scale, auto] |
| XGBoost | n_estimators: [100, 200], max_depth: [3, 5, 7], learning_rate: [0.05, 0.1, 0.2], subsample: [0.8, 1.0] |
- Class imbalance handled: SMOTE applied to training data only (prevents data leakage)
- Models saved: Each trained model pickled to
models/random_forest.pkl,models/svm.pkl,models/xgboost.pkl
- File: 07_model_evaluation.ipynb
- Evaluated all 3 models on held-out 20% test set:
- Classification reports (Precision, Recall, F1-score per class)
- Confusion matrices
- ROC-AUC curves with AUC scores
- Precision-Recall curves
- Threshold optimization (F1-optimal, cost-optimal, balanced)
- Best model selection: Automatically selected based on ROC-AUC
- Output:
models/best_model.pkl,models/best_model_name.pkl
- File: 08_explainability.ipynb
- SHAP (SHapley Additive exPlanations) analysis:
- Global explanation: Summary plots showing feature importance across entire test set
- Local explanation: Waterfall plots for individual predictions (potable vs. non-potable samples)
- Dependence plots: Feature interaction insights for top 3 predictive features
- Actionable insights: Specific environmental monitoring recommendations derived
- Visualizations saved to
data/processed/for use in Streamlit app
The Streamlit web app provides an interactive interface with:
- Real-time Predictions: Input water sample parameters via sliders
- Multi-model Support: Compare predictions across Random Forest, SVM, and XGBoost
- WHO Compliance Checker: Visualize which parameters meet WHO safe limits
- Prediction Confidence: Display probabilities for both potable/non-potable classes
- SHAP Explainability: Interactive plots explaining individual predictions
- Evaluation Metrics: Confusion matrices, ROC curves, and performance dashboards
(Screenshots will be added after deployment)
Water-Quality-Classification/
βββ 01_problem_definition.ipynb β Stage 1: Problem definition
βββ 02_data_collection.ipynb β Stage 2: Data loading & exploration
βββ 03_preprocessing.ipynb β Stage 3: Cleaning & preprocessing
βββ 04_eda.ipynb β Stage 4: Exploratory data analysis
βββ 05_feature_engineering.ipynb β Stage 5: Feature creation & selection
βββ 06_model_building.ipynb β Stage 6: Model training & tuning
βββ 07_model_evaluation.ipynb β Stage 7: Model evaluation & comparison
βββ 08_explainability.ipynb β Stage 8: SHAP analysis
βββ app.py β Streamlit web application (run from root)
βββ requirements.txt β Python dependencies
βββ README.md β This file
βββ GIT_WORKFLOW.md β Team collaboration guide
βββ .gitignore β Git ignore rules
β
βββ data/
β βββ raw/
β β βββ water_potability.csv β Original dataset from Kaggle (download manually)
β βββ processed/
β βββ water_potability_cleaned.csv β After preprocessing (Stage 3)
β βββ water_potability_engineered.csv β After feature engineering (Stage 5)
β βββ X_train.csv, X_train_scaled.csv β Training features (scaled)
β βββ X_test.csv, X_test_scaled.csv β Test features (scaled)
β βββ y_train.csv, y_test.csv β Training/test labels
β βββ water_potability_raw_copy.csv β Backup copy
β
βββ models/
β βββ random_forest.pkl β Trained Random Forest model
β βββ svm.pkl β Trained SVM model
β βββ xgboost.pkl β Trained XGBoost model
β βββ best_model.pkl β Best performing model
β βββ best_model_name.pkl β Name of best model
β βββ scaler.pkl β StandardScaler (fit on train data)
β βββ selected_features.pkl β Selected feature names list
β
βββ .venv/ β Python virtual environment (gitignored)
βββ .git/ β Git repository metadata
β οΈ Important: The Streamlit app loads pre-trained models and processed data from disk. You must run notebooks 01β07 in order before launchingapp.py, otherwise the app will fail to load models and display errors.
- Go to Kaggle β Water Potability Dataset
- Sign in with a free Kaggle account (required to download)
- Click Download and extract the ZIP
- Rename the file to
water_potability.csvif needed - Place it at:
data/raw/water_potability.csv
# 1. Clone the repository
git clone https://github.com/YOUR_ORG/water-quality-project.git
cd water-quality-project
# 2. Create and activate virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Place the dataset (see Step 0 above)
# β data/raw/water_potability.csv
# 5. Run notebooks IN ORDER (01 β 07)
jupyter notebook
# Open and run each notebook: 01 β 02 β 03 β 04 β 05 β 06 β 07 β 08
# 6. Launch the Streamlit app
streamlit run app.pyThe app will open at http://localhost:8501
# If models/ and data/processed/ directories are already populated:
streamlit run app.py- Push code to GitHub (ensure
models/anddata/processed/are committed or use Git LFS) - Go to Streamlit Cloud
- Click "New app" β Select your repository, branch, and set main file to
app.py - Click Deploy β your app will be live at:
https://your-username-projectname.streamlit.app - Update the Live Demo link at the top of this README with the real URL
- Python: 3.10 or higher
- Git: For version control
- Kaggle Account: To download the dataset (free)
Key Python Packages:
pandas,numpy,scipyβ Data manipulation & statisticsscikit-learn,xgboost,lightgbmβ Machine learning modelsimbalanced-learnβ SMOTE for handling class imbalanceshapβ Model explainabilitymatplotlib,seaborn,plotlyβ Data visualizationstreamlitβ Web app frameworkjoblibβ Model serialization
All dependencies listed in requirements.txt
See GIT_WORKFLOW.md for detailed instructions on:
- Initial repository setup
- Creating feature branches
- Committing with meaningful messages
- Opening and reviewing Pull Requests
- Using GitHub Issues for task tracking
Quick Summary of Branch Strategy:
# Each team member creates their own feature branch
git checkout -b feature/stage-N-description
# Examples:
git checkout -b feature/stage-4-eda-analysis
git checkout -b feature/stage-6-model-training
# After finishing, create a PR for review before merging to mainCommit Message Convention:
git commit -m "feat(stage-N): Brief description of changes
- Detailed point 1
- Detailed point 2
- Files saved to: path/to/output"After running all stages:
-
Best Model: Random Forest (selected by ROC-AUC)
- ROC-AUC, F1-score, Precision-Recall curves in
07_model_evaluation.ipynb
- ROC-AUC, F1-score, Precision-Recall curves in
-
Top Predictive Features (SHAP-verified):
Sulfateβ most critical for potability determinationph_deviationβ distance from neutral pH (7.0) is a key signalChloraminesβ disinfection quality strongly influences prediction
-
Class Imbalance Impact:
- SMOTE improved recall for minority (potable) class
- F1-score is a more reliable metric than accuracy for this dataset
-
WHO Compliance Insights:
- Engineered WHO-compliance flags are strong predictors
total_who_compliantscore correlates positively with potability
The project uses SHAP (SHapley Additive exPlanations) to interpret model predictions:
- Global Explanations: Which features matter most across all predictions
- Local Explanations: Why a specific water sample was predicted potable/non-potable
- Dependence Plots: How feature values affect predictions
- Waterfall Plots: Breakdown of prediction components per sample
All SHAP visualizations are generated in 08_explainability.ipynb and displayed in the Streamlit app.
Solution: Run notebooks 01β07 in order first. All .pkl files must exist in models/ before launching the app. Required files: random_forest.pkl, svm.pkl, xgboost.pkl, best_model.pkl, best_model_name.pkl, scaler.pkl, selected_features.pkl
Solution: Run notebooks 03β05 to regenerate data/processed/ files. Required: X_test.csv, X_test_scaled.csv, y_test.csv
Solution: Download from Kaggle and place at data/raw/water_potability.csv. A Kaggle account is required to download.
Solution: pip install imbalanced-learn==0.12.3
Solution: streamlit run app.py --server.port 8502
Solution: pip install shap==0.45.1 β ensure version matches requirements.txt
| Category | Tools |
|---|---|
| Languages | Python 3.10+ |
| Data Science | pandas, numpy, scipy, scikit-learn |
| ML Models | Random Forest, SVM, XGBoost |
| Imbalanced Data | SMOTE (imbalanced-learn) |
| Explainability | SHAP |
| Visualization | matplotlib, seaborn, plotly |
| Web Framework | Streamlit |
| Version Control | Git, GitHub |
| Notebooks | Jupyter |
By completing this project, you will learn:
β
End-to-end machine learning pipeline (data β deployment)
β
Handling class imbalance with SMOTE
β
Hyperparameter tuning with GridSearchCV
β
Model evaluation beyond accuracy (F1, ROC-AUC, Precision-Recall)
β
Feature engineering and domain knowledge application (WHO standards)
β
Model interpretation with SHAP
β
Interactive web app deployment with Streamlit
β
Collaborative development with Git & GitHub
β
Real-world problem solving: predicting water safety
- Add more classification models (Neural Networks, Gradient Boosting)
- Implement real-time IoT sensor data integration
- Add time-series analysis for temporal patterns
- Incorporate microbiological indicators (bacteria, viruses)
- Create REST API for model predictions (FastAPI)
- Add automated retraining pipeline
- Expand to multi-class classification (Excellent, Good, Fair, Poor water quality)
- Kaggle Water Potability Dataset
- WHO Drinking-water Quality Standards
- SHAP Documentation
- Streamlit Official Docs
- Scikit-learn Model Selection & Evaluation
This project is for educational and research purposes. The dataset is provided under the Open Data Commons Open Database License (ODbL).
Last Updated: May 2026
Project Status: β
Active Development