Bhuvanesh24 commited on
Commit
5bf6359
·
1 Parent(s): 45ca800

Upgraded model

Browse files
Files changed (3) hide show
  1. andhra_forecast.pt +3 -0
  2. app.py +16 -19
  3. src/model.py +77 -15
andhra_forecast.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:199336d9e211a73d273cc588765bf1dbbfb42451ddc28c5e49b133c42dd11d14
3
+ size 258558
app.py CHANGED
@@ -1,42 +1,39 @@
1
  import torch
2
  import gradio as gr
3
  import numpy as np
4
- from src.model import LSTM # Adjust to your model path
5
 
6
  # Load the model
7
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
8
- model_path = "./water_forecast_2.pth" # Path to the model file
9
- model = LSTM(input_size=8, lstm_layer_sizes=[128, 128, 128], output_size=3).to(device)
10
- model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
11
  model.eval()
12
-
13
  # Define the prediction function
14
  def predict_water_usage(state_idx, target_year, structured_data):
15
- # structured_data is now a dictionary directly, no need to parse it
16
- if len(structured_data) < 5:
17
- return {"error": "Structured data must include 5 years of data for the specified state."}
18
 
19
  # Convert structured data for model input (extract values for model)
20
  data_values = [list(values) for values in structured_data.values()]
 
21
 
22
 
23
  # Ensure the data has the right shape for the model
24
- if len(data_values) != 5: # Check if there are exactly 5 years of data
25
- return {"error": "Structured data should have 5 years of data."}
26
 
27
- # Check if data_values contains only numeric data
28
- for year_data in data_values:
29
- if not all(isinstance(val, (int, float)) for val in year_data):
30
- return {"error": "All values in structured data should be numeric."}
31
 
32
- # Convert data_values to tensor
33
- tensor_data = torch.tensor(data_values, dtype=torch.float32).to(device)
34
 
35
- # Get model output
 
 
36
  with torch.no_grad():
37
- output = model(tensor_data)
 
 
38
 
39
- return {"prediction": output.tolist()}
40
 
41
  # Configure Gradio interface
