Spaces:
Sleeping
Sleeping
Fixed error
Browse files
app.py
CHANGED
@@ -1,20 +1,30 @@
|
|
1 |
-
import
|
2 |
import torch
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
import seaborn as sns
|
6 |
import io
|
|
|
7 |
import pickle
|
8 |
import torch.nn as nn
|
9 |
from sklearn.preprocessing import MinMaxScaler
|
|
|
10 |
|
|
|
|
|
|
|
|
|
11 |
INPUT_SIZE = 1
|
12 |
HIDDEN_LAYER_SIZE = 100
|
13 |
OUTPUT_SIZE = 1
|
14 |
|
|
|
|
|
15 |
scaler = MinMaxScaler(feature_range=(-1, 1))
|
|
|
|
|
16 |
seq_length = 4
|
17 |
|
|
|
18 |
class LSTM(nn.Module):
|
19 |
def __init__(self, input_size=INPUT_SIZE, hidden_layer_size=HIDDEN_LAYER_SIZE, output_size=OUTPUT_SIZE):
|
20 |
super(LSTM, self).__init__()
|
@@ -29,21 +39,24 @@ class LSTM(nn.Module):
|
|
29 |
predictions = self.linear(lstm_out.view(len(input_seq), -1))
|
30 |
return predictions[-1]
|
31 |
|
32 |
-
|
33 |
-
model = pickle.load(f)
|
34 |
-
|
35 |
def prepare_custom_input(last_values, seq_length, scaler):
|
36 |
last_values_normalized = scaler.transform(np.array(last_values).reshape(-1, 1))
|
37 |
input_seq = torch.from_numpy(last_values_normalized).float()
|
38 |
return input_seq.view(-1)
|
39 |
|
40 |
-
model
|
|
|
|
|
|
|
41 |
|
42 |
-
|
43 |
-
|
|
|
44 |
|
45 |
custom_input = prepare_custom_input(last_four_weeks, seq_length, scaler)
|
46 |
|
|
|
47 |
with torch.no_grad():
|
48 |
model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
|
49 |
torch.zeros(1, 1, model.hidden_layer_size))
|
@@ -53,30 +66,41 @@ def predict_and_plot(week1, week2, week3, week4):
|
|
53 |
predicted_value = predicted_kilometers[0][0]
|
54 |
|
55 |
weeks = ['Week -4', 'Week -3', 'Week -2', 'Week -1', 'Predicted Week']
|
56 |
-
actual_values =
|
57 |
-
|
58 |
-
plt.figure(figsize=(
|
59 |
-
|
60 |
plt.axvline(x='Predicted Week', color='red', linestyle='--', label='Predicted Week')
|
61 |
plt.title('Total Kilometers for Last 4 Weeks and Prediction')
|
62 |
plt.xlabel('Weeks')
|
63 |
plt.ylabel('Total Kilometers')
|
64 |
-
plt.
|
|
|
|
|
65 |
plt.legend()
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
import torch
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
|
|
5 |
import io
|
6 |
+
import base64
|
7 |
import pickle
|
8 |
import torch.nn as nn
|
9 |
from sklearn.preprocessing import MinMaxScaler
|
10 |
+
import pandas as pd
|
11 |
|
12 |
+
# Load your dataset
|
13 |
+
df_weekly_km = pd.read_csv('Weekly_Km.csv')
|
14 |
+
|
15 |
+
# Model parameters
|
16 |
INPUT_SIZE = 1
|
17 |
HIDDEN_LAYER_SIZE = 100
|
18 |
OUTPUT_SIZE = 1
|
19 |
|
20 |
+
# Normalize the data
|
21 |
+
data = df_weekly_km['Total Kilometers'].values.astype(float)
|
22 |
scaler = MinMaxScaler(feature_range=(-1, 1))
|
23 |
+
data_normalized = scaler.fit_transform(data.reshape(-1, 1))
|
24 |
+
|
25 |
seq_length = 4
|
26 |
|
27 |
+
# Define LSTM model
|
28 |
class LSTM(nn.Module):
|
29 |
def __init__(self, input_size=INPUT_SIZE, hidden_layer_size=HIDDEN_LAYER_SIZE, output_size=OUTPUT_SIZE):
|
30 |
super(LSTM, self).__init__()
|
|
|
39 |
predictions = self.linear(lstm_out.view(len(input_seq), -1))
|
40 |
return predictions[-1]
|
41 |
|
42 |
+
# Function to prepare input
|
|
|
|
|
43 |
def prepare_custom_input(last_values, seq_length, scaler):
|
44 |
last_values_normalized = scaler.transform(np.array(last_values).reshape(-1, 1))
|
45 |
input_seq = torch.from_numpy(last_values_normalized).float()
|
46 |
return input_seq.view(-1)
|
47 |
|
48 |
+
# Load the trained model
|
49 |
+
model_path = 'lstm_model.pth'
|
50 |
+
model = LSTM(INPUT_SIZE, HIDDEN_LAYER_SIZE, OUTPUT_SIZE)
|
51 |
+
model.load_state_dict(torch.load(model_path))
|
52 |
|
53 |
+
# Prediction and plot function
|
54 |
+
def predict_and_plot(week4, week3, week2, week1):
|
55 |
+
last_four_weeks = [week4, week3, week2, week1]
|
56 |
|
57 |
custom_input = prepare_custom_input(last_four_weeks, seq_length, scaler)
|
58 |
|
59 |
+
model.eval()
|
60 |
with torch.no_grad():
|
61 |
model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
|
62 |
torch.zeros(1, 1, model.hidden_layer_size))
|
|
|
66 |
predicted_value = predicted_kilometers[0][0]
|
67 |
|
68 |
weeks = ['Week -4', 'Week -3', 'Week -2', 'Week -1', 'Predicted Week']
|
69 |
+
actual_values = last_four_weeks + [predicted_value]
|
70 |
+
|
71 |
+
plt.figure(figsize=(10, 6))
|
72 |
+
plt.plot(weeks, actual_values, marker='o', label='Total Kilometers')
|
73 |
plt.axvline(x='Predicted Week', color='red', linestyle='--', label='Predicted Week')
|
74 |
plt.title('Total Kilometers for Last 4 Weeks and Prediction')
|
75 |
plt.xlabel('Weeks')
|
76 |
plt.ylabel('Total Kilometers')
|
77 |
+
plt.ylim(bottom=0)
|
78 |
+
plt.grid()
|
79 |
+
plt.tight_layout()
|
80 |
plt.legend()
|
81 |
|
82 |
+
# Saving the plot to a BytesIO object
|
83 |
+
buf = io.BytesIO()
|
84 |
+
plt.savefig(buf, format='png')
|
85 |
+
buf.seek(0)
|
86 |
+
plt.close()
|
87 |
+
|
88 |
+
# Converting to base64 for Gradio
|
89 |
+
img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
|
90 |
+
img_tag = f'<img src="data:image/png;base64,{img_base64}"/>'
|
91 |
+
|
92 |
+
return f"{predicted_value:.2f}", img_tag
|
93 |
+
|
94 |
+
# Gradio interface
|
95 |
+
inputs = [gr.Number(label='Week -4'),
|
96 |
+
gr.Number(label='Week -3'),
|
97 |
+
gr.Number(label='Week -2'),
|
98 |
+
gr.Number(label='Week -1')]
|
99 |
+
outputs = [gr.Textbox(label='Predicted Week'),
|
100 |
+
gr.HTML(label='Plot')]
|
101 |
+
|
102 |
+
gr.Interface(fn=predict_and_plot,
|
103 |
+
inputs=inputs,
|
104 |
+
outputs=outputs,
|
105 |
+
title="LSTM Model Prediction",
|
106 |
+
description="Enter the total kilometers for the last 4 weeks to get the prediction for the next week along with a plot.").launch(share=True)
|