<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dhiraj Reddy on Medium]]></title>
        <description><![CDATA[Stories by Dhiraj Reddy on Medium]]></description>
        <link>https://medium.com/@dhirajreddy13?source=rss-1a22bd467fe7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QqKo35ULSOzDRlm_GQvg2Q.jpeg</url>
            <title>Stories by Dhiraj Reddy on Medium</title>
            <link>https://medium.com/@dhirajreddy13?source=rss-1a22bd467fe7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:22:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhirajreddy13/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Factorization Machines and Follow The Regularized Leader for dummies]]></title>
            <link>https://medium.com/@dhirajreddy13/factorization-machines-and-follow-the-regression-leader-for-dummies-7657652dce69?source=rss-1a22bd467fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7657652dce69</guid>
            <category><![CDATA[ftl]]></category>
            <category><![CDATA[fm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dhiraj Reddy]]></dc:creator>
            <pubDate>Tue, 21 May 2019 09:53:06 GMT</pubDate>
            <atom:updated>2019-05-21T10:22:30.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9v0mcMlP23rB_Wdk.jpg" /><figcaption>Interacting galaxies produce eye-shaped Tsunami</figcaption></figure><p>Problems like ad click prediction needs algorithms to train online i.e. the model needs to learn from the decision(Click/ No click) of the user at time T and update its weights to decide which Ad to show or not show at time T+1.</p><p>Let’s say we define a loss function f_t(w, x) (read as <strong>f</strong> subscript <strong>t</strong>) and we calculate two values for this loss function. One is the actual loss occurred when the user makes a decision. After the user has made the decision we will update the weights i.e. <em>w</em>’s of the model so as to generate the least possible value of loss that could have been achieved. This least possible value of loss calculated in light of the user’s decision is the second value. The difference between the actual loss and the least possible loss that was possible is called the <strong>Regret. </strong>The goal of our model should be to reduce the regret as time progresses i.e Regret at time T+1 should be less than the regret at time T.</p><p>An algorithm that offers us low regret in the online setting is the Follow The Regularized Leader algorithm.</p><p>We will walk through the algorithms that lead to the development of the optimal state of Follow The Regularized Leader and then we will get a gist of how Factorization Machines algorithm takes advantage of the interaction between the features. Finally we will conclude by combining the advantages of FTRL with FMs.</p><p>We will follow the developments in this order</p><ol><li>Follow the leader concept</li><li>Follow the Regularized leader concept</li><li>Truncated Gradient Descent</li><li>Forward Backward Splitting</li><li>Residual Dual Averaging</li><li>Follow The Regularized Leader</li><li>Factorization Machines</li></ol><h4>Follow The Leader (FTL)</h4><p>The loss function is a function of <em>w </em>and <em>x.</em> where <em>w </em>vector corresponds to the weights and <em>x </em>vector corresponds to the feature vector. We calculate loss for all the train data available to us and hence the sum.</p><p>w_1(read as w subscript time instant 1) is initialized arbitrarily. Then w_2, w_3.. and so on are updated as follows:</p><pre>for t=1,2,3....T<br>  w_t = argmin summation(f_s(w)) for all s = 1 to t-1</pre><p>When t=3 we use the w that lead to the minimum value of <em>summation(f_s(w))</em> for all s = 1 to 2.</p><p>When t=4 we use the w that lead to the minimum value of <em>summation(f_s(w))</em> for all s = 1 to 3.</p><p>This algorithm moves slower and slower as time progresses.</p><blockquote>Here we always use the ‘w’ that was the best fit for all previous iterations. Therefore this algorithm is called <strong><em>Following The Leader</em></strong><em> </em>algorithm.</blockquote><p>In certain cases where <em>w</em> and <em>x</em> are from a subset [+1,-1] it can be proven that the regret is approximately equal to T. But we need the regret to reduce with T. Moreover we need the values of <em>w</em> in manageable ranges, if the growth of the value of <em>w</em>’s are unchecked the optimization algorithm will simply choose a large value of <em>w</em> to reduce the loss — You will stumble upon the mathematical reason for this as you scroll down the blog.</p><p>For the reasons mentioned above this algorithm is considered the most impractical solution. But it is the best way to get started and introduces us to the core problem.</p><blockquote>In order to prevent the algorithm from choosing large values of <em>w</em>’s, we add a regularization term to the loss function and optimize this sum. This becomes <strong><em>Follow The Regularized Leader</em></strong> algorithm.</blockquote><p>What I have introduced is a plane vanilla FTL and FTRL algorithms, in other words I have introduced the philosophy behind these algorithms. There were several algorithms that were introduced to optimize FTRL but none succeeded until a bunch of researches at Google came out with <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/41159.pdf">this</a> paper in 2013.</p><p><a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/41159.pdf">Ad Click Prediction: a View from the Trenches</a> is by far the best implementation of FTRL. It further boosts the capabilities of this algorithm by combining with a concept called Factorization Machines (FM, a concept you will be introduced further down in this blog). This new algorithm is unsurprisingly called FM-FTRL.</p><p>But before we get to FM-FTRL we need to know the evolution path starting from Truncated Gradient.</p><h4>Truncated Gradient (TG)</h4><p>For problems with large features i.e. in the range of 7 or 8 powers of 10. We cannot load the entire data set into the memory due to RAM constraints. Large feature set also impact our test evaluation speeds and obviously training speeds. In such a large feature set there will be features whose usefulness varies from little to zero. We are better off without these features. It would be nice if our optimization algorithm could detect such features and render their weights zero instead of a very small number which further sucks the computational resources.</p><p>One no-brainer approach is to simply set the weight to zero if the value is less then a threshold.</p><p>But this is brutal as some features might not be able to prove their importance because of the lack of training data. Therefore we choose a more relaxed truncation method as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*XwNkOAS65HBL6l9XDCtSAw.png" /><figcaption>Simple Truncation v/s Controlled Truncation</figcaption></figure><p>In the figure above the right side figure indicates the <strong>Truncated Gradient</strong> which gives us the ability to control the sparsity of the feature set by controlling the value of alpha. Greater the value of alpha, higher the sparsity.</p><p>Some introductory machine learning classes espouses that L1 regularization to introduce sparsity, but if you dig deep into the mathematical formulation of L1 regularization you will find that it only increases the probability of the weights being reduced to smaller values but not sparsity directly. We need to train for a very long duration before we reach the sparsity levels desired for our problem. This is the luxury our online training unfortunately cannot afford. Thus the need for <a href="http://www.jmlr.org/papers/volume10/langford09a/langford09a.pdf">Truncated Gradient</a>.</p><p>The prediction performance of standard Stochastic Gradient Descent is on par with the Truncated Gradient Descent. Although sparsity reduced computations to a large extent our regret is still approximately equal to T.</p><p>We were so immersed in removing the weights that are too small that we did not consider the other extreme possibility. In case of logistic regression the loss function is of the form “e to the power of -x”. The plot of which is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*PTMMlP28Dw3B-rWarShzFA.png" /><figcaption>Graph of e^-x</figcaption></figure><p>The optimization algorithm will simply choose a w value that is very large so that the loss function approaches zero. We have to beat the smarts of the optimization problem by adding an L2 norm or L1 norm as regularizer that will make sure to check the exploding weights. But how do we effectively solve for a minimum w vector for a function that is sum of two functions(Loss function + Regularizer)?</p><p>Enter Forward Backward Splitting a.k.a Proximal Gradient algorithm.</p><h4>Forward Backward Splitting (FBS) / Proximal Gradient</h4><p>Our optimization problem now is of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*uglfyP8PyuRGcMCXi1kCGw.png" /><figcaption>f(x) is the loss function and g(x) is the regularization</figcaption></figure><p>In this case <em>f(x)</em> is a convex differentiable function but <em>g(x) </em>is an arbitrary (not necessarily smooth) convex function.</p><p>The FBS takes a two step approach to solve the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*ITnjPIRDHg0w3kzdII8NOw.png" /><figcaption>Forward Backward splitting algorithm</figcaption></figure><p>In step one we simply move forward in the direction indicated by the gradient of function <em>f</em> with a step size of <em>tou</em>. In step two we calculate something called as the proximal operator which chooses an optimal value of <em>x</em> not far from the starting point <em>x_k+1</em>. This is achieved by evaluating the gradient at the new point during the updating step rather than evaluating the gradient at the starting point. Hence the name <strong>backward gradient descent</strong>. When FBS is applied to an optimal point of <em>x</em>, the point is moved to a new location by the forward descent step, and the backward descent step puts it back where it started. The step size plays a crucial role in the FBS and there are implementations of FBS where steps sizes are adaptive i.e. they decrease as the optimization closes in on the minimum loss values.</p><p>FBS works well with simple regression problems to complex problems. But it is slow for the simple reason that it is a two step approach. For every weight update it needs to perform twice the number of calculations.</p><p>And more over if we follow SGD during the update we are completely ignoring the learning from all the previous gradients.</p><p>Detailed mathematical explanation of FBS can be found <a href="https://arxiv.org/pdf/1411.3406.pdf">here</a>.</p><h4>Regularized Dual Averaging (RDA) algorithm</h4><p>In SGD we only consider the gradient computed at that moment in time (T) to compute the weight vector for the next instant of time (T+1). SGD does not utilize the fact that loss function and regularization function are actually two functions, we can actually merge the regularization function into the loss function and we would still converge into weights that lead to a similar accuracy. We converge only when <em>t</em> goes to infinity, in practice we stop before that. Albeit the convergence the results are elusive owing to the stochastic nature of the algorithm.</p><p>Batch processing algorithm with L1 regularization produces decent accuracy with satisfactory sparsity (Provided we have enough training data). The sparsity is obtained by setting the weights with low magnitude to zero. However the same cannot be said to SGD, simply setting low weights to zero in SGD leads to very low accuracy levels. Many algorithms were suggested to reduce the aggressive truncation but still the sparsity and accuracy were not even close the those produced by batch processing algorithms. These problems are addressed in RDA by solving the below optimization problem to set the weights for the next time instant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*nYLizaCXGRicqw9ufJHvyQ.png" /><figcaption>RDA optimization problem</figcaption></figure><p>First term is the key to this Algorithm. It is the average of all the previous sub gradients. This sort of brings all the learning from the previous iterations into the update of the next iteration.</p><p>Second term is the regularization function L1 or L2 or L1 and L2.</p><p>Third term is also regularization term which is a strong convex function. with the first term being a non negative and non decreasing input sequence. Second term is an auxiliary strongly convex function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*ebzxvAuYLE5YRiCx0o6D0Q.png" /><figcaption>RDA implementation algorithm</figcaption></figure><p><a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/xiao10JMLR.pdf">RDA</a> is pretty powerful but we might face a problem of exploding gradient because of the averaging function.</p><h4>Follow The Regularized Leader (FTRL)</h4><p>FTRL strikes a trade off between the advantages and disadvantages of FBS and RDA. The update is according to the optimization shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*V-yzKT52FJvnOemvD7--5w.png" /><figcaption>FTRL weight update algorithm</figcaption></figure><p>Where G(1:t) is the average of previous sub gradients. Another cool thing about FTRL is that the learning rate is different for different dimensions. If the training data deems that the dimension <em>i </em>needs to take a wider step than dimension <em>j, </em>the below learning rate will accommodate such updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*T0-nxzgU5lLSSEGi0u-zyw.png" /><figcaption>Learning rate for FTRL</figcaption></figure><p><strong>Factorization Machines (FM)</strong></p><p>In all the algorithms we have glimpsed thus far we can easily conclude that the weight of each feature is learned individually with complete disregard to the interactions among the features. Suppose we are modelling the weight of humans then the height and distance from equator together would be more helpful to infer the weight than looking at them individually.</p><p>One solution to this is to simply make the algorithm learn the weight matrix for the interaction of every feature with other. The conspicuous complexity of this model is impractical to implement. And you guessed it right, the solution is Factorization Machines.</p><p>FM models the interaction among the features as an inner product of lower dimensional vectors. This sentence will make sense after you look at the below equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*mhSlvFTuPafYxx5oxrFzcw.png" /><figcaption>Factorization Machines algorithm</figcaption></figure><p>Details and properties about inner product can be found <a href="http://mathworld.wolfram.com/InnerProduct.html">here</a>.</p><p>The interactions are embedded in the inner product space. The inner product of the features with greater interaction will be greater than the inner product of the features with little or no interactions. More so, this formulation enables us to select the interaction weights even with fewer training samples for any two given features. The vector size of each vector <strong><em>v</em></strong><em> </em>is the lesser than the dimension of each feature, it is a hyper parameter to tune. Clearly the space complexity is linear but not the time complexity. The above formula can be rewritten to be solved in linear time. Therefore we are achieving the effects of feature interactions which is intuitively quadratic in linear time and space. This is the true power of FMs.</p><p><strong>FM-FTRL</strong></p><p>In the FTRL formula we discussed replace the loss function <strong><em>f </em></strong>with the FM formulation and we get FM-FTRL. As with every algorithm FM has a glitch, it is not convex. However SGD seems to work well with FMs.</p><p><strong>References</strong></p><ol><li><a href="http://tech.adroll.com/blog/data-science/2015/08/25/factorization-machines.html">http://tech.adroll.com/blog/data-science/2015/08/25/factorization-machines.html</a> — Factorization Machines</li><li><a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/xiao10JMLR.pdf">https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/xiao10JMLR.pdf</a> — RDA</li><li><a href="https://github.com/anttttti/Wordbatch">https://github.com/anttttti/Wordbatch</a> — Python library for FM-FTRL</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7657652dce69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock price prediction and forecast using LSTM and ARIMA.]]></title>
            <link>https://medium.com/@dhirajreddy13/stock-price-prediction-and-forecast-using-lstm-and-arima-52db753a23c7?source=rss-1a22bd467fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/52db753a23c7</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dhiraj Reddy]]></dc:creator>
            <pubDate>Sun, 05 May 2019 15:25:07 GMT</pubDate>
            <atom:updated>2019-05-05T15:25:07.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*XE10cNjzvZi3eZPl.png" /></figure><p>LSTMs are known to produce great results on time series data.</p><p>Although they are good at predictions are they useful in forecasting?</p><p>ARIMA is a simple, fast and robust mechanism to forecast values.</p><p>Of course we can use ARIMA in forecasting and prediction, but what is the advantage of using ARIMA over LSTM or vice versa?</p><p>These are the questions I will be answering in this blog.</p><p>I will be using the stock prices data downloaded from <a href="https://www.kaggle.com/dgawlik/nyse">here</a>.</p><p><em>All the masters of Machine Learning and Data Science craft who stumble upon this blog, please highlight the novice mistakes and I will correct them to the best of my knowledge.</em></p><h3>Prerequisites:</h3><ol><li><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">LSTM</a></li><li><a href="https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/">ARIMA</a></li></ol><h3>What is in plate for the readers:</h3><ol><li>A simple exploratory data analysis to understand the data set.</li><li>LSTM prediction — Multiple stock symbol prices at a time</li><li>LSTM prediction — One stock symbol price at a time</li><li>LSTM prediction using functional API of Keras demonstrated with auxiliary inputs</li><li>ARIMA model for forecasting, including how to find the P, Q and D values.</li><li>When to use ARIMA and LSTM?</li></ol><h3>Exploratory Data Analysis</h3><p>I am going to use the data from <strong>prices-split-adjusted.csv</strong> through out this blog to explore the aforementioned topics. So let’s pull the data in and execute the Hello world of data science data.head()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*jJqKT5FrzLh4aYGhpQ1Iug.png" /></figure><p>I have sorted the values by date and also made the date column the index</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*_XlG9DB5__vAFdEtx3cBLQ.png" /></figure><p>So we have the opening and closing prices of each stock symbol from January 2010 to December 2016.</p><p>We are going to concentrate on the closing prices only.</p><ol><li>There are no data cells with missing data</li><li>There are exactly 501 unique symbols</li><li>There are 851264 data points collectively.</li></ol><p>Lets get all those unique symbols in to a variable</p><p>all_symbols = data.symbol.unique().tolist()</p><p>Get the closing price of each stock at the end of each year</p><pre>growthData = pd.DataFrame(index=all_symbols, columns=[&#39;2010&#39;,&#39;2011&#39;,&#39;2012&#39;,&#39;2013&#39;,&#39;2014&#39;,&#39;2015&#39;,&#39;2016&#39;])<br>for sym in all_symbols:<br>  symData = data[data.symbol == sym][&#39;close&#39;]<br>  yearEndClosePrices = []<br>  for year in range(2010, 2017,1):<br>    closePrice = symData[symData.index.year == year]<br>    if closePrice.size &gt; 0:<br>      yearEndClosePrices.append(float(symData[symData.index.year == year].tail(1)))<br>    else:<br>      yearEndClosePrices.append(np.nan)<br>        <br>  growthData.loc[sym] = yearEndClosePrices</pre><p>Calculate the percentage change of each stock year on year</p><pre>growthData_pct_change = growthData.pct_change(axis=&#39;columns&#39;)<br>growthData_pct_change.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*UWYuLLToak0vw2jPHtaTXA.png" /></figure><p>Get the top 5 performing stocks at the end of each year with respect to their growth rate. Because in stocks we need to take the difference rather than the absolute value to calculate the profit or loss.</p><pre># Top performing symbols in each year with respect to their growth rate<br>for year in range(2011,2017,1):  <br>  year = str(year)<br>  print(f&#39;=========={year}==========&#39;)<br>  print(&#39; &#39;*24)<br>  print(growthData_pct_change.sort_values(by=year, ascending=False).head()[year])<br>  print(&#39; &#39;*24)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*FhIzIFrGxXu8qwu0xKBvIg.png" /></figure><h3>LSTM prediction — Multiple stock symbol prices at a time</h3><p>Before we build the LSTM model we need to prepare our data for the LSTM. The data need to be scaled and reshaped.</p><blockquote>The number of hidden layers in an LSTM is the number of neurons that form the neural network in the LSTM cell. The LSTM cell has 4 neural networks colored in yellow. The number of neurons that form each of the neural network is the number of hidden layer parameter in keras LSTM. Therefore the output of the LSTM cell i.e. h_t will be of length equal to the number of neurons in the neural network. As a result the output of LSTM layer will be of length equal to the number of hidden layer parameter that we choose.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*pFY3868fEAhIcD1va7l4ZQ.png" /><figcaption>Courtesy of Christopher Olah</figcaption></figure><p>We will use the MinMaxScaler</p><pre>def Scale(train, test):<br>  scaler = MinMaxScaler()<br>  train = np.array(train)<br>  test = np.array(test)<br>  train = scaler.fit_transform(train.reshape(train.shape[0], -1))<br>  test = scaler.transform(test.reshape(test.shape[0], -1))<br>  return scaler, train, test</pre><p>We prepare the data in the format that LSTMs expect.</p><p>For example : for 2 time steps and for sequence [1,2,3,4,5,6,7]<br> The x and y are<br> [[1]<br> [2]] [3]<br> [[3]<br> [4]] [5]<br> [[5]<br> [6]] [7]<br> In every sample each column is feature, each row is a time step. We are predicting the ‘n’ th time step value given the n-2 and n-1 values.</p><pre>def PrepareData(sequence, n_steps):<br>  x, y = [],[]<br>  length = sequence.shape[0]<br>  for i in range(length):<br>    end_index = i + n_steps<br>    <br>    if(end_index &gt;= length):<br>      break;<br>     <br>    x.append(sequence[i:end_index]) <br>    y.append(sequence[end_index])<br>    <br>  x = np.array(x)<br>  y = np.array(y)<br>  x = x.reshape(x.shape[0], n_steps, 1)<br>  return x, y</pre><p>We will create the model that we are going to use</p><pre>def CreateModel(rate = 0.4, n_features = 501):<br>  model = Sequential()<br>  model.add(GRU(256, return_sequences=True, input_shape = (2, n_features)))<br>  model.add(Dropout(rate))<br>  model.add(LSTM(256))<br>  model.add(Dropout(rate))<br>  model.add(Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;))<br>  model.add(Dense(n_features)) # Number of outputs<br>  model.compile(loss=&#39;mean_squared_error&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;mean_squared_error&#39;])<br>  return model</pre><p>By choosing the n_features of our choice we can use the same architecture to model single or multi parallel time series data</p><p>When we are using the architecture for multi parallel series we need to split/reshape the data accordingly.</p><pre>def split_sequences(sequences, n_steps):<br>  x, y = list(), list()<br>  for i in range(len(sequences)):<br>    end_ix = i + n_steps<br>    <br>    if(end_ix &gt; len(sequences)-1):<br>      break<br>      <br>    seq_x, seq_y = sequences[i: end_ix, :], sequences[end_ix, :]<br>    <br>    x.append(seq_x)<br>    y.append(seq_y)<br>    <br>  x = np.array(x)<br>  y = np.array(y)<br>  <br>  return x, y</pre><p>We prepare the data in the format that LSTMs expect<br> For example : for 2 time steps and for sequences [1,2,3,4,5,6,7] and [10,20,30,40,50,60,70]<br> The x and y is<br> [[1 10]<br> [2 20]] [3 30]<br> [[3 30]<br> [4 40]] [5 50]<br> [[5 50]<br> [6 60]] [7 70]<br> In every sample each column is a feature, each row is a time step. Here each feature represents a separate time series data, in our case each feature represents the closing prices of different stock symbols. Output is an array of values, the length of the array should be equal to the number of features. Each value in the output array corresponds to a feature in the order in which features appear.</p><p>When we are modeling for multi parallel input we need to make sure that all the inputs are of equal length. As we are modeling for prices and prices cannot go below zero we will be padding the sequence of smaller length with zeros.</p><pre># 1792 is the maximum number of observations for most of the stocks<br># In order to predict the stock prices using multiple series<br># together in an LSTM, we need to Zeropad the unknown values<br>MAX_VALUES_TRAIN = 1409 # 1792 * 0.8<br>MAX_VALUES_TEST = 353 # 1792 - 1409<br>def ZeroPadding(sequence, maxPaddingWidth):<br>  &quot;&quot;&quot;<br>  sequence = [1,2,3,4]<br>  return sequence = [1,2,3,4,0,0,0,.... upto 1791 index]<br>  <br>  sequence = [1,2,3,4, 5, 6, 7 .... 1791]<br>  return sequence = [1,2,3,4, 5, 6, 7..... 1791] -&gt; No padding as the length match<br>  &quot;&quot;&quot;<br>  length = len(sequence)<br>  if(length &lt; maxPaddingWidth):<br>    retVal = np.pad(sequence.flatten(), (0, maxPaddingWidth-length), &#39;constant&#39;, constant_values=[0])<br>    return retVal<br>  return sequence</pre><p>However we need to be careful while performing a train test split. We need to first split and then zero pad the train test portions. Just like we have to scale the data before the split to avoid train data leaking into test data.</p><p>There fore the order of data preparation is as follows</p><ol><li>Split the time series data in to train and test, we will take 80% of data as train and remaining as test data.</li><li>Scale the train data, use the same scaler to transform the test data. Thus you will end up with one scaler per symbol</li><li>Zero pad the train and test data</li><li>Reshape train and test data</li></ol><blockquote>The number of steps I am choosing to go with is 2 because it gave me better results.</blockquote><p>Phew.. that was a lot of data preparation. Now it is time to finally predict the prices.</p><p>Wait!!</p><p>There are lot of parameters to tune viz. number of epochs, batch size during each epoch and drop out rate.</p><p>We will use <strong>KerasRegressor </strong>and skelarn’s <strong>GridSearchCV </strong>to select the best value for these parameters using Mean Squared Error as our metric.</p><p>All the input parameters of the function CreateModel and all the input parameters to the fit function of the sequential model instance should be passed as key to the param_grid of GridSearchCV. n_features is the input parameter of function CreateModel and validation_data is the input parameter of the model.fit function.</p><pre>model = KerasRegressor(build_fn=CreateModel,verbose = 0)</pre><pre>params = {&#39;epochs&#39; : [100,150,200],<br>          &#39;batch_size&#39; : [100, 150],<br>          &#39;n_features&#39; : [test_y.shape[1]],<br>          &#39;rate&#39;: [0.3],<br>          &#39;validation_data&#39; : [(test_x, test_y)]}</pre><pre>regressor = GridSearchCV(estimator = model, param_grid = params, n_jobs = 1, refit=True, scoring=&#39;neg_mean_squared_error&#39;)</pre><pre>regressor.fit(train_x, train_y)</pre><pre>preds = regressor.predict(test_x)</pre><p>When we try to model with multi parallel input we get good results for some symbols and bad - i mean really bad - results for some symbols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*sIfRoKXbEiRmo-6crQ2OEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*100P3LDhy6lUu3F1ch_M9w.png" /></figure><p>It is evident that upon trying to solve for all the stock prices using a single architecture leads to a wider deviation in some symbols. Therefore we have to hyper parameter tune the architecture, epochs and batch size for each symbol.</p><h3>LSTM prediction — One stock symbol prices at a time</h3><p>Upon hyper parameter tuning for the stock symbol <strong>FB</strong>. We get the below result.</p><p>The drop out rate, epochs and batch_size values were arrived at after hyper parameter tuning.</p><pre>model = CreateModel(0.0,1)<br>model.fit(train_x, train_y.flatten(), epochs=150, batch_size=64)<br>y_pred = model.predict(test_x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*CkpS_KwMU-UNs685DjtqNA.png" /></figure><h3>LSTM prediction using functional API of Keras demonstrated with auxiliary inputs</h3><p>Lets add some auxiliary features to see if the predictions improve. The auxiliary inputs that I am going with are</p><ol><li>Rolling mean of the past two values</li><li>Top 3 Fourier amplitudes</li><li>Top 3 Fourier frequencies</li></ol><p>Therefore there are 7 auxiliary inputs for each sample of data that goes into the LSTM layer.</p><pre># Rolling mean<br>def moving_average(x, w):<br>  return np.convolve(x, np.ones(w)) / w</pre><pre># Fourier features<br>ffts = np.fft.fft(train.flatten())<br>amps = np.abs(ffts)<br>freqs = np.abs(np.fft.fftfreq(train.shape[0],1))</pre><pre># The amplitudes are symmetric in nature.<br># Therefore when sorted we will have two equal amplitudes places <br># next to each other<br># We discard the first amplitude because it is just the value along # which the time series is moving. In simple words it is the DC <br># component of the AC current<br>amps_sorted_indices = np.argsort(-amps)[2:]</pre><pre># The reason for choosing 0, 2 and 4 is because same value appears<br># twice due to the symmetric nature of Fourier transformation<br>max_amp_1 = amps[amps_sorted_indices[0]]<br>max_amp_2 = amps[amps_sorted_indices[2]]<br>max_amp_3 = amps[amps_sorted_indices[4]]</pre><pre>max_freq_1 = freqs[amps_sorted_indices[0]]<br>max_freq_2 = freqs[amps_sorted_indices[2]]<br>max_freq_3 = freqs[amps_sorted_indices[4]]</pre><pre># Prepare the auxiliary inputs <br>rolling_tr = moving_average(train.reshape(1,-1)[0], 2)[1:-2]<br>rolling_te = moving_average(test.reshape(1,-1)[0], 2)[1:-2]<br>aux_inputs_tr = []<br>aux_inputs_te = []</pre><pre>for i in range(0,train_x.shape[0]):<br>  aux_inputs_tr.append([rolling_tr[i], max_amp_1, max_amp_2, max_amp_3, max_freq_1, max_freq_2, max_freq_3])<br>  <br>for i in range(0,test_x.shape[0]):<br>  aux_inputs_te.append([rolling_te[i], max_amp_1, max_amp_2, max_amp_3, max_freq_1, max_freq_2, max_freq_3])</pre><p>Our next step is to come up with an architecture that accommodates these new features <strong>in addition</strong> to the time steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*KNKl7bvrxEkFrlUHfEPXZg.png" /></figure><p>It will be cumbersome to construct such architecture with a sequential model. We will use the <a href="https://keras.io/getting-started/functional-api-guide/">Keras functional API</a> to achieve this.</p><pre>def CreateModelWithAuxillaryyInputs(rate = 0.4, n_lstm_layers = 2, n_dense_layers = 2, dropout = True):<br>  main_input = Input(shape=(2,1), dtype=&#39;float&#39;, name=&#39;main_input&#39;)<br>  lstm_out = LSTM(256, return_sequences = n_lstm_layers &gt; 1)(main_input)<br> <br>  if n_lstm_layers == 2:<br>    if dropout:<br>      lstm_out = Dropout(rate)(lstm_out)<br>    lstm_out = LSTM(256, return_sequences = n_lstm_layers &gt; 2)(lstm_out)<br>  <br>  if n_lstm_layers == 3:<br>    if dropout:<br>      lstm_out = Dropout(rate)(lstm_out)<br>    lstm_out = LSTM(256)(lstm_out)<br>  <br>  aux_input = Input(shape=(7,), name=&#39;aux_input&#39;)<br>  x = concatenate([lstm_out, aux_input])<br>  x = Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39; )(x)<br>  <br>  if n_dense_layers == 2:<br>    if dropout:<br>      x = Dropout(rate)(x)<br>    x = Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;)(x)<br>    <br>  if n_dense_layers == 3:<br>    if dropout:<br>      x = Dropout(rate)(x)<br>    x = Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;he_uniform&#39;)(x)<br>  <br>  main_output = Dense(1, activation=&#39;linear&#39;, name=&#39;main_output&#39;)(x)<br>  <br>  model = Model(inputs=[main_input, aux_input], outputs=[main_output])<br>  model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;, metrics=[&#39;mean_squared_error&#39;])<br>  <br>  return model</pre><p>I was not able to use KerasRegressor and GridSearchCV for this architecture. If any of you folks know how to do it please comment the example or the documentation for the same.</p><p>When I measured the MAPE(Mean absolute percentage error) for <strong>FB </strong>stock symbol with and without auxiliary features, the model without auxiliary features yielded better results. This was true for all symbols.</p><blockquote>Although our experiment of including auxiliary features failed, we learned how to model additional inputs, share layers and use Kears functional API. Failed architectures are a major part of Machine learning, so newcomers get used to disappointment. On the bright side you will learn many things that can help you gain brownie points in your interviews</blockquote><h3>ARIMA model for forecasting</h3><p>What if I want to predict the closing price of FB stock in the next 30 days?My LSTM model can predict the next price given the previous two time stamp prices. Here each time stamp represents one day. So given past two days values my model can predict today’s closing price. So if I want to predict a value 30 days from now — This is called forecasting, I need to have values of the 28th and 29th day from now. If I need to find the value of 28th day, I need to find the value of 27th and 26th day, and so on.</p><p>So I get the last two values in train data and predict the next value. Now I use the new value and the last value in the train data to predict the next value. Now I use last two predicted values to predict the next value and so on until I reached the time for which the value is required. Notice that we are not touching the test data. We are only using train data to arrive at a possible value in future. This is called forecasting.</p><p>The forecasting done in this way was horrible. They were so bad that I will not waste the space to post them here.</p><p>Given two previous values I can <strong>predict </strong>the next value, but if I want an estimate of the value that is way ahead in the future I <strong>forecast </strong>the value. In order to forecast, we need to have an understanding of below terminologies</p><ol><li>Level — The value above or below which time series data is oscillating, in simple words it is the average/moving average of previous n values</li><li>Trend — Indicate the growth or decline of previous n values, in simple words the slope of the values.</li><li>Seasonality — The patterns in the time series data that is repeated after a certain time interval.</li></ol><p>Explaining each of these concept is another big blog altogether. I have given an excellent link in the prerequisites section that will explain time series forecasting in depth. Please go though that link before proceeding.</p><p>As our stock prices have a significant trend and any time series forecasting deals only with stationary data we need to detrend and remove the seasonality before we develop a model. We should apply the trend and seasonality to our model’s predictions to get the actual value.</p><p>Sounds like a lot of work. But do not worry I am writing this blog to make these tasks easy for you.</p><p>The below imports will help you achieve cross these barriers</p><pre>from statsmodels.tsa.stattools import acf, pacf<br>from scipy.ndimage.interpolation import shift<br>from statsmodels.tsa.arima_model import ARIMA</pre><p>We can detrend the model by differencing each value from a value in the past and modeling these differences. Later adding the value from the past to arrive at the actual value. We can choose to difference each value from a value at t-1 or t-2 or t-3 … Upon experimentation I found t-2 to give good results. By good results I mean the stationarity of the resulting time series was better. Again to know what is stationarity and how to measure it please go through the link in the prerequisite section.</p><pre>n_diff = 2<br>train_x_diff = flat_train_x - shift(flat_train_x, n_diff, cval=np.nan)<br>train_x_diff = train_x_diff[n_diff: ]<br>plt.plot(train_x_diff)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*c4w3B-s7jyBqQNFaeggsJw.png" /><figcaption>Differneced close prices of FB</figcaption></figure><p><strong>ARIMA </strong>— <strong>A</strong>uto<strong>R</strong>egressor(p) <strong>I</strong>ntegrated(d) <strong>M</strong>oving <strong>A</strong>verage(q).</p><p>ARIMA is a regression model whose features are determined by the below parameters</p><ul><li>p — Number of previous values to consider for estimating the current value</li><li>d — n_diff in the previous code snippet</li><li>q — If we consider a moving average to estimate each value, then q indicates the number of previous errors. i.e if q= 3 then we will consider e(t-3), e(t-2) and e(t-1) as inputs of the regressor. Where e(i) = moving_average(i)- actual_value(i)</li></ul><p>We determine <strong>P</strong> and <strong>Q</strong> using <strong>PACF</strong>(Partial Auto Correlation Function) and <strong>ACF</strong>(Auto Correlation Function) graphs respectively.</p><pre>lag_acf = acf(train_x_diff, nlags=10)<br>lag_pacf = pacf(train_x_diff, nlags=10, method=&#39;ols&#39;)<br>plt.figure(figsize=(20,5))<br>plt.subplot(121) <br>plt.plot(lag_acf)<br>plt.axhline(y=0,linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.axhline(y=-1.96/np.sqrt(len(flat_train_x)),linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.axhline(y=1.96/np.sqrt(len(flat_train_x)),linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.title(&#39;Autocorrelation Function&#39;)</pre><pre>#Plot PACF:<br>plt.subplot(122)<br>plt.plot(lag_pacf)<br>plt.axhline(y=0,linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.axhline(y=-1.96/np.sqrt(len(flat_train_x)),linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.axhline(y=1.96/np.sqrt(len(flat_train_x)),linestyle=&#39;--&#39;,color=&#39;gray&#39;)<br>plt.title(&#39;Partial Autocorrelation Function&#39;)<br>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2hCjfG14mNCiLvDxoxk5g.png" /><figcaption>ACF and PACF graphs</figcaption></figure><p>Notice that we are plotting the ACF and PACF graphs for the differenced values and not the actual values.</p><p>Both ACF(for <strong>q</strong>) and PACF(for <strong>p</strong>) cut the upper dotted line for the first time at a value close to 2 on the x-axis. Therefore we choose both q and p values as 2. I experimented with different lags and most of the lag values yield same result.</p><p>The only thing left to do is initialize ARIMA and fit the train values</p><pre>model = ARIMA(flat_train_x, order=(2, 2, 2))  <br>results_AR = model.fit()  <br>plt.figure(figsize=(20,5))<br>plt.plot(train_x_diff)<br>plt.plot(results_AR.fittedvalues, color=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQApTdnbrdJfEBdlR2uFuQ.png" /><figcaption>Fitted values in red and actual values in blue</figcaption></figure><p>The absolute fitted values are close to the actual values, but the sign of each value seem to be inverted so multiply each value with -1 to get the correct sign. I do not know why this is happening, yet. If any of you folks can help me out that’d be great.</p><pre>plt.figure(figsize=(20,5))<br>plt.plot(train_x_diff)<br>plt.plot(-1*results_AR.fittedvalues, color=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWnVoFIvtA34TyT7mTHffA.png" /><figcaption>Fitted values are close to the expected values</figcaption></figure><p>We need to keep in mind an important nity grity detail about the ARIMA model. With ARIMA predictions the start and end indices are inclusive.<br>If 398 is the length of the diff array i.e there are 0 to 397 indices.<br>If we need to predict the next 200 values, starting form index 398,<br>398 + 200 = 598, but again remember end index is inclusive so choose end = 597. We also need to add the 2nd previous value to the current predicted value. This is required because we initially modeled the differenced data.</p><pre>y_pred = results_AR.predict(start=398, end=597)<br>y_pred = -1 * y_pred</pre><pre>for i in range(2, 200):<br>    y_pred[i] = y_pred[i] + test_y[i-2][0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Rz3FQ5ecNmHSsVCcaXrUg.png" /><figcaption>ARIMA forecasting without 2 time steps shifting</figcaption></figure><p>As it clearly appears that the predictions are 2 time steps ahead the actual values. We will shift the actual values by two time steps.</p><pre>plt.figure(figsize=(20,5))<br>plt.plot(y_pred[2:], label=&#39;Predictions&#39;)<br>#plt.plot(test_y.flatten()[2:], label=&#39;actual&#39;)<br>plt.plot(shift(test_y.flatten()[2:], 2, cval=np.nan), label=&#39;actual&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pD3ddPz8n0G1vEo1vIXrKw.png" /><figcaption>ARIMA forecasting with 2 time steps shifting</figcaption></figure><h3>When to use ARIMA and LSTM?</h3><p>It is very important to note that the above predictions are purely extracted from the train data. In case of LSTM we needed the previous values of test data to predict the next value. But in ARIMA we forecasted all the test values without the help of any test data but only using the train data. i.e. When we want to predict the value at time instance 30 we went to test data and extracted the values at 28 and 29 and feed it to the NN, but in case of ARIMA we just pass the index 30, ARIMA will use the information of seasonality in train data, previous values in train data and trend in train data to forecast a value at 30. In ARIMA we do not need the 28th and 29th value to predict the 30th value. I hope I have made my point clear here. If not please comment and I will try to articulate it better.</p><p>That’s all folks | Thanks for reading | Stay Foolish, Stay Hungry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52db753a23c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>