CoolFace
Apppublic

KALYAN1188/Household-Energy-Consumption-Predictor

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
App README

🏠 Predicting Appliance Energy Consumption In Households

![Python](https://www.python.org/) ![scikit-learn](https://scikit-learn.org/) ![Gradio](https://gradio.app/) ![License](LICENSE)

ML-powered household energy consumption prediction with comprehensive insights for energy optimization, cost reduction, and grid management.


🎯 Project Overview

Our client, an energy management company, aims to enhance their understanding of appliance energy consumption patterns in residential settings. This project leverages machine learning to predict appliance energy usage based on various environmental and household factors.

🌟 Project Benefits

BenefitDescription
⚑ Energy OptimizationIdentifies key factors influencing consumption for targeted saving strategies
πŸ’° Cost ReductionHelps customers manage consumption and reduce electricity bills
πŸ”Œ Grid ManagementAssists in power grid load balancing during peak hours

πŸ“Š Model Performance

MetricValue
Test RΒ² Score0.70
Test MSE465.23 WhΒ²
Test RMSE21.57 Wh
Test MAE14.27 Wh
Test MAPE17.32%
Overfit Gap-0.06 (Excellent generalization)
Dataset Size19,735 records
Features40+ engineered features

Interpretation: Model explains 70% of energy variance with average error of Β±14.27 Wh. Negative overfit gap indicates excellent generalization β€” model performs better on unseen data!


πŸš€ Live Demo

Try the live application here: πŸ”— [Hugging Face Space](https://huggingface.co/spaces/YOUR_USERNAME/energy-consumption-predictor)


πŸ“ Project Structure

household-energy-prediction/
β”œβ”€β”€ notebook.ipynb                    # Complete ML pipeline (12 steps)
β”œβ”€β”€ app.py                            # Gradio deployment app
β”œβ”€β”€ final_model.pkl                   # Trained model package
β”œβ”€β”€ requirements.txt                  # Python dependencies
β”œβ”€β”€ README.md                         # This file
β”œβ”€β”€ energydata_complete.csv           # Dataset
└── outputs/                          # Generated visualizations
    β”œβ”€β”€ 01_target_analysis.png
    β”œβ”€β”€ 02_feature_distributions.png
    β”œβ”€β”€ 03_correlation_analysis.png
    β”œβ”€β”€ 04_time_patterns.png
    β”œβ”€β”€ 05_scatter_plots.png
    β”œβ”€β”€ 06_room_analysis.png
    β”œβ”€β”€ 07_lights_analysis.png
    β”œβ”€β”€ 08_weather_analysis.png
    β”œβ”€β”€ 09_multicollinearity.png
    β”œβ”€β”€ 10_consumption_categories.png
    β”œβ”€β”€ 11_outlier_handling.png
    β”œβ”€β”€ 12_feature_engineering.png
    β”œβ”€β”€ 13_model_comparison.png
    β”œβ”€β”€ 14_cross_validation.png
    β”œβ”€β”€ 15_feature_importance.png
    β”œβ”€β”€ 16_shap_importance.png
    β”œβ”€β”€ 17_shap_beeswarm.png
    └── 18_error_analysis.png

πŸ› οΈ Installation

Prerequisites

  • β€”Python 3.11 or higher
  • β€”pip package manager

Step 1: Clone Repository

bash
git clone https://github.com/YOUR_USERNAME/household-energy-prediction.git
cd household-energy-prediction

Step 2: Create Virtual Environment (Recommended)

bash
# Create virtual environment
python -m venv venv

# Activate β€” Windows:
venv\Scripts\activate

# Activate β€” Mac/Linux:
source venv/bin/activate

Step 3: Install Dependencies

bash
pip install -r requirements.txt

πŸŽ“ How to Reproduce

Option 1: Run Complete Training Pipeline

bash
# Step 1: Open Jupyter notebook
jupyter notebook notebook.ipynb

# Step 2: Run all cells from top to bottom
# The notebook will automatically:
#   - Load and clean data
#   - Perform comprehensive EDA (11 sections)
#   - Engineer 40+ features including lag features
#   - Train 14 different models
#   - Perform hyperparameter tuning
#   - Run time series cross-validation
#   - Generate SHAP analysis
#   - Create 18 visualizations
#   - Save final model as final_model.pkl

# Step 3: Wait for completion (~15-20 minutes)
# Step 4: Check outputs/ folder for all generated plots

Option 2: Use Pre-trained Model

bash
# Run Gradio app directly
python app.py

This launches the interface at http://localhost:7860


πŸ”¬ Methodology

1. Data Overview

  • β€”Dataset: 19,735 records at 10-minute intervals (Jan–May 2016)
  • β€”Target: Appliances β€” energy use in Wh
  • β€”Features: 29 original β†’ 40+ after engineering
  • β€”Missing Values: None βœ…
  • β€”Duplicate Rows: None βœ…

2. Data Split Strategy

TIME-BASED SPLIT (respects temporal order):
β”œβ”€β”€ Train  : 70% β†’ Jan–Mar 2016
β”œβ”€β”€ Val    : 15% β†’ Mar–Apr 2016
└── Test   : 15% β†’ Apr–May 2016

βœ… Split done BEFORE any preprocessing (zero data leakage)
βœ… No shuffle β€” preserves time series order

3. Exploratory Data Analysis (11 Sections)

SectionAnalysis
4ATarget variable distribution & time series
4BFeature distributions (all 29 features)
4CCorrelation analysis & heatmap
4DTime-based patterns (hour, day, weekend)
4EScatter plots β€” top correlated features
4FPlotly interactive visualizations
4GRoom-wise temperature & humidity analysis
4HLights vs appliances relationship
4IWeather features vs energy
4JMulticollinearity & random variables
4KConsumption category breakdown

4. Feature Engineering (40+ Features)

Time Features:

  • β€”Hour, day of week, month, day
  • β€”Is weekend, is night, is peak hour
  • β€”Minute of day

Temperature & Humidity Aggregates:

  • β€”Average/max/min indoor temperature
  • β€”Indoor temperature range
  • β€”Indoor vs outdoor differential

Interaction Features:

  • β€”Temperature Γ— Humidity
  • β€”Temperature Γ— Hour
  • β€”Lights Γ— Hour

Lag Features (Most Important!):

  • β€”lag1 to lag12 (10 min to 2 hours ago)
  • β€”lag_144 (1 day ago)
  • β€”lag_288 (2 days ago)

Rolling Window Features:

  • β€”Rolling mean (3, 6, 12, 24 intervals)
  • β€”Rolling std, max, min (6 intervals)

5. Outlier Handling

Strategy:
β”œβ”€β”€ Train  : REMOVE outliers (IQR method, multiplier=1.5)
β”œβ”€β”€ Val    : CAP outliers at bounds
└── Test   : CAP outliers at bounds

Bounds computed on TRAIN ONLY β†’ applied to Val/Test

6. Model Training & Comparison

Evaluated 14 regression models:

CategoryModels
LinearLinear Regression, Ridge, Lasso, ElasticNet
Tree-BasedDecision Tree, Random Forest, Extra Trees
BoostingGradient Boosting, AdaBoost, XGBoost, LightGBM, CatBoost
OtherKNN, SVR

Best Model: Lasso Regression

  • β€”Val RΒ²: 0.672 (highest among all models)
  • β€”Overfit Gap: -0.047 (no overfitting!)

7. Hyperparameter Tuning

Method    : RandomizedSearchCV
CV        : 5-Fold Time Series Split
Iterations: 50
Scoring   : RΒ²
Best Alpha: 0.1

8. Model Evaluation

A) Time Series Cross-Validation (5-Fold):
   RΒ² Mean  : 0.6050 Β± 0.0622
   MSE Mean : 305.41 Β± 55.23
   RMSE Mean: 17.45 Β± 1.60
   MAE Mean : 12.07 Β± 0.87

B) SHAP Analysis:
   - LinearExplainer for interpretability
   - Lag features dominate importance
   - Rolling features second most important

