Silverxwolf commited on
Commit
f759104
·
1 Parent(s): 51f2dee

Upload main_general.py

Browse files
Files changed (1) hide show
  1. main_general.py +383 -0
main_general.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib
6
+ from prophet import Prophet
7
+ from sklearn.metrics import mean_squared_error, mean_absolute_error, mean_absolute_percentage_error
8
+ from math import sqrt
9
+ from pandas.tseries.offsets import DateOffset
10
+ from gluonts.dataset.common import ListDataset
11
+ from gluonts.mx import DeepAREstimator
12
+ from gluonts.mx.trainer import Trainer
13
+ from gluonts.evaluation import Evaluator
14
+ from gluonts.evaluation.backtest import make_evaluation_predictions
15
+ from pmdarima.arima import auto_arima
16
+
17
+ font = {'weight' : 'normal',
18
+ 'size' : 18}
19
+
20
+ matplotlib.rc('font', **font)
21
+
22
+ def preprocess(df, freq):
23
+ # group according to frequency
24
+ df.set_index('DOB', inplace=True)
25
+ df = df.resample(freq).sum()
26
+ df.reset_index('DOB', inplace=True)
27
+
28
+ # Replace small values with 0.01
29
+ df.loc[df["AMOUNT"] < 0.01, "AMOUNT"] = 0.01
30
+
31
+ return df
32
+
33
+ def evaluate(y_true, y_pred):
34
+ dict = {
35
+ 'MAE': mean_absolute_error(y_true, y_pred),
36
+ 'MSE': mean_squared_error(y_true, y_pred),
37
+ 'RMSE': np.sqrt(mean_squared_error(y_true, y_pred)),
38
+ 'MAPE': mean_absolute_percentage_error(y_true, y_pred)
39
+ }
40
+
41
+ return dict
42
+
43
+ def draw_results(y_true, y_pred, length, frequency):
44
+ x = np.arange(length)
45
+ f, ax = plt.subplots(1)
46
+ f.set_figheight(5)
47
+ f.set_figwidth(15)
48
+ ax.plot(x, y_true, marker='o', markersize=10, linestyle='', color='black', label='Actual data')
49
+ ax.plot(x, y_pred, marker='o', markersize=10, linestyle='', color='orange', label='Forecast')
50
+ ax.grid()
51
+ plt.xlabel('Time', fontsize = 16)
52
+ plt.ylabel(frequency + ' Demand', fontsize = 16)
53
+ ax.legend(loc='best')
54
+ plt.suptitle(frequency+' forecast', y=1)
55
+ st.write(f)
56
+
57
+ @st.cache
58
+ def load_data(file):
59
+ file_name = file.name
60
+ if file_name.endswith('.csv'):
61
+ data = pd.read_csv(file)
62
+ elif file_name.endswith('.xlsx'):
63
+ data = pd.read_excel(file)
64
+ else:
65
+ st.error("Unsupported file format. Only CSV and Excel files are supported.")
66
+ return data
67
+
68
+ def click_button():
69
+ st.session_state.clicked = True
70
+
71
+ def main():
72
+ st.title("FoodQast")
73
+
74
+ two_files = st.sidebar.checkbox("Recipe and sales on seperate files")
75
+ file = st.sidebar.file_uploader('Upload sales file', type=["csv", "xlsx", " xls"])
76
+ recipe_file = True
77
+ if two_files:
78
+ recipe_file = st.sidebar.file_uploader('Upload recipe file', type=["csv", "xlsx", " xls"])
79
+
80
+ if ('clicked' not in st.session_state) or (not file) or (not recipe_file):
81
+ st.session_state.clicked = False
82
+
83
+ if not file or not recipe_file:
84
+ st.write("Please upload a file...")
85
+
86
+ if file and recipe_file:
87
+ original_data = load_data(file)
88
+ if two_files:
89
+ recipe_data = load_data(recipe_file)
90
+ data = original_data.copy()
91
+
92
+ # Select columns
93
+ time_column='<None>'
94
+ seperate_datetime = st.sidebar.checkbox("Date and time on seperate columns")
95
+ date_column = st.sidebar.selectbox("Select date column:", ['<None>'] + [col for col in data.columns])
96
+ if seperate_datetime:
97
+ time_column = st.sidebar.selectbox("Select time column:", ['<None>'] + [col for col in data.columns])
98
+ quantity_column = st.sidebar.selectbox("Select quantity column:", ['<None>'] + [col for col in data.columns])
99
+ if two_files:
100
+ sale_column = st.sidebar.selectbox("Select sale file item ID:", ['<None>'] + [col for col in data.columns])
101
+ recipe_column = st.sidebar.selectbox("Select recipe file item ID:", ['<None>'] + [col for col in recipe_data.columns])
102
+ quantity_per_item_column = st.sidebar.selectbox("Select quantity per item column:", ['<None>'] + [col for col in recipe_data.columns])
103
+ item_column = st.sidebar.selectbox("Select menu item column (optional):", ['<None>'] + [col for col in recipe_data.columns])
104
+ else:
105
+ item_column = st.sidebar.selectbox("Select menu item column (optional):", ['<None>'] + [col for col in data.columns])
106
+
107
+ # Validation checks
108
+ if two_files and (quantity_per_item_column=='<None>' or recipe_column=='<None>' or sale_column=='<None>'):
109
+ st.sidebar.warning("Select all the required columns.")
110
+ st.session_state.clicked = False
111
+ st.stop()
112
+ if date_column=='<None>' or quantity_column=='<None>':
113
+ st.sidebar.warning("Select columns for Date and quantity.")
114
+ st.session_state.clicked = False
115
+ st.stop()
116
+
117
+ if date_column == quantity_column:
118
+ st.sidebar.warning("Date and quantity columns should be different.")
119
+ st.session_state.clicked = False
120
+ st.stop()
121
+
122
+ if item_column != '<None>' and (item_column == date_column or item_column == quantity_column):
123
+ st.sidebar.warning("The item column should be different from date and quantity columns.")
124
+ st.session_state.clicked = False
125
+ st.stop()
126
+
127
+ if date_column:
128
+ if not pd.api.types.is_datetime64_any_dtype(data[date_column]):
129
+ try:
130
+ data[date_column] = pd.to_datetime(data[date_column])
131
+ except Exception as e:
132
+ st.sidebar.error(f"{date_column} is not in datetime format.")
133
+ st.session_state.clicked = False
134
+ st.stop()
135
+
136
+ if quantity_column:
137
+ if not pd.api.types.is_numeric_dtype(data[quantity_column]):
138
+ st.sidebar.error(f"{quantity_column} is not a numeric column.")
139
+ st.session_state.clicked = False
140
+ st.stop()
141
+
142
+ # Combine date and time if in seperate columns
143
+ if time_column != '<None>':
144
+ if data[time_column].dtype == 'int64' or data[time_column].dtype == 'float64':
145
+ data[date_column] = data[date_column] + pd.to_timedelta(data[time_column], unit='H')
146
+ else:
147
+ try:
148
+ data[time_column] = pd.to_datetime(data[time_column]).dt.time
149
+ data[date_column] = data.apply(lambda x: pd.datetime.combine(x[date_column], x[time_column]), axis=1)
150
+ except Exception as e:
151
+ st.sidebar.error(f"Date or hour column is not in datetime format.")
152
+ st.session_state.clicked = False
153
+ st.stop()
154
+
155
+ if two_files:
156
+ try:
157
+ data = pd.merge(recipe_data, data, left_on=recipe_column, right_on=sale_column)
158
+ except Exception as e:
159
+ st.sidebar.warning(f"{str(e)}")
160
+ st.session_state.clicked = False
161
+ st.stop()
162
+
163
+ # Select item to forecast if there is items column
164
+ if item_column != '<None>':
165
+ # Removing items that are sold less than 70% of total days
166
+ try:
167
+ data["date_only"] = data[date_column].dt.date
168
+ df_agg = data.groupby(['date_only', item_column])[quantity_column].sum().reset_index()
169
+ menuitem_counts = df_agg[item_column].value_counts().reset_index()
170
+ menuitem_counts.columns = [item_column, 'count']
171
+ filtered_menuitems = menuitem_counts[menuitem_counts['count'] >= len(data["date_only"].unique())*0.7][item_column]
172
+ data = data[data[item_column].isin(filtered_menuitems)]
173
+
174
+ if len(data[item_column].unique()) == 0:
175
+ st.error("Make sure the right column is selected")
176
+ st.session_state.clicked = False
177
+
178
+ item = st.sidebar.selectbox("Select item to forecast:", sorted(data[item_column].unique(), key=lambda x: x.lower()))
179
+
180
+ # Keep only the chosen menu_item
181
+ data = data[data[item_column] == item]
182
+ data = data.reset_index(drop=True)
183
+ except Exception as e:
184
+ st.session_state.clicked = False
185
+ st.sidebar.warning("Make sure that the columns are in the correct format")
186
+ st.stop()
187
+
188
+ run_btn = st.sidebar.button("Run", on_click=click_button)
189
+
190
+ if st.session_state.clicked:
191
+ try:
192
+ #renaming columns
193
+ data.rename(columns={date_column: 'DOB'}, inplace=True)
194
+ data = data.sort_values(by='DOB', ascending=True)
195
+ if two_files:
196
+ data['AMOUNT'] = data[quantity_column] * data[quantity_per_item_column]
197
+ else:
198
+ data.rename(columns={quantity_column: 'AMOUNT'}, inplace=True)
199
+
200
+ st.subheader("Settings")
201
+ #Renaming and splitting training and testing
202
+ st.write("Choose an algorithm:")
203
+ algorithm = st.selectbox("", ["Algorithm 1", "Algorithm 2", "Algorithm 3"], label_visibility="collapsed")
204
+ st.write("Choose data frequency:")
205
+ frequency = st.selectbox("", ["Hourly", "Daily", "Weekly"], label_visibility="collapsed", index=1)
206
+
207
+ #frequency settings
208
+ if frequency == "Daily":
209
+ freq = "D"
210
+ elif frequency == "Hourly":
211
+ freq = "H"
212
+ else:
213
+ freq = "W"
214
+
215
+ food_df = preprocess(data, freq)
216
+
217
+ d = st.date_input("Enter training start date:", value=food_df.loc[0, 'DOB'])
218
+ training_initial_date = pd.to_datetime(d)
219
+ initial_date = food_df.loc[len(food_df['DOB'])-1, 'DOB'] - DateOffset(months=1)
220
+ d = st.date_input("Enter testing start date:", value=initial_date)
221
+ split_date = pd.to_datetime(d)
222
+ d = st.date_input("Enter testing end date:", value=food_df.loc[len(food_df['DOB'])-1, 'DOB'])
223
+ end_date = pd.to_datetime(d)
224
+
225
+ #splitting data
226
+ Training = food_df[(food_df["DOB"] >= training_initial_date) & (food_df["DOB"] < split_date)].copy()
227
+ Testing = food_df[(food_df["DOB"] >= split_date) & (food_df["DOB"] <= end_date)].copy()
228
+
229
+ #visualizing the dataset
230
+ st.subheader("1. Visualizing data")
231
+ fig_main, ax_main = plt.subplots(1, 1, figsize=(15, 5))
232
+ tmp = Training.append(Testing.iloc[0], ignore_index=True)
233
+ ax_main.plot (tmp["DOB"], tmp["AMOUNT"])
234
+ ax_main.plot (Testing["DOB"], Testing["AMOUNT"])
235
+ st.write(fig_main)
236
+
237
+ #training the data
238
+ st.subheader("2. Forecasting data")
239
+
240
+ #training using prophet
241
+ if algorithm == 'Algorithm 1':
242
+ Training = Training.rename(columns={'DOB':'ds', 'AMOUNT':'y'})
243
+ Testing = Testing.rename(columns={'DOB':'ds', 'AMOUNT':'y'})
244
+
245
+ #prophet seasonaility setup
246
+ min_date = food_df['DOB'].min()
247
+ max_date = food_df['DOB'].max()
248
+ delta = max_date - min_date
249
+
250
+ def train_prophet():
251
+ model = Prophet(
252
+ interval_width=0.95,
253
+ weekly_seasonality = True,
254
+ daily_seasonality = freq == "D",
255
+ yearly_seasonality = delta.days > 365
256
+ )
257
+ model.fit(Training)
258
+
259
+ return model
260
+
261
+ model = train_prophet()
262
+ future = model.make_future_dataframe(periods=len(Testing), freq=freq)
263
+ forecast = model.predict(future)
264
+ yhat=forecast['yhat'].to_numpy()
265
+ yhat=yhat[-len(Testing):]
266
+
267
+ draw_results(Testing['y'], yhat, len(Testing), frequency)
268
+
269
+ elif algorithm == "Algorithm 2":
270
+ food_df = food_df.set_index("DOB")
271
+ Training = Training.set_index("DOB")
272
+ Testing = Testing.set_index("DOB")
273
+
274
+ # preparing train data in format for DeepAR
275
+ training_data = ListDataset(
276
+ [{"start": Training.index[0], "target": Training.AMOUNT}],
277
+ freq = freq
278
+ )
279
+
280
+ # Test data (includes both train and test data)
281
+ test_data = ListDataset(
282
+ [{"start": food_df.index[0], "target": food_df.AMOUNT}],
283
+ freq = freq
284
+ )
285
+
286
+ def train_DeepAR():
287
+ estimator = DeepAREstimator(
288
+ num_layers= 2,
289
+ num_cells = 30,
290
+ context_length= len(Testing),
291
+ freq=freq,
292
+ prediction_length= len(Testing),
293
+ trainer=Trainer(epochs=30, learning_rate= 0.001))
294
+ predictor = estimator.train(training_data)
295
+ return predictor
296
+
297
+ predictor = train_DeepAR()
298
+ forecast_it, ts_it = make_evaluation_predictions(
299
+ dataset=test_data,
300
+ predictor=predictor
301
+ )
302
+
303
+ # Evaluate the data
304
+ forecast_it, ts_it = make_evaluation_predictions(
305
+ dataset=test_data, # test dataset
306
+ predictor=predictor # predictor
307
+ )
308
+
309
+ forecasts = list(forecast_it)
310
+ tss = list(ts_it)
311
+ forecast = forecasts[0]
312
+
313
+ forecast_mean = pd.Series(forecast.mean, index=Testing.index)
314
+ draw_results(Testing, forecast_mean, len(forecast_mean), frequency)
315
+
316
+ else:
317
+ x_train= Training['AMOUNT'].to_numpy()
318
+ x_test=Testing['AMOUNT'].to_numpy()
319
+
320
+ model = auto_arima(x_train, start_p=1, start_q=1,
321
+ test='adf',
322
+ max_p=5, max_q=5,
323
+ m=1,
324
+ d=1,
325
+ seasonal=False,
326
+ start_P=0,
327
+ D=None,
328
+ trace=True,
329
+ error_action='ignore',
330
+ suppress_warnings=True,
331
+ stepwise=True)
332
+
333
+ prediction = model.predict(n_periods=len(Testing))
334
+ draw_results(x_test, prediction, len(Testing), frequency)
335
+
336
+
337
+ st.subheader("3. Evaluation metrics")
338
+
339
+ if algorithm == 'Algorithm 1':
340
+ yhat=forecast['yhat']
341
+ eval = evaluate( Testing['y'], yhat[-len(Testing):])
342
+ evaluation = pd.DataFrame(
343
+ [[eval["MAE"], eval["MAPE"], sqrt(eval["MSE"])]],
344
+ columns = ["MAE", "MAPE", "RMSE"]
345
+ )
346
+ elif algorithm == 'Algorithm 2':
347
+ evaluator = Evaluator()
348
+ eval, _ = evaluator(iter(tss), iter(forecasts), num_series=len(test_data))
349
+ mae = np.mean(np.abs(Testing["AMOUNT"] - forecast.mean))
350
+ evaluation = pd.DataFrame(
351
+ [[mae, eval["MAPE"], sqrt(eval["MSE"])]],
352
+ columns = ["MAE", "MAPE", "RMSE"]
353
+ )
354
+ else:
355
+ eval = evaluate( x_test, prediction)
356
+ evaluation = pd.DataFrame(
357
+ [[eval["MAE"], eval["MAPE"], sqrt(eval["MSE"])]],
358
+ columns = ["MAE", "MAPE", "RMSE"]
359
+ )
360
+
361
+
362
+ # CSS to inject contained in a string
363
+ hide_table_row_index = """
364
+ <style>
365
+ thead tr th:first-child {display:none}
366
+ tbody th {display:none}
367
+ </style>
368
+ """
369
+
370
+ # Inject CSS with Markdown
371
+ st.markdown(hide_table_row_index, unsafe_allow_html=True)
372
+
373
+ st.table(evaluation)
374
+
375
+ except Exception as e:
376
+ st.session_state.clicked = False
377
+ st.error(f"An error occurred: {e}")
378
+
379
+ else:
380
+ st.write("Select the required columns and click run...")
381
+
382
+ if __name__ == '__main__':
383
+ main()