Capebm commited on
Commit
8bee5ba
·
verified ·
1 Parent(s): 048c58f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -15
app.py CHANGED
@@ -1,25 +1,49 @@
1
  import pandas as pd
2
  import numpy as np
3
  import gradio as gr
4
- from statsmodels.tsa.holtwinters import ExponentialSmoothing
5
- import webbrowser
6
- import threading
7
 
8
  # Load the dataset
9
- file_path = 'Volumes_processed.xlsx' # Make sure to upload this file to the space as well
10
  data = pd.read_excel(file_path)
11
 
12
  # Transpose the data to have months as rows
13
  data_transposed = data.set_index('Processos').T
14
 
15
- # Function to forecast future values for each process using Holt-Winters
16
- def forecast_process(data, process_name, n_future, seed=42):
17
- np.random.seed(seed) # Set random seed for reproducibility
 
 
 
 
 
 
 
 
 
18
  process_data = data[process_name].dropna()
19
- model = ExponentialSmoothing(process_data, seasonal='add', seasonal_periods=12)
20
- fit_model = model.fit()
21
- forecasted_values = fit_model.forecast(steps=n_future)
22
- return forecasted_values
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # Gradio function to get forecast for a given month and process
25
  def get_forecast(month, processes, n_months):
@@ -32,9 +56,17 @@ def get_forecast(month, processes, n_months):
32
  results = {}
33
  forecasted_month_names = pd.date_range(start=f'2024-{month_num:02d}-01', periods=n_months, freq='M').strftime("%b")
34
  results["Mês"] = forecasted_month_names
 
 
 
 
35
  for process in processes:
36
- forecast_values = forecast_process(data_transposed, process, n_months)
37
- results[process] = forecast_values.values
 
 
 
 
38
  forecast_df = pd.DataFrame(results)
39
  return forecast_df
40
 
@@ -52,7 +84,7 @@ default_processes = list(data['Processos'].unique())
52
  def forecast_interface(month=default_month_name, process=default_processes, n_months=9):
53
  return get_forecast(month, process, n_months)
54
 
55
- # Gradio UI
56
  css = """
57
  body {
58
  background-color: black;
@@ -61,7 +93,7 @@ body {
61
  """
62
 
63
  with gr.Blocks(css=css) as iface:
64
- gr.Markdown("## BCTT: Prever Processos com Holt Winters")
65
 
66
  month = gr.Dropdown(choices=list(month_map_reverse.values()), value=default_month_name, label="Mês de Inicio da Previsão")
67
  process = gr.CheckboxGroup(choices=default_processes, value=default_processes, label="Processos")
 
1
  import pandas as pd
2
  import numpy as np
3
  import gradio as gr
4
+ from sklearn.ensemble import RandomForestRegressor
5
+ from sklearn.model_selection import train_test_split
 
6
 
7
  # Load the dataset
8
+ file_path = 'Volumes_processed.xlsx' # This file should be uploaded to the Hugging Face Space
9
  data = pd.read_excel(file_path)
10
 
11
  # Transpose the data to have months as rows
12
  data_transposed = data.set_index('Processos').T
13
 
14
+ # Prepare data for training
15
+ def create_lagged_features(data, lag=12):
16
+ df = pd.DataFrame(data)
17
+ columns = [df.shift(i) for i in range(1, lag+1)]
18
+ columns.append(df)
19
+ df = pd.concat(columns, axis=1)
20
+ df.columns = [f'lag_{i}' for i in range(lag, 0, -1)] + ['target']
21
+ df.dropna(inplace=True)
22
+ return df
23
+
24
+ # Function to forecast future values for each process
25
+ def forecast_process_ml(data, process_name, n_future, random_state=42):
26
  process_data = data[process_name].dropna()
27
+ lagged_data = create_lagged_features(process_data)
28
+
29
+ X = lagged_data.drop('target', axis=1)
30
+ y = lagged_data['target']
31
+
32
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state)
33
+
34
+ model = RandomForestRegressor(random_state=random_state)
35
+ model.fit(X_train, y_train)
36
+
37
+ future_lags = X.values[-1].tolist()
38
+ forecasts = []
39
+
40
+ for _ in range(n_future):
41
+ future_lag_df = pd.DataFrame([future_lags], columns=X.columns)
42
+ forecast = model.predict(future_lag_df)[0]
43
+ forecasts.append(forecast)
44
+ future_lags = future_lags[1:] + [forecast]
45
+
46
+ return forecasts
47
 
48
  # Gradio function to get forecast for a given month and process
49
  def get_forecast(month, processes, n_months):
 
56
  results = {}
57
  forecasted_month_names = pd.date_range(start=f'2024-{month_num:02d}-01', periods=n_months, freq='M').strftime("%b")
58
  results["Mês"] = forecasted_month_names
59
+
60
+ # Identify last month with data
61
+ last_data_month = data_transposed.index.max()
62
+
63
  for process in processes:
64
+ if last_data_month < pd.Timestamp.now():
65
+ forecast_values = forecast_process_ml(data_transposed, process, n_months)
66
+ results[process] = forecast_values
67
+ else:
68
+ results[process] = ["N/A"] * n_months
69
+
70
  forecast_df = pd.DataFrame(results)
71
  return forecast_df
72
 
 
84
  def forecast_interface(month=default_month_name, process=default_processes, n_months=9):
85
  return get_forecast(month, process, n_months)
86
 
87
+ # Gradio UI with CSS for black background
88
  css = """
89
  body {
90
  background-color: black;
 
93
  """
94
 
95
  with gr.Blocks(css=css) as iface:
96
+ gr.Markdown("## BCTT: Prever Processos com Random Forest")
97
 
98
  month = gr.Dropdown(choices=list(month_map_reverse.values()), value=default_month_name, label="Mês de Inicio da Previsão")
99
  process = gr.CheckboxGroup(choices=default_processes, value=default_processes, label="Processos")