Rhaya03's picture
Update app.py
5b4abd3 verified
import gradio as gr
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
# Load the dataseth
def load_data():
"""
Loads the home energy consumption dataset. Handles potential file errors.
"""
try:
# Using a more robust path and filename.
data = pd.read_csv("home_energy_data.csv")
return data
except FileNotFoundError:
print("Error: 'home_energy_data.csv' not found. Creating sample data.")
return create_sample_data()
except Exception as e:
print(f"An error occurred while loading the data: {e}")
return None # Important: Return None to signal failure
def create_sample_data():
"""
Generates a sample dataset for demonstration purposes.
"""
# Create a sample dataset.
data = {
'Home Size (sqft)': [1000, 1500, 2000, 1200, 1800, 2500, 1300, 1600, 2100, 1100],
'Num Occupants': [2, 3, 4, 2, 3, 5, 2, 4, 3, 2],
'Avg Temp (°F)': [65, 70, 75, 68, 72, 78, 66, 71, 74, 67],
'Has Solar Panels': [0, 0, 1, 0, 1, 1, 0, 1, 0, 0],
'Energy Consumption (kWh)': [800, 1200, 1500, 950, 1300, 1800, 1050, 1250, 1600, 900],
'Daily Cost ($)': [20, 30, 37.5, 23.75, 32.5, 45, 26.25, 31.25, 40, 22.5]
}
return pd.DataFrame(data)
# Preprocess the data and train the model
def train_model(data):
"""
Preprocesses the data, trains a linear regression model, and returns the model and scaler.
Handles potential errors during training.
Args:
data: The input pandas DataFrame.
Returns:
A tuple containing the trained model and the scaler, or (None, None) on error.
"""
if data is None:
return None, None # Exit if data loading failed
try:
# Select features and target
features = ['Home Size (sqft)', 'Num Occupants', 'Avg Temp (°F)', 'Has Solar Panels']
target = 'Energy Consumption (kWh)'
X = data[features]
y = data[target]
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Scale test data
# Train a linear regression model
model = LinearRegression()
model.fit(X_train_scaled, y_train)
return model, scaler # Return both the model and the scaler
except Exception as e:
print(f"An error occurred during model training: {e}")
return None, None # Return None, None on error
# Make energy consumption prediction
def predict_energy_consumption(model, scaler, home_size, num_occupants, avg_temp, has_solar_panels):
"""
Predicts energy consumption based on user inputs, handling potential errors.
Args:
model: The trained machine learning model.
scaler: The scaler used to transform the input features.
home_size: Home size in square feet.
num_occupants: Number of occupants.
avg_temp: Average temperature in Fahrenheit.
has_solar_panels: 1 if the home has solar panels, 0 if not.
Returns:
The predicted energy consumption in kWh, or an error message.
"""
if model is None or scaler is None:
return "Error: Model not trained."
try:
# Create a feature array from user inputs
input_features = np.array([[home_size, num_occupants, avg_temp, has_solar_panels]])
# Scale the input features using the scaler
input_features_scaled = scaler.transform(input_features)
# Make the prediction
prediction = model.predict(input_features_scaled)
return f"Predicted Monthly Energy Consumption: {prediction[0]:.2f} kWh"
except Exception as e:
return f"Error during prediction: {e}"
# Define the Gradio interface
def create_gradio_interface(model, scaler):
"""
Creates the Gradio interface for the Home Energy Optimization Model.
Args:
model: The trained machine learning model.
scaler: The scaler used to transform the input features.
Returns:
The Gradio interface.
"""
# Input components for the Gradio interface
home_size_input = gr.Number(label="Home Size (sqft)", value=1500)
num_occupants_input = gr.Number(label="Number of Occupants", value=3)
avg_temp_input = gr.Number(label="Average Temperature (°F)", value=70)
solar_panel_input = gr.Radio(choices=[0, 1], label="Has Solar Panels", value=0)
# Output component for the Gradio interface
output_label = gr.Label(label="Prediction")
# Create the Gradio interface
iface = gr.Interface(
fn=lambda home_size, num_occupants, avg_temp, has_solar_panels: predict_energy_consumption(
model, scaler, home_size, num_occupants, avg_temp, has_solar_panels
),
inputs=[home_size_input, num_occupants_input, avg_temp_input, solar_panel_input],
outputs=output_label,
title="Home Energy Consumption Predictor",
description="Enter your home details to predict energy consumption.",
examples=[
[1200, 2, 68, 0],
[2000, 4, 75, 1],
[1000, 2, 65, 0],
]
)
return iface
def main():
"""
Main function to load data, train the model, and launch the Gradio interface.
"""
data = load_data()
if data is not None:
model, scaler = train_model(data)
if model is not None and scaler is not None:
iface = create_gradio_interface(model, scaler)
iface.launch(share=True)
else:
print("Failed to train the model. Cannot launch interface.")
else:
print("Failed to load data. Cannot train model or launch interface.")
if __name__ == "__main__":
main()