lstm / app.py
nalinrajendran's picture
Upload app.py
135a621
import pandas as pd
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import keras
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error as MAE
pwd = os.getcwd()
filepath = os.path.join(pwd,r"DATA/try_data.csv")
df = pd.read_csv(filepath)
df1 = df.reset_index()['cases']
scaler = MinMaxScaler(feature_range=(0,1))
df1 = scaler.fit_transform(np.array(df1).reshape(-1,1))
training_size = int(len(df1)*0.8)
test_size= len(df1)-training_size
train_data,test_data = df1[0:training_size,:],df1[training_size:len(df1),:1]
def create_dataset (dataset,time_step=1):
dataX, dataY = [], []
for i in range(len(dataset)-time_step-1):
a = dataset[i:(i+time_step),0]
dataX.append(a)
dataY.append(dataset[i+time_step, 0])
return np.array(dataX), np.array(dataY)
time_step = 2
X_train, y_train = create_dataset(train_data, time_step)
X_test, y_test = create_dataset(test_data, time_step)
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
model = Sequential()
model.add(LSTM(11,return_sequences=True, input_shape=(2,1)))
model.add(LSTM(11,return_sequences=True))
model.add(LSTM(11))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer = "adam")
lin_model=model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs=400, batch_size=38, verbose=1)
train_predict=model.predict(X_train)
test_predict=model.predict(X_test)
look_back=2
trainPredictPlot = np.empty_like(df1)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict
# shift test predictions for plotting
testPredictPlot = np.empty_like(df1)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict
# plot baseline and predictions
plt.figure(figsize = (15,6))
plt.plot(scaler.inverse_transform(df1),'r',label='Original Data')
plt.plot(trainPredictPlot,'g',label='Train Data')
plt.plot(testPredictPlot,'b',label='Test Data')
plt.xlabel('Months')
plt.ylabel('Cases')
plt.show()
import gradio as gr
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def plot(df):
plt.plot(scaler.inverse_transform(df1),'r',label='Original Data')
plt.title("Original data that is used for analysis")
plt.savefig("original_data.png")
plt.plot(trainPredictPlot,'g',label='Train Data')
plt.title("Predicting the Trained data from the original data")
plt.savefig("train_prediction.png")
plt.plot(testPredictPlot,'b',label='Test Data')
plt.title("Predicting the case coutn of the year 2020 and 2021")
plt.savefig("test_prediction.png")
plots = ["Case_count.png","Rainfall_pattern.png","original_data.png","train_prediction.png", "test_prediction.png"]
return plots
inputs = [gr.Dataframe(label="Dengue Data")]
outputs = [gr.Gallery(label="Inference from the data").style(grid=(5,1))]
description = "We are given with the dataset of dengue cases with respect to the state Kerala with a span ranging from the year 2011 to 2021.The goal is to predict the cases in a monthly fashion, for the upcoming years.The bar graph indicated the year-wise dengue case count.The Time series plot indicates the rainfall pattern across the period 2011-2021.The red part of the graph is the input data that we have .The green part of the graph is the data with which we trained our model.The blue part of the graph indicates the predicted output(test data) against the red part which is the original data"
gr.Interface(plot, inputs=inputs, outputs=outputs, title="Dengue Cases Prediction Dashboard",description=description,allow_flagging="never").launch()