42
  inputs = [
 
1
  import torch
2
  import gradio as gr
3
  import numpy as np
4
+ from src.model import LSTM
5
 
6
  # Load the model
7
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
8
+ model_path = "./andhra_forecast.pt"
9
+ model = torch.load(model_path, map_location=device)
 
10
  model.eval()
 
11
  # Define the prediction function
12
  def predict_water_usage(state_idx, target_year, structured_data):
13
+
14
+ if len(structured_data) < 3:
15
+ return {"error": "Structured data must include 3 years of data for the specified state."}
16
 
17
  # Convert structured data for model input (extract values for model)
18
  data_values = [list(values) for values in structured_data.values()]
19
+ inputs = [[np.log(value + 1) for value in sublist] for sublist in data_values]
20
 
21
 
22
  # Ensure the data has the right shape for the model
23
+ if len(inputs) != 3:
24
+ return {"error": "Structured data should have 3 years of data."}
25
 
 
 
 
 
26
 
 
 
27
 
28
+ inputs = torch.tensor(inputs, dtype=torch.float32)
29
+ predictions = model(inputs).cpu().detach().numpy()
30
+
31
  with torch.no_grad():
32
+ output = [np.exp(prediction) - 1 for prediction in predictions]
33
+ return output
34
+ # Get model output
35
 
36
+ return {"error" : "Does not contain the torch model grad"}
37
 
38
  # Configure Gradio interface
39
  inputs = [
src/model.py CHANGED
@@ -4,16 +4,19 @@ import math
4
  #from transformers import AutoModelForCausalLM, AutoTokenizer
5
 
6
  class LSTM(nn.Module):
7
- def __init__(self, input_size, lstm_layer_sizes, output_size):
8
- super(LSTM, self).__init__()
9
 
10
  self.input_size = input_size
 
11
 
12
  self.lstm_layer_1 = nn.LSTM(input_size, lstm_layer_sizes[0], batch_first=True)
13
  self.lstm_layer_2 = nn.LSTM(lstm_layer_sizes[0], lstm_layer_sizes[1], batch_first=True)
14
  self.lstm_layer_3 = nn.LSTM(lstm_layer_sizes[1], lstm_layer_sizes[2], batch_first=True)
15
 
16
- self.fc = nn.Linear(lstm_layer_sizes[2], output_size)
 
 
17
 
18
  def forward(self, x):
19
 
@@ -25,25 +28,84 @@ class LSTM(nn.Module):
25
  out = self.fc(out)
26
  return out
27
 
28
-
 
 
 
 
 
 
 
 
 
 
29
  class Linear(nn.Module):
30
- def __init__(self,input_size,output_size):
31
- super(Linear,self).__init__()
32
 
33
- self.relu =nn.relu()
34
- self.input = nn.Linear(input_size,1024)
35
- self.fc = nn.Linear(1024,256)
36
- self.output = nn.Linear(256,output_size)
 
 
 
 
37
 
38
  def forward(self,x):
39
  out = self.relu(self.input(x))
40
  out = self.relu(self.fc(out))
41
  out = self.relu(self.output(out))
42
- return out[:, -1, :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  class PositionalEncoding(nn.Module):
45
- def __init__(self, dim, max_len=300):
46
- super(PositionalEncoding, self).__init__()
47
  pe = torch.zeros(max_len, dim)
48
  position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
49
  div_term = torch.exp(torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim))
@@ -56,5 +118,5 @@ class PositionalEncoding(nn.Module):
56
  return x + self.pe[:x.size(0), :]
57
 
58
  class Transformer(nn.Module):
59
- def __init__(self):
60
- super(Transformer,self).__init__()
 
4
  #from transformers import AutoModelForCausalLM, AutoTokenizer
5
 
6
  class LSTM(nn.Module):
7
+ def _init_(self, input_size, lstm_layer_sizes,linear_layer_size, output_size):
8
+ super(LSTM, self)._init_()
9
 
10
  self.input_size = input_size
11
+ self.linear_layer_size = linear_layer_size
12
 
13
  self.lstm_layer_1 = nn.LSTM(input_size, lstm_layer_sizes[0], batch_first=True)
14
  self.lstm_layer_2 = nn.LSTM(lstm_layer_sizes[0], lstm_layer_sizes[1], batch_first=True)
15
  self.lstm_layer_3 = nn.LSTM(lstm_layer_sizes[1], lstm_layer_sizes[2], batch_first=True)
16
 
17
+ self.fc = Linear(lstm_layer_sizes[2], self.linear_layer_size,output_size)
18
+
19
+ self.apply(self.initialize_weights)
20
 
21
  def forward(self, x):
22
 
 
28
  out = self.fc(out)
29
  return out
30
 
31
+ def initialize_weights(self, layer):
32
+ if isinstance(layer, nn.Linear):
33
+ nn.init.xavier_uniform_(layer.weight)
34
+ nn.init.zeros_(layer.bias)
35
+ elif isinstance(layer, nn.LSTM):
36
+ for name, param in layer.named_parameters():
37
+ if 'weight' in name:
38
+ nn.init.xavier_uniform_(param.data)
39
+ elif 'bias' in name:
40
+ nn.init.zeros_(param.data)
41
+
42
  class Linear(nn.Module):
43
+ def _init_(self,input_size,hidden_sizes,output_size):
44
+ super(Linear,self)._init_()
45
 
46
+ self.relu =nn.ReLU()
47
+ self.sigmoid =nn.Sigmoid()
48
+ self.tanh = nn.Tanh()
49
+ self.input = nn.Linear(input_size,hidden_sizes[0])
50
+ self.fc = nn.Linear(hidden_sizes[0],hidden_sizes[1])
51
+ self.output = nn.Linear(hidden_sizes[1],output_size)
52
+
53
+ self.apply(self.initialize_weights)
54
 
55
  def forward(self,x):
56
  out = self.relu(self.input(x))
57
  out = self.relu(self.fc(out))
58
  out = self.relu(self.output(out))
59
+ return out
60
+
61
+ def initialize_weights(self, layer):
62
+ if isinstance(layer, nn.Linear):
63
+ nn.init.xavier_uniform_(layer.weight)
64
+ nn.init.zeros_(layer.bias)
65
+
66
+ class LUCLSTM(nn.Module):
67
+ def _init_(self, input_size, lstm_layer_sizes, output_size):
68
+ super(LUCLSTM, self)._init_()
69
+
70
+ self.input_size = input_size
71
+
72
+ self.lstm_layer_1 = nn.LSTM(input_size, lstm_layer_sizes[0], batch_first=True)
73
+ self.lstm_layer_2 = nn.LSTM(lstm_layer_sizes[0], lstm_layer_sizes[1], batch_first=True)
74
+ self.lstm_layer_3 = nn.LSTM(lstm_layer_sizes[1], lstm_layer_sizes[2], batch_first=True)
75
+
76
+ self.fc = nn.Linear(lstm_layer_sizes[2],64)
77
+ self.fc2 = nn.Linear(64,output_size)
78
+ self.tanh = nn.Tanh()
79
+ self.relu =nn.ReLU()
80
+
81
+ self.apply(self.initialize_weights)
82
+
83
+ def forward(self, x):
84
+
85
+ out, (hn_1, cn_1) = self.lstm_layer_1(x)
86
+ out, (hn_2, cn_2) = self.lstm_layer_2(out)
87
+ out, (hn_3, cn_3) = self.lstm_layer_3(out)
88
+
89
+ out = hn_3[-1]
90
+ out = self.tanh(self.fc(out))
91
+ out = self.fc2(out)
92
+ return out
93
+
94
+ def initialize_weights(self, layer):
95
+ if isinstance(layer, nn.Linear):
96
+ nn.init.xavier_uniform_(layer.weight)
97
+ nn.init.zeros_(layer.bias)
98
+ elif isinstance(layer, nn.LSTM):
99
+ for name, param in layer.named_parameters():
100
+ if 'weight' in name:
101
+ nn.init.xavier_uniform_(param.data)
102
+ elif 'bias' in name:
103
+ nn.init.zeros_(param.data)
104
+
105
 
106
  class PositionalEncoding(nn.Module):
107
+ def _init_(self, dim, max_len=300):
108
+ super(PositionalEncoding, self)._init_()
109
  pe = torch.zeros(max_len, dim)
110
  position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
111
  div_term = torch.exp(torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim))
 
118
  return x + self.pe[:x.size(0), :]
119
 
120
  class Transformer(nn.Module):
121
+ def _init_(self):
122
+ super(Transformer,self)._init_()