Predicting Future using RNN¶
In this Tutorial i will be teaching you how to predict Future Stock Values using RNN Network¶
Soumil Nitin Shah¶
Bachelor in Electronic Engineering | Masters in Electrical Engineering | Master in Computer Engineering |
- Website : https://soumilshah.herokuapp.com
- Github: https://github.com/soumilshah1995
- Linkedin: https://www.linkedin.com/in/shah-soumil/
- Blog: https://soumilshah1995.blogspot.com/
- Youtube : https://www.youtube.com/channel/UC_eOodxvwS_H7x2uLQa-svw?view_as=subscriber
- Facebook Page : https://www.facebook.com/soumilshah1995/
- Email : shahsoumil519@gmail.com
- projects : https://soumilshah.herokuapp.com/project
Hello! I’m Soumil Nitin Shah, a Software and Hardware Developer based in New York City. I have completed by Bachelor in Electronic Engineering and my Double master’s in Computer and Electrical Engineering. I Develop Python Based Cross Platform Desktop Application , Webpages , Software, REST API, Database and much more I have more than 2 Years of Experience in Python
Import all Modules¶
import numpy as np
import os
import tensorflow as tf
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
%matplotlib inline
df = pd.read_csv("Google_Stock_Price_Train.csv")
print(df.head(3))
print("\n")
print(df.isnull().sum())
print("\n")
print(df.info())
print("\n")
print(df.describe())
Import the training Set¶
Training_Set = df.iloc[:,1:2]
print(Training_Set.head(2))
print("\n")
print(Training_Set.shape)
convert into Numpy Array¶
Training_Set = Training_Set.values
Normalize The data Set¶
sc = MinMaxScaler(feature_range=(0, 1))
Train = sc.fit_transform(Training_Set)
we will look at 60 time stamp back to predict the Future¶
X_Train = []
Y_Train = []
# Range should be fromm 60 Values to END
for i in range(60, Train.shape[0]):
# X_Train 0-59
X_Train.append(Train[i-60:i,0])
# Y Would be 60 th Value based on past 60 Values
Y_Train.append(Train[i,0])
# Convert into Numpy Array
X_Train = np.array(X_Train)
Y_Train = np.array(Y_Train)
print(X_Train.shape)
print(Y_Train.shape)
Applying Reshaping Function¶
# Shape should be Number of [Datapoints , Steps , 1 )
# we convert into 3-d Vector or #rd Dimesnsion
X_Train = np.reshape(X_Train, newshape=(X_Train.shape[0], X_Train.shape[1], 1))
Model¶
regressor = Sequential()
# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_Train.shape[1], 1)))
regressor.add(Dropout(0.2))
# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units = 1))
# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
regressor.fit(X_Train, Y_Train, epochs = 60, batch_size = 32)
Test¶
df1 = pd.read_csv('Google_Stock_Price_Test.csv')
df1.head(2)
combine Train and Test Dataset Combine into 1 DataFrame¶
Df_Total = pd.concat((df["Open"], df1["Open"]), axis=0)
Df_Total.shape
# Getting the predicted stock price of 2017
# len(Df_Total) ----- >. Total 1278 rows
# len(df1) ----> 20 Rows
# result When we Subtract we get Original Dataset
# We need Prevoius 60 to predict NEW so we do -60
# that would be our inputs
inputs = Df_Total[len(Df_Total) - len(df1) - 60:].values
# We need to Reshape
inputs = inputs.reshape(-1,1)
# Normalize the Dataset
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 80):
X_test.append(inputs[i-60:i, 0])
# Convert into Numpy Array
X_test = np.array(X_test)
# Reshape before Passing to Network
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# Pass to Model
predicted_stock_price = regressor.predict(X_test)
# Do inverse Transformation to get Values
predicted_stock_price = sc.inverse_transform(predicted_stock_price)
# change the index to Date
df1["Open"].plot()
plt.title("Actual Google Stock Price")
plt.grid(True)
plt.ylabel("Price in $")
Test = pd.read_csv('Google_Stock_Price_Test.csv')
Prediction = pd.DataFrame(data={
"Date":Test["Date"].to_list(),
"Open":Test["Open"],
"Network Predicted":[x[0] for x in predicted_stock_price ]
})
Prediction.plot()
Prediction
very nicely describe thank you. we need to download the data set from kaggle.
ReplyDelete