Bhuvanesh24 commited on
Commit ·
4e188a6
1
Parent(s): 8abf9b3
Added app.py
Browse files- app.py +40 -0
- requirements.txt +7 -0
- src/data.py +99 -0
- src/model.py +60 -0
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
import numpy as np
|
| 6 |
+
from src.model import LSTM
|
| 7 |
+
|
| 8 |
+
# Initialize FastAPI app
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# Device setup
|
| 12 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 13 |
+
|
| 14 |
+
# Ensure the model file is available in the Hugging Face Space's environment
|
| 15 |
+
model_path = './water_forecast_2.pth'
|
| 16 |
+
if not os.path.exists(model_path):
|
| 17 |
+
raise FileNotFoundError(f"Model file '{model_path}' not found.")
|
| 18 |
+
|
| 19 |
+
# Load the model
|
| 20 |
+
model = LSTM(input_size=8, lstm_layer_sizes=[128,128,128], output_size=3).to(device)
|
| 21 |
+
|
| 22 |
+
print("Loading model...")
|
| 23 |
+
model.load_state_dict(torch.load(model_path, map_location=device))
|
| 24 |
+
print("Model loaded successfully")
|
| 25 |
+
model.eval()
|
| 26 |
+
|
| 27 |
+
class ForecastRequest(BaseModel):
|
| 28 |
+
state_idx: int
|
| 29 |
+
target_year: int
|
| 30 |
+
structured_data: dict
|
| 31 |
+
|
| 32 |
+
@app.post("/predict")
|
| 33 |
+
async def predict_usage(data: ForecastRequest):
|
| 34 |
+
structured_data = data.structured_data
|
| 35 |
+
tensor_data = torch.tensor(np.array(list(structured_data.values())), dtype=torch.float32).to(device)
|
| 36 |
+
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
outputs = model(tensor_data)
|
| 39 |
+
|
| 40 |
+
return {"prediction": outputs.tolist()}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
fastapi
|
| 3 |
+
pydantic
|
| 4 |
+
numpy
|
| 5 |
+
pandas
|
| 6 |
+
scikit-learn
|
| 7 |
+
uvicorn
|
src/data.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from sklearn.preprocessing import StandardScaler
|
| 7 |
+
|
| 8 |
+
class WaterDataset(Dataset):
|
| 9 |
+
def __init__(self, sequence_length=5, transform=None):
|
| 10 |
+
"""
|
| 11 |
+
Initializes the dataset by loading LUC, population, and usage data, merging them
|
| 12 |
+
based on year and state, and creating sequences of data for training.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
sequence_length (int): The length of each data sequence for time series forecasting.
|
| 16 |
+
transform (callable, optional): Optional transform to be applied on a sample.
|
| 17 |
+
"""
|
| 18 |
+
self.sequence_length = sequence_length
|
| 19 |
+
self.luc = pd.read_csv('data/luc.csv')
|
| 20 |
+
self.population = pd.read_csv('data/population.csv')
|
| 21 |
+
self.usage = pd.read_csv('data/usage.csv')
|
| 22 |
+
self.transform = transform
|
| 23 |
+
|
| 24 |
+
self.years = sorted(set(self.usage['Year']))
|
| 25 |
+
self.states = sorted(set(self.usage['State']))
|
| 26 |
+
self.all_years = sorted(set(self.population['Year']))
|
| 27 |
+
|
| 28 |
+
self.df = self.merge_data()
|
| 29 |
+
self.x, self.y = self.create_sequence()
|
| 30 |
+
|
| 31 |
+
self.scaler = StandardScaler()
|
| 32 |
+
self.x = self.scaler.fit_transform(self.x.reshape(-1, self.x.shape[-1])).reshape(self.x.shape)
|
| 33 |
+
|
| 34 |
+
def merge_data(self):
|
| 35 |
+
"""
|
| 36 |
+
Merges land use classification (LUC) and population data based on year and state.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
pd.DataFrame: A DataFrame with merged data on population, urban/rural breakdown,
|
| 40 |
+
and LUC attributes for each year and state.
|
| 41 |
+
"""
|
| 42 |
+
merged_data = []
|
| 43 |
+
|
| 44 |
+
for year, state in [(y, s) for y in self.all_years for s in self.states]:
|
| 45 |
+
population_data = self.population[(self.population['Year'] == year)]
|
| 46 |
+
luc_data = self.luc[(self.luc['Year'] == year) & (self.luc['State'] == state)]
|
| 47 |
+
|
| 48 |
+
if not population_data.empty and not luc_data.empty:
|
| 49 |
+
combined_data = {
|
| 50 |
+
'year': year,
|
| 51 |
+
'state': state,
|
| 52 |
+
'population': population_data['Population'].values[0],
|
| 53 |
+
'urban_population': population_data['Urban Population'].values[0],
|
| 54 |
+
'rural_population': population_data['Rural Population'].values[0],
|
| 55 |
+
'forest': luc_data['Forest'].values[0],
|
| 56 |
+
'barren': luc_data['Barren'].values[0],
|
| 57 |
+
'others': luc_data['Others'].values[0],
|
| 58 |
+
'fallow': luc_data['Fallow'].values[0],
|
| 59 |
+
'cropped': luc_data['Cropped'].values[0]
|
| 60 |
+
}
|
| 61 |
+
merged_data.append(combined_data)
|
| 62 |
+
|
| 63 |
+
return pd.DataFrame(merged_data)
|
| 64 |
+
|
| 65 |
+
def create_sequence(self):
|
| 66 |
+
"""
|
| 67 |
+
Creates sequences of input data and their corresponding labels for training.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
tuple: Two numpy arrays, one for data sequences and one for label sequences.
|
| 71 |
+
"""
|
| 72 |
+
data_sequences, label_sequences = [], []
|
| 73 |
+
missing_sequences = {state: [] for state in self.states}
|
| 74 |
+
|
| 75 |
+
for state in self.states:
|
| 76 |
+
state_data = self.df[self.df['state'] == state].sort_values('year')
|
| 77 |
+
usage_state_data = self.usage[self.usage['State'] == state]
|
| 78 |
+
|
| 79 |
+
for i in range(len(state_data) - self.sequence_length):
|
| 80 |
+
sequence = state_data.iloc[i:i + self.sequence_length]
|
| 81 |
+
year = sequence['year'].values[-1] + 1
|
| 82 |
+
|
| 83 |
+
usage_label = usage_state_data[usage_state_data['Year'] == year]
|
| 84 |
+
|
| 85 |
+
if len(sequence) == self.sequence_length and not usage_label.empty:
|
| 86 |
+
data_sequences.append(sequence[['population', 'urban_population', 'rural_population',
|
| 87 |
+
'forest', 'barren', 'others', 'fallow', 'cropped']].values.astype(np.float32))
|
| 88 |
+
label_sequences.append(usage_label[['Domestic', 'Industrial', 'Irrigation']].values[0].astype(np.float32))
|
| 89 |
+
else:
|
| 90 |
+
missing_sequences[state].append(year)
|
| 91 |
+
|
| 92 |
+
return np.array(data_sequences), np.array(label_sequences)
|
| 93 |
+
|
| 94 |
+
def __len__(self):
|
| 95 |
+
return len(self.x)
|
| 96 |
+
|
| 97 |
+
def __getitem__(self, index):
|
| 98 |
+
return (torch.tensor(self.x[index], dtype=torch.float32),
|
| 99 |
+
torch.tensor(self.y[index], dtype=torch.float32))
|
src/model.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
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 |
+
|
| 20 |
+
out, (hn_1, cn_1) = self.lstm_layer_1(x)
|
| 21 |
+
out, (hn_2, cn_2) = self.lstm_layer_2(out)
|
| 22 |
+
out, (hn_3, cn_3) = self.lstm_layer_3(out)
|
| 23 |
+
|
| 24 |
+
out = hn_3[-1]
|
| 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))
|
| 50 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 51 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 52 |
+
pe = pe.unsqueeze(0).transpose(0, 1)
|
| 53 |
+
self.register_buffer('pe', pe)
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
return x + self.pe[:x.size(0), :]
|
| 57 |
+
|
| 58 |
+
class Transformer(nn.Module):
|
| 59 |
+
def __init__(self):
|
| 60 |
+
super(Transformer,self).__init__()
|