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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import plotly.express as px
|
| 6 |
+
from io import StringIO
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
|
| 9 |
+
# Debug: Verify file paths
|
| 10 |
+
st.write("Debug: Checking file paths...")
|
| 11 |
+
files_to_check = ["inference.py", "new_best_improved_model.pth", "scaler.pkl", "feature_names.json"]
|
| 12 |
+
for file in files_to_check:
|
| 13 |
+
if os.path.exists(file):
|
| 14 |
+
st.write(f"{file} found")
|
| 15 |
+
else:
|
| 16 |
+
st.error(f"{file} not found")
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from inference import load_model_and_artifacts, forecast
|
| 20 |
+
except Exception as e:
|
| 21 |
+
st.error(f"Error importing inference: {str(e)}")
|
| 22 |
+
st.stop()
|
| 23 |
+
|
| 24 |
+
st.title("Store Sales Forecasting")
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
model, scaler, feature_names = load_model_and_artifacts()
|
| 28 |
+
st.success("Model and artifacts loaded successfully")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
st.error(f"Error loading model or artifacts: {str(e)}")
|
| 31 |
+
st.stop()
|
| 32 |
+
|
| 33 |
+
# Display model metrics
|
| 34 |
+
st.header("Model Performance Metrics")
|
| 35 |
+
metrics = {
|
| 36 |
+
"MAE": 710.75,
|
| 37 |
+
"RMSE": 1108.51,
|
| 38 |
+
"MAPE": 7.14,
|
| 39 |
+
"R2": 0.8633
|
| 40 |
+
}
|
| 41 |
+
st.write(f"- **MAE**: ${metrics['MAE']:.2f}")
|
| 42 |
+
st.write(f"- **RMSE**: ${metrics['RMSE']:.2f}")
|
| 43 |
+
st.write(f"- **MAPE**: {metrics['MAPE']:.2f}%")
|
| 44 |
+
st.write(f"- **R² Score**: {metrics['R2']:.4f}")
|
| 45 |
+
|
| 46 |
+
# Synthetic data generation
|
| 47 |
+
st.header("Test with Synthetic Data")
|
| 48 |
+
if st.button("Generate Synthetic Sample Data"):
|
| 49 |
+
np.random.seed(42)
|
| 50 |
+
sequence_length = 21
|
| 51 |
+
n_features = len(feature_names)
|
| 52 |
+
synthetic_data = np.zeros((sequence_length, n_features))
|
| 53 |
+
|
| 54 |
+
# Generate realistic data based on training sales range (~$3,000–19,000)
|
| 55 |
+
for i, feature in enumerate(feature_names):
|
| 56 |
+
if feature == "sales":
|
| 57 |
+
synthetic_data[:, i] = np.random.normal(8955, 3307, sequence_length) # Mean=8954.97, std=3307.49
|
| 58 |
+
elif feature == "onpromotion":
|
| 59 |
+
synthetic_data[:, i] = np.random.choice([0, 1], sequence_length, p=[0.8, 0.2])
|
| 60 |
+
elif feature in ["dayofweek_sin", "dayofweek_cos", "month_sin", "month_cos"]:
|
| 61 |
+
synthetic_data[:, i] = np.sin(np.linspace(0, 2 * np.pi, sequence_length))
|
| 62 |
+
elif feature == "trend":
|
| 63 |
+
synthetic_data[:, i] = np.linspace(0, sequence_length, sequence_length)
|
| 64 |
+
elif feature == "is_weekend":
|
| 65 |
+
synthetic_data[:, i] = np.random.choice([0, 1], sequence_length, p=[0.7, 0.3])
|
| 66 |
+
elif feature == "quarter":
|
| 67 |
+
synthetic_data[:, i] = np.random.choice([1, 2, 3, 4], sequence_length)
|
| 68 |
+
elif "lag" in feature:
|
| 69 |
+
synthetic_data[:, i] = np.roll(synthetic_data[:, 0], int(feature.split('_')[-1])) if i > 0 else np.zeros(sequence_length)
|
| 70 |
+
elif "ma" in feature or "std" in feature:
|
| 71 |
+
synthetic_data[:, i] = np.random.normal(8955, 1000, sequence_length)
|
| 72 |
+
elif "ratio" in feature:
|
| 73 |
+
synthetic_data[:, i] = np.random.normal(1, 0.2, sequence_length)
|
| 74 |
+
elif "promo" in feature:
|
| 75 |
+
synthetic_data[:, i] = np.random.choice([0, 1], sequence_length, p=[0.8, 0.2])
|
| 76 |
+
elif feature == "dcoilwtico":
|
| 77 |
+
synthetic_data[:, i] = np.random.normal(80, 10, sequence_length)
|
| 78 |
+
elif feature == "is_holiday":
|
| 79 |
+
synthetic_data[:, i] = np.random.choice([0, 1], sequence_length, p=[0.9, 0.1])
|
| 80 |
+
|
| 81 |
+
synthetic_df = pd.DataFrame(synthetic_data, columns=feature_names)
|
| 82 |
+
end_date = datetime.now().date()
|
| 83 |
+
dates = [end_date - timedelta(days=x) for x in range(sequence_length-1, -1, -1)]
|
| 84 |
+
synthetic_df.index = dates
|
| 85 |
+
st.session_state["synthetic_df"] = synthetic_df
|
| 86 |
+
|
| 87 |
+
st.subheader("Synthetic Sample Data Preview")
|
| 88 |
+
st.write(synthetic_df.head())
|
| 89 |
+
|
| 90 |
+
csv_buffer = StringIO()
|
| 91 |
+
synthetic_df.to_csv(csv_buffer)
|
| 92 |
+
st.download_button(
|
| 93 |
+
label="Download Synthetic Sample CSV",
|
| 94 |
+
data=csv_buffer.getvalue(),
|
| 95 |
+
file_name="synthetic_sample.csv",
|
| 96 |
+
mime="text/csv"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
sequences = synthetic_df[feature_names].values
|
| 101 |
+
sequences = scaler.transform(sequences)
|
| 102 |
+
sequences = sequences.reshape(-1, sequence_length, n_features)
|
| 103 |
+
predictions, uncertainties = forecast(model, scaler, sequences)
|
| 104 |
+
|
| 105 |
+
forecast_dates = [end_date + timedelta(days=x*7) for x in range(1, 14)]
|
| 106 |
+
df_predictions = pd.DataFrame({
|
| 107 |
+
'Date': forecast_dates,
|
| 108 |
+
'Predicted Sales ($)': predictions[0],
|
| 109 |
+
'Uncertainty ($)': uncertainties[0]
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
st.subheader("Forecast Results")
|
| 113 |
+
st.table(df_predictions)
|
| 114 |
+
|
| 115 |
+
fig = px.line(df_predictions, x='Date', y='Predicted Sales ($)', title='13-Week Sales Forecast')
|
| 116 |
+
fig.add_scatter(
|
| 117 |
+
x=df_predictions['Date'],
|
| 118 |
+
y=df_predictions['Predicted Sales ($)'] + df_predictions['Uncertainty ($)'],
|
| 119 |
+
mode='lines', name='Upper Bound', line=dict(dash='dash', color='red')
|
| 120 |
+
)
|
| 121 |
+
fig.add_scatter(
|
| 122 |
+
x=df_predictions['Date'],
|
| 123 |
+
y=df_predictions['Predicted Sales ($)'] - df_predictions['Uncertainty ($)'],
|
| 124 |
+
mode='lines', name='Lower Bound', line=dict(dash='dash', color='red'),
|
| 125 |
+
fill='tonexty', fillcolor='rgba(255, 0, 0, 0.1)'
|
| 126 |
+
)
|
| 127 |
+
st.plotly_chart(fig)
|
| 128 |
+
except Exception as e:
|
| 129 |
+
st.error(f"Error generating forecast: {str(e)}")
|
| 130 |
+
|
| 131 |
+
# Manual CSV upload
|
| 132 |
+
st.header("Upload Your Own Data")
|
| 133 |
+
st.write("Upload a CSV with 21 timesteps and 20 features.")
|
| 134 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
|
| 135 |
+
|
| 136 |
+
if uploaded_file is not None:
|
| 137 |
+
try:
|
| 138 |
+
data = pd.read_csv(uploaded_file)
|
| 139 |
+
if set(feature_names).issubset(data.columns) and len(data) == 21:
|
| 140 |
+
sequences = data[feature_names].values
|
| 141 |
+
sequences = scaler.transform(sequences)
|
| 142 |
+
sequences = sequences.reshape(-1, 21, len(feature_names))
|
| 143 |
+
predictions, uncertainties = forecast(model, scaler, sequences)
|
| 144 |
+
df_predictions = pd.DataFrame({
|
| 145 |
+
'Week': range(1, 14),
|
| 146 |
+
'Predicted Sales ($)': predictions[0],
|
| 147 |
+
'Uncertainty ($)': uncertainties[0]
|
| 148 |
+
})
|
| 149 |
+
st.subheader("Forecast Results")
|
| 150 |
+
st.table(df_predictions)
|
| 151 |
+
|
| 152 |
+
fig = px.line(df_predictions, x='Week', y='Predicted Sales ($)', title='13-Week Sales Forecast')
|
| 153 |
+
fig.add_scatter(
|
| 154 |
+
x=df_predictions['Week'],
|
| 155 |
+
y=df_predictions['Predicted Sales ($)'] + df_predictions['Uncertainty ($)'],
|
| 156 |
+
mode='lines', name='Upper Bound', line=dict(dash='dash', color='red')
|
| 157 |
+
)
|
| 158 |
+
fig.add_scatter(
|
| 159 |
+
x=df_predictions['Week'],
|
| 160 |
+
y=df_predictions['Predicted Sales ($)'] - df_predictions['Uncertainty ($)'],
|
| 161 |
+
mode='lines', name='Lower Bound', line=dict(dash='dash', color='red'),
|
| 162 |
+
fill='tonexty', fillcolor='rgba(255, 0, 0, 0.1)'
|
| 163 |
+
)
|
| 164 |
+
st.plotly_chart(fig)
|
| 165 |
+
else:
|
| 166 |
+
st.error(f"Invalid CSV. Ensure 21 rows and columns: {', '.join(feature_names)}")
|
| 167 |
+
except Exception as e:
|
| 168 |
+
st.error(f"Error processing CSV or making prediction: {str(e)}")
|