give me an app code of electricity consumption prediction analysis which i give month and they give me predicted month
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import plotly.express as px
from datetime import datetime, timedelta
# Set page title
st.title("Electricity Consumption Prediction")
# Generate sample data
def generate_sample_data():
np.random.seed(42)
dates = pd.date_range(start='2020-01-01', end='2023-12-31', freq='M')
consumption = np.random.normal(1000, 200, len(dates)) # Random consumption values
# Add seasonal variation
seasonal_factor = np.sin(np.arange(len(dates)) * 2 * np.pi / 12) * 200
consumption += seasonal_factor
consumption = np.abs(consumption) # Ensure positive values
df = pd.DataFrame({
'Date': dates,
'Consumption': consumption,
'Month': dates.month,
'Year': dates.year
})
return df
# Load data
df = generate_sample_data()
# Prepare features for model
X = df.index.values.reshape(-1, 1)
y = df['Consumption'].values
# Train model
model = LinearRegression()
model.fit(X, y)
# Create prediction interface
st.subheader("Predict Future Consumption")
# Allow user to select future months
months_to_predict = st.slider("Select number of months to predict:", 1, 24, 6)
# Generate future dates
last_date = df['Date'].iloc[-1]
future_dates = pd.date_range(start=last_date + timedelta(days=31),
periods=months_to_predict,
freq='M')
# Make predictions
future_indices = np.arange(len(df), len(df) + months_to_predict).reshape(-1, 1)
predictions = model.predict(future_indices)
# Create future DataFrame
future_df = pd.DataFrame({
'Date': future_dates,
'Consumption': predictions,
'Month': future_dates.month,
'Year': future_dates.year
})
# Display predictions
st.subheader("Predicted Consumption")
st.write(future_df)
# Visualize historical data and predictions
fig = px.line(df, x='Date', y='Consumption', title='Historical and Predicted Electricity Consumption')
fig.add_scatter(x=future_df['Date'], y=future_df['Consumption'],
name='Predictions', line=dict(dash='dash'))
st.plotly_chart(fig)
# Show model performance metrics
st.subheader("Model Information")
col1, col2 = st.columns(2)
with col1:
st.metric("Model R² Score", f"{model.score(X, y):.3f}")
with col2:
avg_consumption = future_df['Consumption'].mean()
st.metric("Average Predicted Consumption", f"{avg_consumption:.2f} kWh")
# Add explanatory notes
st.markdown("""
### Notes:
- This is a simplified prediction model using linear regression
- The model takes into account historical trends and seasonal patterns
- Predictions are based on past consumption patterns
- Actual consumption may vary due to various factors not considered in this simple model
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?