C) Comprehensive Error Analysis:
   - 9-plot error visualization
   - Error by price range
   - Cumulative error distribution

9. Key Findings

  1. 1.Lag features are the strongest predictors β€” what happened in the last 10-60 minutes best predicts current usage
  2. 2.Linear models outperform tree models β€” lag features create linear relationships
  3. 3.Peak hours (5-9PM) show highest energy consumption
  4. 4.Energy is 57% higher when lights are ON vs lights off
  5. 5.No overfitting β€” model generalizes perfectly to unseen data

10. Deployment

  • β€”Framework: Gradio 5.10.0
  • β€”Features:
  • β€”5 output tabs (Prediction, Cost, Grid, Tips, Summary)
  • β€”Real-time cost estimation in β‚Ή
  • β€”Peak hour warnings
  • β€”Personalized energy saving tips
  • β€”Grid management recommendations
  • β€”COβ‚‚ emissions tracking
  • β€”Platform: Hugging Face Spaces

πŸ“Š Visualizations Generated

#VisualizationDescription
01Target AnalysisDistribution, time series, box plot
02Feature DistributionsAll 29 features with skewness
03Correlation AnalysisHeatmap + target correlations
04Time PatternsHour, day, weekend heatmap
05Scatter PlotsTop 8 features vs target
06Room AnalysisTemperature & humidity by room
07Lights AnalysisLights ON vs OFF impact
08Weather AnalysisAll weather features vs energy
09MulticollinearityTemperature correlation heatmap
10Consumption CategoriesLow/Medium/High breakdown
11Outlier HandlingBefore/after comparison
12Feature EngineeringNew features vs energy
13Model Comparison14 models RΒ², MSE, RMSE, overfit
14Cross-Validation5-fold time series results
15Feature ImportancePermutation importance
16SHAP Bar PlotFeature importance via SHAP
17SHAP BeeswarmValue distribution via SHAP
18Error AnalysisComprehensive 9-plot analysis

