Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,8 @@
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
3 |
-
from statsmodels.tsa.holtwinters import ExponentialSmoothing
|
4 |
-
import numpy as np
|
5 |
-
from itertools import product
|
6 |
from io import BytesIO
|
|
|
|
|
7 |
import plotly.express as px
|
8 |
|
9 |
# Function to run the Exponential Smoothing Model
|
@@ -17,15 +16,14 @@ def run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period)
|
|
17 |
return None, None
|
18 |
|
19 |
def create_data():
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
# Function to convert DataFrame to Excel
|
30 |
def to_excel(df):
|
31 |
output = BytesIO()
|
@@ -35,37 +33,25 @@ def to_excel(df):
|
|
35 |
processed_data = output.getvalue()
|
36 |
return processed_data
|
37 |
|
|
|
|
|
|
|
38 |
|
39 |
st.title("Exponential Smoothing Forecasting")
|
40 |
-
# Grid search button
|
41 |
-
if st.button('Run Grid Search'):
|
42 |
-
best_aic = float('inf')
|
43 |
-
best_params = None
|
44 |
-
for param_set in product(['add', 'mul', None], [True, False], ['add', 'mul', None], [12]):
|
45 |
-
_, temp_aic = run_exp_smoothing(city_data, *param_set)
|
46 |
-
if temp_aic and temp_aic < best_aic:
|
47 |
-
best_aic = temp_aic
|
48 |
-
best_params = param_set
|
49 |
-
st.write(f"Best Parameters: {best_params} with AIC: {best_aic}")
|
50 |
-
# Upload Data Section
|
51 |
-
# uploaded_file = st.file_uploader("Choose a file")
|
52 |
-
# if uploaded_file is not None:
|
53 |
|
|
|
54 |
data = create_data()
|
55 |
unique_cities = data['City'].unique()
|
56 |
|
57 |
# Select a city
|
58 |
selected_city = st.selectbox('Select a City', unique_cities)
|
59 |
|
60 |
-
# Sliders for parameter adjustment
|
61 |
-
trend = st.select_slider('Select Trend', options=['add', 'mul', None])
|
62 |
-
damped_trend = st.checkbox('Damped Trend')
|
63 |
-
seasonal = st.select_slider('Select Seasonal', options=['add', 'mul', None])
|
64 |
-
seasonal_period = st.slider('Seasonal Period', 1, 24,
|
65 |
|
66 |
-
# ... [previous code remains the same]
|
67 |
-
|
68 |
-
# Display forecast with current parameters
|
69 |
city_data = data[data['City'] == selected_city]['Accident Count']
|
70 |
forecast, aic = run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period)
|
71 |
|
@@ -74,17 +60,26 @@ if forecast is not None:
|
|
74 |
st.write(f"Trend: {trend}, Damped Trend: {damped_trend}, Seasonal: {seasonal}, Seasonal Period: {seasonal_period}")
|
75 |
forecast_index = pd.date_range(start=city_data.index[-1], periods=7, freq='M')[1:]
|
76 |
forecast_index = forecast_index.to_period('M') # Convert to period index with monthly frequency
|
77 |
-
|
78 |
-
forecast_df = pd.DataFrame(forecast,columns=['Forecast'])
|
79 |
-
# Ensure the index is correctly formatted as 'YYYY-MM'
|
80 |
-
# forecast_df.index = forecast_df.index.strftime('%Y-%m')
|
81 |
st.table(forecast_df)
|
82 |
fig = px.line(forecast_df, x=forecast_df.index, y="Forecast")
|
83 |
st.plotly_chart(fig)
|
84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
#
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
|
|
|
|
|
|
3 |
from io import BytesIO
|
4 |
+
from itertools import product
|
5 |
+
from statsmodels.tsa.holtwinters import ExponentialSmoothing
|
6 |
import plotly.express as px
|
7 |
|
8 |
# Function to run the Exponential Smoothing Model
|
|
|
16 |
return None, None
|
17 |
|
18 |
def create_data():
|
19 |
+
data = pd.read_csv('accident_count.csv', parse_dates=True, index_col=0)
|
20 |
+
data.index = pd.to_datetime(data.index, format='%Y%m')
|
21 |
+
data = data.groupby('City').resample('M').sum().reset_index()
|
22 |
+
data.index = data['Accident Month Bracket']
|
23 |
+
data = data.drop(['Accident Month Bracket'],axis=1)
|
24 |
+
data.index = data.index.strftime('%Y-%m')
|
25 |
+
return data
|
26 |
+
|
|
|
27 |
# Function to convert DataFrame to Excel
|
28 |
def to_excel(df):
|
29 |
output = BytesIO()
|
|
|
33 |
processed_data = output.getvalue()
|
34 |
return processed_data
|
35 |
|
36 |
+
# Initialize session state for best parameters
|
37 |
+
if 'best_params' not in st.session_state:
|
38 |
+
st.session_state.best_params = {'trend': None, 'damped_trend': False, 'seasonal': None, 'seasonal_period': 12}
|
39 |
|
40 |
st.title("Exponential Smoothing Forecasting")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
+
# Data preparation
|
43 |
data = create_data()
|
44 |
unique_cities = data['City'].unique()
|
45 |
|
46 |
# Select a city
|
47 |
selected_city = st.selectbox('Select a City', unique_cities)
|
48 |
|
49 |
+
# Sliders for parameter adjustment, using session state values as defaults
|
50 |
+
trend = st.select_slider('Select Trend', options=['add', 'mul', None], value=st.session_state.best_params['trend'])
|
51 |
+
damped_trend = st.checkbox('Damped Trend', value=st.session_state.best_params['damped_trend'])
|
52 |
+
seasonal = st.select_slider('Select Seasonal', options=['add', 'mul', None], value=st.session_state.best_params['seasonal'])
|
53 |
+
seasonal_period = st.slider('Seasonal Period', 1, 24, value=st.session_state.best_params['seasonal_period'])
|
54 |
|
|
|
|
|
|
|
55 |
city_data = data[data['City'] == selected_city]['Accident Count']
|
56 |
forecast, aic = run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period)
|
57 |
|
|
|
60 |
st.write(f"Trend: {trend}, Damped Trend: {damped_trend}, Seasonal: {seasonal}, Seasonal Period: {seasonal_period}")
|
61 |
forecast_index = pd.date_range(start=city_data.index[-1], periods=7, freq='M')[1:]
|
62 |
forecast_index = forecast_index.to_period('M') # Convert to period index with monthly frequency
|
63 |
+
forecast_df = pd.DataFrame(forecast, columns=['Forecast'])
|
|
|
|
|
|
|
64 |
st.table(forecast_df)
|
65 |
fig = px.line(forecast_df, x=forecast_df.index, y="Forecast")
|
66 |
st.plotly_chart(fig)
|
67 |
|
68 |
+
# Grid search button
|
69 |
+
if st.button('Run Grid Search'):
|
70 |
+
best_aic = float('inf')
|
71 |
+
best_params = None
|
72 |
+
for param_set in product(['add', 'mul', None], [True, False], ['add', 'mul', None], [12]):
|
73 |
+
_, temp_aic = run_exp_smoothing(city_data, *param_set)
|
74 |
+
if temp_aic and temp_aic < best_aic:
|
75 |
+
best_aic = temp_aic
|
76 |
+
best_params = param_set
|
77 |
|
78 |
+
# Updating session state with the best parameters
|
79 |
+
st.session_state.best_params = {
|
80 |
+
'trend': best_params[0],
|
81 |
+
'damped_trend': best_params[1],
|
82 |
+
'seasonal': best_params[2],
|
83 |
+
'seasonal_period': best_params[3]
|
84 |
+
}
|
85 |
+
st.write(f"Best Parameters: {best_params} with AIC: {best_aic}")
|