# -*- coding: utf-8 -*-
"""LSTM.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1DkofoY-LKqsX-GIxOiVcEof43vd-9J15
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from google.colab import files
uploaded = files.upload()
import io
Features = pd.read_csv(io.BytesIO(uploaded['Featuredata.csv']))

from google.colab import files
uploaded = files.upload()
import io
KP = pd.read_csv(io.BytesIO(uploaded['KPdata.csv']))

df = pd.concat([KP, Features], axis=1)
df.head(30)

df = df.drop(['year','day','hr','min','sec','Date'],axis=1)

df = df[df['Np'].notna()]

df #

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
	n_vars = 1 if type(data) is list else data.shape[1]
	df = pd.DataFrame(data)
	cols, names = list(), list()
	# input sequence (t-n, ... t-1)
	for i in range(n_in, 0, -1):
		cols.append(df.shift(i))
		names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
	# forecast sequence (t, t+1, ... t+n)
	for i in range(0, n_out):
		cols.append(df.shift(-i))
		if i == 0:
			names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
		else:
			names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
	# put it all together
	agg = pd.concat(cols, axis=1)
	agg.columns = names
	# drop rows with NaN values
	if dropnan:
		agg.dropna(inplace=True)
	return agg

df = df.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(df)
# frame as supervised learning
n_lags = 16
n_features = 30
# frame as supervised learning
reframed = series_to_supervised(scaled, n_lags, 1)
values = reframed.values
n_train_size = 1300
train = values[:n_train_size, :]
test = values[n_train_size:, :]
# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

model = Sequential()

model.add(LSTM(units=29, return_sequences= True, input_shape=(train_X.shape[1],train_X.shape[2])))
model.add(LSTM(units=29, return_sequences=True))
model.add(LSTM(units=29))
model.add(Dense(units=1))

model.compile(optimizer='adam', loss='mean_squared_error')

model.fit(train_X, train_y, epochs=50 )

testP = model.predict(test_X)

testP = pd.Series(testP.reshape(310,))

pred_df = pd.DataFrame(test_y,columns=['True Y'])
pred_df = pd.concat([pred_df,testP],axis=1)
pred_df.columns = ['True KP', 'Estimated KP']
pred_df.head(60)

pred_df.plot(figsize=(35,5))