πŸ› Troubleshooting

Model Loading Issues

python
import joblib, sklearn
print(f"sklearn version: {sklearn.__version__}")
# Should be 1.6.1

SHAP Installation Issues

bash
# Windows
pip install shap --no-build-isolation

# Linux/Mac
pip install shap

Gradio Version Issues

bash
pip install gradio==5.10.0

πŸ“ˆ Future Improvements

  • β€”[ ] Add more data sources (smart meter data)
  • β€”[ ] Implement occupancy detection features
  • β€”[ ] Real-time data streaming
  • β€”[ ] Mobile app deployment
  • β€”[ ] API for third-party integration
  • β€”[ ] Advanced deep learning models (LSTM)

🀝 Contributing

Contributions are welcome!

  1. 1.Fork the repository
  2. 2.Create a feature branch
  3. 3.Make your changes
  4. 4.Submit a pull request

πŸ“„ License

This project is licensed under the MIT License.


πŸ‘¨β€πŸ’» Developer

Sai Kalyan Machine Learning Engineer


πŸ“š References

  1. 1.UCI Machine Learning Repository β€” Appliances Energy Prediction Dataset
  2. 2.Candanedo, L.M., Feldheim, V., Deramaix, D. (2017). "Data driven prediction models of energy use of appliances in a low-energy house"
  3. 3.SHAP: Lundberg, S.M., & Lee, S.I. (2017). "A Unified Approach to Interpreting Model Predictions"
  4. 4.Lasso Regression: Tibshirani, R. (1996). "Regression Shrinkage and Selection via the Lasso"

⭐ If you found this project helpful, please give it a star!

Last Updated: March 2026 | Version: 1.0