<?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 Tirth1306 on Medium]]></title>
        <description><![CDATA[Stories by Tirth1306 on Medium]]></description>
        <link>https://medium.com/@tirth.stu?source=rss-a4b8f5bfb324------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_ZfQ9EOhjhqU3KrjOAEpFg.jpeg</url>
            <title>Stories by Tirth1306 on Medium</title>
            <link>https://medium.com/@tirth.stu?source=rss-a4b8f5bfb324------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:42:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tirth.stu/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[Browser-based Models with TensorFlow.js]]></title>
            <link>https://medium.com/analytics-vidhya/browser-based-models-with-tensorflow-js-afcd10be3615?source=rss-a4b8f5bfb324------2</link>
            <guid isPermaLink="false">https://medium.com/p/afcd10be3615</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <dc:creator><![CDATA[Tirth1306]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 18:27:05 GMT</pubDate>
            <atom:updated>2020-09-08T16:03:26.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>One of the key skills for machine learning is not just making models but also deployment. One of the most exciting deployment scenarios is javascript, where you can train, test, and make inferences right there in your web browser.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Grf-UsXV3MYkE0f95DB8mg.jpeg" /><figcaption>Source — <a href="https://www.freepik.com/free-vector/machine-learning-banner-artificial-intelligence_6993831.htm#page=1&amp;query=machine%20learning&amp;position=25">Freepik</a></figcaption></figure><p>You might be thinking, that training a machine learning model and getting inferences from it will require a big data center or maybe a big GPU at least in your machine. But with the help of modern web-browser and high tech computers, we can instantly train a model and deploy it on your web browser. It’s cool that we can easily upload an image to a web browser or can get the image from a webcam. Then we can have a model to do inferences right in the web browser without needing to send that image up to the cloud to be processed by any server.</p><h3>Design and architecture of TensorFlow.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npKSvz2aHjl3mzVT3bGN-A.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/browser-based-models-tensorflow/lecture/PITQg/a-few-words-from-laurence">Coursera</a></figcaption></figure><p>It is designed in such a way that it can be run on a browser as well as on the Node.js server. The <strong>Layers API </strong>in <a href="https://www.tensorflow.org/js">TensorFlow.js</a> looks and feels a lot like Keras. As we will be coding in javascript, there is a slight difference in syntax that we used to code in python. The low-level APIs are called <strong>Core APIs.</strong>They are designed to work with TensorFlow saved model formats, which is designed to be a standard file format that can be used across the <a href="https://www.w3schools.com/js/">JavaScript</a>, the Python APIs, and even <a href="https://www.tensorflow.org/lite/">TensorFlow Lite</a> for mobile and embedded devices. For accelerated training and inference, the Core API then operates with the browser and can take advantage of <a href="https://en.wikipedia.org/wiki/WebGL"><strong>WebGL</strong></a>. Also on <a href="https://www.w3schools.com/nodejs/"><strong>Node.js</strong></a>, you can build server-side or terminal applications and can then take benefit of CPUs, GPUs, and TPUs depending on your machine.</p><h3>Simple Neural Network in Browser</h3><p>The first thing you’ll need to do is add a script tag below the head and above the body of your <a href="https://www.w3schools.com/html/">HTML </a>file to load the TensorFlow.js file. Below is the code to do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e1f68a086bcb85a219bc44b822651cb/href">https://medium.com/media/6e1f68a086bcb85a219bc44b822651cb/href</a></iframe><p>The first line defines the model to be sequential. The simplest possible neural network is one layer with one neuron. So we’re only adding one dense layer to our sequence. This dense layer has only one neuron in it, as you can see from the units equals one parameter. We then compiled a neural network with a loss function as <strong>Mean Squared Error</strong>, which works well in a linear relationship and <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent"><strong>SGD(stochastic gradient descent)</strong></a> as the optimizer. <strong>Model.summary</strong> just outputs the summary of the model definition for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e17d43ec4f889fe24b03eac07f92e56/href">https://medium.com/media/0e17d43ec4f889fe24b03eac07f92e56/href</a></iframe><p>Also, <strong>dotraining()</strong> should be an asynchronous function because training can take an indeterminate amount of time, and we don’t want to block the browser while this is going on. You call this function and parse the model that you just created above and can do the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6284f8fcd85951bd9b1f9673a5c44532/href">https://medium.com/media/6284f8fcd85951bd9b1f9673a5c44532/href</a></iframe><p>Below is the <strong>data </strong>that you’ll use to train the neural network. First, you’ll notice that we’re defining it as a <strong>tensor 2D</strong>, whereas in Python we were able to use a NumPy array. We don’t have NumPy in JavaScript, so we’re going a little lower. As its name suggests, when using a <strong>Tensor 2D</strong>, you have a two-dimensional array or two one-dimensional arrays. So in this case you’ll see that my training values are in one array, and the second array is the shape of those training values. So I’m using a set of 6 values in a one-dimensional array, and thus the second parameter is <strong>[6, 1]</strong>, and we will do the same for <strong>y</strong>. So if you tweak this code to add or remove parameters, remember to also add the second array to match its size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10005dcca6595bbeb3d28b4e31c631f/href">https://medium.com/media/a10005dcca6595bbeb3d28b4e31c631f/href</a></iframe><p>After calling the asynchronous dotraining() function, we can easily do predictions using the <strong>model.predict</strong> by passing the value to be predicted in <strong>tensor2d</strong>. Now, you are ready to run our first ever and simple neural network in your web browser. Just run your HTML file and you can see the training in the console along with the summary of the model and get the predicted output as an alert message as shown below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH14UIK66fGE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH14UIK66fGE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH14UIK66fGE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4460dcbd2f059fb2a72c048b9e1846e/href">https://medium.com/media/f4460dcbd2f059fb2a72c048b9e1846e/href</a></iframe><h3>Image Classification In the Browser</h3><p>Now, we will look at image processing in JavaScript, by training <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53#:~:text=A%20Convolutional%20Neural%20Network%20(ConvNet,differentiate%20one%20from%20the%20other.">convolutional neural networks</a> for image classification in the browser, and then writing a browser app that takes these images and passes them to the classifier. We’ll start by looking at creating the model using JavaScript. So below is the code for creating a convnet with JavaScript. It’ll mostly look familiar, but there are a few minor differences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95be26714fe18d1e163a648af81847a/href">https://medium.com/media/a95be26714fe18d1e163a648af81847a/href</a></iframe><p>Training a model can be done with the fit method of the model object. You pass it the training data and labels, as well as a dictionary of parameters. Batching data for training instead of flooding the model with all of the data at once is always a good idea. When doing it in the browser it’s an even better idea so you don’t lock up the browser itself. If you want the model to validate as it’s training to report back an accuracy, then you can use a list of validation data as shown below. You also can specify the number of epochs that you want to train and can shuffle the data to prevent <a href="https://www.geeksforgeeks.org/underfitting-and-overfitting-in-machine-learning/">over-fitting</a>. As always, you can specify callbacks, so you can update the user on the training status, and for that javascript has a cool library called tf-vis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab3d0bec65c9ada0f78a8f170357bb3e/href">https://medium.com/media/ab3d0bec65c9ada0f78a8f170357bb3e/href</a></iframe><h4>— Visualization tool in Javascript ( <a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-vis">tjs-vis</a> )</h4><p>JavaScript has some extra tools that you can use to make visualization of the training a lot more friendly. First of all, you include the library called tjs-vis in your code with this script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddaec8722c5ea79bf7f3df1211541079/href">https://medium.com/media/ddaec8722c5ea79bf7f3df1211541079/href</a></iframe><p>To use the tf-visualization libraries with fitCallbacks, you simply declare it to be the return from <strong>tfvis.show.fitCallbacks</strong>. This function requires you to pass it a container where it will render the feedback, and a set of metrics that it should track. It’s straightforward as setting the metrics list to the metrics that you want to capture, like loss, validation loss, accuracy, and validation accuracy. And for the container, you just set a name and any required styles, and the visualization library will create tose elements in the browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79b1137b6d5c5ad5ac5068c23525b1ec/href">https://medium.com/media/79b1137b6d5c5ad5ac5068c23525b1ec/href</a></iframe><h4>— Sprite Sheet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*yRYrhs_dPmjV6TMAvNQQSw.png" /><figcaption>Part of the MNIST Sprite Sheet ( Source — <a href="https://storage.googleapis.com/learnjs-data/model-builder/mnist_images.png">Sprite Sheet</a> )</figcaption></figure><p>You might be familiar with the <a href="https://en.wikipedia.org/wiki/MNIST_database">MNIST database</a> which contains thousands of images. When training the model in python it takes every image as an input from the file system and processes it according to the model very easily and instantly. But in the browser, whenever you load an image it makes an <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP </a>call, and making thousands of HTTP call is not a good practice. One of the good solutions is by making a <a href="https://www.codeandweb.com/what-is-a-sprite-sheet"><strong>sprite sheet</strong></a><strong> </strong>of the whole MNIST dataset. Sprite Sheet is very beneficial for training a classifier in javascript. So, the sprite sheet contains all 70,000 images in a single image, stack on one another, which will be then sliced into an individual image. This individual image is then converted into arrays and will be processed by the model.</p><p>Below is the Demo of Handwriting Classification using the MNIST dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIPo2CWrK7aE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIPo2CWrK7aE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIPo2CWrK7aE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc98d1baeb3490ce1bbc0f635958828c/href">https://medium.com/media/dc98d1baeb3490ce1bbc0f635958828c/href</a></iframe><h3>Converting Models to JSON Format</h3><p>We can take models that have been created with <a href="https://www.tensorflow.org/">TensorFlow </a>in Python and convert them to <a href="https://www.json.org/json-en.html">JSON </a>format so that they can run them in the browser using Javascript. For this, we have to install tensorflowjs in python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/623c8b26fc193accc6d573202f22d49d/href">https://medium.com/media/623c8b26fc193accc6d573202f22d49d/href</a></iframe><p>Once you had created and trained your model, we need to save out our model. We’ll start by generating a directory to save the file, and we do that using a timestamp. So we’ll <strong>import time</strong>, get the current timestamp, and save the model and the path /tmp/saved_models/ followed by the timestamp. It saves the saved model to the specified path. Now the next line will convert your saved model to JSON format. Your model may have multiple files other than just model.json, depending upon your model. Next step, you’ll need to download these files and put them in the same directory as the HTML page that will host them. For more methods, <a href="https://www.tensorflow.org/guide/keras/save_and_serialize">click here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4182666609a78762e7f9d142e3381ff6/href">https://medium.com/media/4182666609a78762e7f9d142e3381ff6/href</a></iframe><p>First of all, the URL of the model has to be loaded over HTTP. While it’s in the same directory as the HTML, we can directly write the name but I still use the URL path. Be sure to get this part right. To get the JSON and turn it into a model, I’ll call <strong>await tf.loadlayersModel()</strong> by passing that <strong>MODEL_URL</strong>. Once this completes, I’ll have a trained model available to me. Now, I can inspect the model by calling its model.summary and can get the results by calling <strong>model.predict()</strong>. Yeah, that’s it. Now you can make any type model in python and it can be used in the javascript by converting into JSON format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b99d2d8e228bf96dda5791427264f2da/href">https://medium.com/media/b99d2d8e228bf96dda5791427264f2da/href</a></iframe><h3>Transfer Learning in Javascript</h3><p><a href="https://towardsdatascience.com/a-comprehensive-hands-on-guide-to-transfer-learning-with-real-world-applications-in-deep-learning-212bf3b2f27a">Transfer Learning</a> is a technique in which we apply the knowledge to one problem i.e. obtained from another problem. Here, as before, you’ll load the JSON model from its hosted URL and use <strong>tf.loaLayersModel</strong> to load it into an object. Here I am using a hosted URL of <a href="https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json"><strong>pre-trained mobilenet</strong></a>. From here, you can now get one of the output layers from the preloaded mobilenet. We’re selecting the layer called <strong>conv_p3_13_relu,</strong> above which we will be freezing everything. We’ll then use the <strong>tf.model</strong> class to make a new model and its constructor can take inputs and outputs, which we will set to take the mobilenet inputs, namely the top of the mobilenet and then <strong>conv_pw_13_relu</strong> as output. So that everything beneath that layer will be ignored when we connect a new set of layers to this model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99201a85b67e99fa01946f51eb82bb3c/href">https://medium.com/media/99201a85b67e99fa01946f51eb82bb3c/href</a></iframe><p>Unlike Python, instead of adding a new densely connected set of layers underneath the frozen layers from the original model, we will create a new model in javascript. With its input shape being the output shape of the desired mobilenet layer. We then treat this as a separate model that we train.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f843b12e963bcb5806bf3de7e8044cae/href">https://medium.com/media/f843b12e963bcb5806bf3de7e8044cae/href</a></iframe><p>At prediction time, we’ll then get a prediction from our truncated mobilenet up to the layer that we wanted to give us a set of embeddings. We’ll then pass those embeddings through the new model to get a prediction that the new model was trained on. As you can see below, it’s a little bit different from what you might be used to.</p><h3>Rock Paper Scissors Lizard Spock</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*2FXmoxqIbzfNsQi-AmOGFQ.png" /><figcaption>Source — <a href="https://the-big-bang-theory.com/rock-paper-scissors-lizard-spock/">Fansite</a></figcaption></figure><p>An extension of the traditional game of chance, Rock Paper &amp; Scissors, created by Karen Bryla and Sam Kass. <a href="http://www.samkass.com/theories/RPSSL.html">Sam Kass explains</a>, he designed this extended game because it appeared like most games of Rock Paper &amp; Scissors would end in a tie.</p><blockquote>“Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors.” — Sheldon</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*hqhlAgvVMEGzaWLyc5gNjA.jpeg" /><figcaption>Source — <a href="https://the-big-bang-theory.com/rock-paper-scissors-lizard-spock/">The Big Bang Theory</a></figcaption></figure><p>Now, I have developed the classifier using a pre-trained MobileNet model to classify hand gestures of Rock, Paper, Scissors, Spock, and Lizard captured by a webcam. In this project, I have used all the concepts that are discussed above, and below is the demo of my project along with code explanation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLugI5wvEk0A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLugI5wvEk0A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLugI5wvEk0A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3565b7c6d6be002403f3c2560e328e7/href">https://medium.com/media/a3565b7c6d6be002403f3c2560e328e7/href</a></iframe><h3>Conclusion</h3><p>With the help of tensorflowjs, we can train, test, and validate our model in the browser with the help of javascript. We also learned some tool like tjs-vis which is used for better visualization of training in the browser and some technique like sprite sheet which is very important to reduce the HTTP calls to the server. Then we had learned some tricks like converting your pre-trained model to JSON format and then using that converted model in the javascript. Also, we have seen Transfer Learning in javascript which was slightly different from what we used to do in python. If you want to go more deep in this domain would like to recommend <a href="https://www.coursera.org/learn/browser-based-models-tensorflow">this course</a> by <a href="https://www.coursera.org/">Coursera</a>.</p><h3>Tirth Patel — Computer Science and Engineering Student, Nirma University.</h3><p><a href="https://www.linkedin.com/in/tirth-patel-861303171/">LinkedIn</a> | <a href="https://github.com/Tirth1306/">Github</a>| <a href="https://www.instagram.com/__txrth__/">Instagram</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afcd10be3615" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/browser-based-models-with-tensorflow-js-afcd10be3615">Browser-based Models with TensorFlow.js</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series and Prediction (Part-2)]]></title>
            <link>https://medium.com/analytics-vidhya/time-series-and-prediction-part-2-84f674803c03?source=rss-a4b8f5bfb324------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f674803c03</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tirth1306]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 05:01:13 GMT</pubDate>
            <atom:updated>2020-07-17T14:48:39.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comprehensive Study of Time Series and Prediction with and without deep learning algorithms.</h4><p>Cheers! you made it here. This is my second article on Time Series and prediction. If you have not read the first one then please read that article <a href="https://medium.com/@tirth.stu/time-series-and-prediction-part-1-4a9b55c85276"><strong><em>here</em></strong></a>. In this part, we are going to apply some deep Learning algorithms to our time series. First of all, we have to divide our data into features and labels.</p><h3>Preparing features and labels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yGVurgsif0HePpxdPVViw.png" /><figcaption>features and labels (Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a>)</figcaption></figure><p>In this case, our feature is effectively several values in the series, with our label being the next value. We’ll call that number of values that will treat as our feature, the window size, where we’re taking a window of the data, and training an ML model to predict the next value. So for example, if we take our time-series data, say, 30 days at a time, we’ll use 30 values as the feature and the next value is the label. Then over time, we’ll train a neural network to match the 30 features to the single label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4734a2ae2c596f3096840a61e3d1815/href">https://medium.com/media/a4734a2ae2c596f3096840a61e3d1815/href</a></iframe><p>So let’s, for example, use the <strong>tf.data.Dataset</strong> class to create some data for us, we’ll make a range of 10 values. We’ll use the <strong>dataset.window</strong> to expand our data set using windowing. Its parameters are the size of the window and how much we want to shift by each time. So we will set a window size of 5 with a shift of 1. We can do that with an additional parameter on the window called <strong>drop_remainder</strong>. And if we set this to true, it will truncate the data by dropping all of the remainders. Namely, this means it will only give us windows of five items. The good news is that converting to a NumPy array is super easy, we just have to call the .<strong>numpy</strong> method on each item in the data set. Okay, the next task is to split the data into features and labels. For each item in the list, it kind of makes sense to have all of the values except the last one to be the feature, and then the last one can be the label. Also, you would shuffle their data before training. And this is possible using the <strong>shuffle method</strong>. Finally, we can look at batching the data, and this is done with the <strong>batch method</strong>. It’ll take a size parameter, and in this case, it’s 2. So, we’ll see this output.</p><pre>OUTPUT :<br>x =  [[1 2 3 4]  [0 1 2 3]] y =  [[5]  [4]] <br>x =  [[3 4 5 6]  [4 5 6 7]] y =  [[7]  [8]] <br>x =  [[2 3 4 5]  [5 6 7 8]] y =  [[6]  [9]]</pre><p><strong>Applying On my Synthetic Data </strong>— The first step will be to create a dataset from the series using a<strong> tf.data.dataset</strong>. And we’ll pass the series to it using its <strong>from_tensor_slices</strong> method. We will then use the <strong>window method</strong> of the dataset based on our <strong>window_size</strong> to slice the data up into the appropriate windows. Each one being shifted by one-time set. We’ll keep them all the same size by setting drop remainder to true. We then flatten the data out to make it easier to work with. Once it’s flattened, it’s easy to shuffle it. You call a shuffle and you pass it the shuffle buffer. Using shuffle buffer speeds things up a bit. So for example, if you have 100,000 items in your dataset, but you set the buffer to a thousand. It will just fill the buffer with the first thousand elements, pick one of them at random. And then it will replace that with the 1,000 and first element before randomly picking again, and so on. This way with super large datasets, the random element choosing can choose from a smaller number which effectively speeds things up. The shuffled dataset is then split into the ‘<strong>x</strong>’, which are all of the elements except the last, and the ‘<strong>y’ </strong>which is the last element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2583527cfe55a83cdd7c9a72b2aa2b7c/href">https://medium.com/media/2583527cfe55a83cdd7c9a72b2aa2b7c/href</a></iframe><h3>Prediction</h3><p>We create an empty list of forecasts and then iterate over the series taking slices and window size, predicting them, and adding the results to the forecast list. We had split our time series into training and testing data taking everything before a certain time is training and the rest is validation. So we’ll just take the forecasts after the split time and load them into a NumPy array for charting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a927a7bba831c5951d457241c1e2c5f/href">https://medium.com/media/7a927a7bba831c5951d457241c1e2c5f/href</a></iframe><ol><li><strong>Using Single-Layer Neural Network — </strong>Now that we have a window datasets, we can start training neural networks with it. Let’s start with a super simple one that’s effectively a linear regression. We’ll measure its accuracy, and then we’ll work from there to improve that.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/431241c14944db9b838e13bac88b50b1/href">https://medium.com/media/431241c14944db9b838e13bac88b50b1/href</a></iframe><pre>Layer weights [array([[-0.05013938],        [-0.01954073],        <br>[ 0.0709962 ],        [-0.04240771],        [ 0.04903989],        <br>[ 0.0161289 ],        [ 0.01836954],        [ 0.04157093],        [-0.09568894],        [-0.01370953],        [ 0.0600764 ],        [-0.01854219],        [ 0.02502013],        [-0.03948223],        <br>[ 0.0480251 ],        [-0.00747724],        [ 0.11437633],        <br>[ 0.22616488],        [ 0.23641631],        [ 0.41190135]], dtype=float32), array([0.0148659], dtype=float32)]</pre><pre>Model: &quot;sequential_1&quot; _________________________________________________________________ Layer (type)                 Output Shape              Param #    ================================================================= dense_1 (Dense)              (None, 1)                 21         ================================================================= Total params: 21 Trainable params: 21 Non-trainable params: 0 _________________________________________________________________ None</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*ueU0NHDDpP5ZRqwRvCvyqA.png" /><figcaption>prediction <strong>Using Single-Layer Neural Network</strong></figcaption></figure><p>We’ll then define the model, compile it, and fit it to the data that we generated. When it’s done it will print out the layer weights. You can see the layer weights which provide the coefficients for the x values as the linear regression, as well as the bias value for their regression here. We got this by calling the <strong>get weights method</strong> on the layer. We can now plot the predictions for each of the elements in the validation split of the series, the predictions are in orange, and the actual values are in blue. Finally, we can measure the mean absolute error between the valid data and the predicted results. I got a mean absolute error of <strong>5.2505198</strong>.</p><p><strong>2. Using Deep Neural Network (DNN) </strong>— Now let’s take that to the next step with a DNN to see if we can improve our model accuracy. It’s not that much different from the linear regression model we saw earlier. And this is a relatively simple deep neural network that has three layers. So let’s unpack it line by line. I have kept my model simple with three layers of <strong>10, 10, and 1 neurons</strong>. The input shape is the size of the window and we’ll activate each layer using a relu function. We’ll then compile the model as before with a <strong>mean squared error loss function</strong> and <strong>stochastic gradient descent optimizer</strong>. Finally, we’ll fit the model over <strong>100 epochs,</strong> and after a few seconds of training, we’ll see results that look like this. It’s pretty good still. And when we calculate the mean absolute error i.e. <strong>4.567452</strong>, we’re lower than we were earlier, so it’s a step in the right direction.<br>Refer to Explore more on <a href="https://towardsdatascience.com/a-laymans-guide-to-deep-neural-networks-ddcea24847fb">DNN</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79c3b959cf05d44edcfcf0d7a529a41/href">https://medium.com/media/d79c3b959cf05d44edcfcf0d7a529a41/href</a></iframe><p>But it’s also a somewhat a stab in the dark, particularly with the optimizer function. Wouldn’t it be nice if we could pick the optimal learning rate instead of the one that we chose? We might learn more efficiently and build a better model. Now let’s look at a technique that uses callbacks. I’ve added a <strong>callback</strong> to tweak the learning rate using a <strong>learning rate scheduler</strong>. You can see that code below. This function will be called at the callback at the end of each epoch. What it will do is change the learning rates to a value based on the epoch number. So in <strong>epoch 1</strong>, the learning rate is <strong>1e-8 * 10**(1/20)</strong>. And by the time we reach the <strong>100 epoch</strong>, it’ll be <strong>1e-8 * 10**(100/20)</strong>. This will happen on each callback because we set it in the callbacks parameter of the <strong>model.fit</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ab3a814239a48e1964563e35284ae98/href">https://medium.com/media/8ab3a814239a48e1964563e35284ae98/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*d8uNqKdpZOL_HkOMqvf0oQ.png" /><figcaption>loss per epoch against the learning rate per epoch</figcaption></figure><p>After training with this, we can then plot the loss per epoch against the learning rate per epoch by using the below code, and we’ll see a chart like this. The y-axis shows us the loss for that epoch and the x-axis shows us the learning rate. We can then try to pick the lowest point of the curve where it’s still relatively stable like this, and that’s right around <strong>7 * (10 **-6)</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74133fc2d89758956b2e68a575dcf12a/href">https://medium.com/media/74133fc2d89758956b2e68a575dcf12a/href</a></iframe><p>So let’s set that to be our learning rate and then we’ll retrain. So here’s the same neural network code, and we’ve updated the learning rate, so we’ll also train it for a bit longer. Let’s check the results after training for 500 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPh3ONiUSHVZ5EHrsXV2pw.png" /><figcaption>loss per epoch against the number of epoch</figcaption></figure><p>The first inspection looks like we’re probably wasting our time training beyond maybe only 10 epochs, but it’s somewhat skewed by the fact that the earlier losses were so high. If we cropped them off and plot the loss for epochs after 10 epoch then the chart will tell us a different story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRDulFAEUs8wV1oqaCjeCQ.png" /><figcaption>zoom image</figcaption></figure><p>We can see that the loss was continuing to decrease even after 500 epochs. And that shows that our network is learning very well indeed. And the mean absolute error i.e. <strong>4.48277</strong> is significantly lower than earlier.</p><p><strong>3. Using Recurrent Neural Network (RNN) </strong>— A Recurrent Neural Network, or RNN is a neural network that contains recurrent layers. These are designed to sequentially processes the sequence of inputs. RNNs are pretty flexible, able to process all kinds of sequences including predicting text. Here we’ll use them to process the time series. We will build an RNN that contains two recurrent layers and a final dense layer, which will serve as the output. With an RNN, you can feed it in batches of sequences, and it will output a batch of forecasts. One difference will be that the full input shape when using RNNs is three-dimensional. The first dimension will be the batch size, the second will be the timestamps, and the third is the dimensionality of the inputs at each time step. To know more about RNN please visit <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/ftkzt/recurrent-neural-network-model"><em>here</em></a>.</p><p>To know more refer to these articles: <a href="https://towardsdatascience.com/understanding-rnn-and-lstm-f7cdf6dfc14e"><em>Article1</em></a>, <a href="https://www.analyticsvidhya.com/blog/2017/12/introduction-to-recurrent-neural-networks/"><em>Article2</em></a>.<br>Refer to this <a href="https://www.tensorflow.org/guide/keras/rnn"><em>link</em></a> to implement RNN in TensorFlow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wv1sAKoi79hmIXaZiqF7A.png" /><figcaption>RNN cell (Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a>)</figcaption></figure><p>So for example, if we have a window size of 30 timestamps and we’re batching them in sizes of four, the shape will be 4 times 30 times 1, and each timestamp, the memory cell input will be a four by one matrix, like above. The cell will also take the input of the state matrix from the previous step. But of course in this case, in the first step, this will be zero. Now, in some cases, you might want to input a sequence, but you don’t want to output on and you just want to get a single vector for each instance in the batch. This is typically called a <strong>sequence to vector RNN</strong>. But in reality, all you do is ignore all of the outputs, except the last one. When using <strong>Keras in TensorFlow</strong>, this is the default behavior. So if you want the recurrent layer to output a sequence, you have to specify <strong>returns sequences equals true</strong> when creating the layer. You’ll need to do this when you stack one RNN layer on top of another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6Vs3QqJPcn3SUhY8JLdIg.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p>So in my RNN, there are two recurrent layers, and the first has <strong>return_sequences=True</strong> set up. It will output a sequence which is fed to the next recurrent layer. The next layer does not have return_sequence that’s set to True, so this layer will give us output to a single dense layer.</p><p>Also, I’d like to add a couple of new layers to this, layers that use the <strong>Lambda</strong> type. So the first Lambda layer will be used to help us with our dimensionality. If you recall an RNN expects three-dimensions: <strong>batch size, the number of timestamps, and the series dimensionality.</strong> Using the Lambda, we just expand the array by one dimension. Similarly, if we scale up the outputs by 100 using the lambda function, we can help training. The default activation function in the RNN layers is <strong>tanh()</strong> which is the hyperbolic tangent activation. This outputs values between -1 and 1. Since the time series values are in that order usually in the 10s like the 40s, 50s, 60s, and 70s, then scaling up the outputs to the same ballpark can help us with learning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b12fc02c810961b73194ed861915439e/href">https://medium.com/media/b12fc02c810961b73194ed861915439e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*nHoAXkI_MFGv34jS9tQfuQ.png" /><figcaption>Prediction <strong>Using Recurrent Neural Network (RNN)</strong></figcaption></figure><p>Here’s the code to train the neural network. I’ve set the optimal learning rates and I’ve picked 400 epochs for which to train. Once it’s trained, I can use it to forecast for the validation range and plot the results. On all my plot, I can see that my prediction isn’t too bad other than this plateau, which is going to impact my MAE in a bad way. But despite that my MAE is only about <strong>6.41</strong>, so it’s not too bad.</p><p><strong>4. Using Long Short-Term Memory (LSTM) — </strong>LSTMs is the cell state that keeps a state throughout the life of the training so that the state is passed from cell to cell, timestamp to timestamp, and it can be better maintained. This means that the data from earlier in the window can have a greater impact on the overall projection than in the case of RNNs. The state can also be bidirectional so that the state can move forward and backward. To know more about LSTMs click <a href="https://www.coursera.org/lecture/nlp-sequence-models/long-short-term-memory-lstm-KXoay"><em>here</em></a>.</p><p>Refer to implement LSTMs using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM"><em>Tensorflow</em></a>.<br>Refer to this <a href="https://medium.com/mlreview/understanding-lstm-and-its-diagrams-37e2f46f1714"><em>article</em></a> to learn the structure of LSTMs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41763599e499b580af551e1ca2f73a4f/href">https://medium.com/media/41763599e499b580af551e1ca2f73a4f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*386-mDvBirBjFeAlHB_UDw.png" /><figcaption>Prediction <strong>Using Long Short-Term Memory (LSTM)</strong></figcaption></figure><p>First of all, is the <strong>tf.keras.backend.clear_session</strong>, and this clears any internal variables. That makes it easy for us to experiment without models impacting later versions of themselves. After the Lambda layer that expands the dimensions for us, I’ve added a single <strong>LSTM layer with 32 cells</strong>. I’ve also made a bidirectional to see the impact of that on a prediction. Now we will add the second layer and note that we had to set return sequences equal to true on the first one for this to work. We train on this and now we can see the chart. Now it’s tracking much better and closer to the original data. Maybe not keeping up with the sharp increase but at least it’s tracking close. It also gives us a mean average error of <strong>5.28722</strong> that’s a lot better and it’s showing that we’re heading in the right direction.</p><p><strong>5. Using Convolution — </strong>It is a Deep Learning algorithm that can take in an input image, assign importance like learnable weights and biases to various objects/aspects in the image and be able to differentiate one from the other.</p><p>To go deep in convolution, please watch this <a href="https://www.youtube.com/playlist?list=PLkDaE6sCZn6Gl29AoE31iwdVwSG-KnDzF"><strong><em>video</em></strong></a>.</p><p>Or else refer to this <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53#:~:text=A%20Convolutional%20Neural%20Network%20(ConvNet,differentiate%20one%20from%20the%20other."><strong><em>Article</em></strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a45dae04c8bac84b3a4671dcabf8bf3/href">https://medium.com/media/4a45dae04c8bac84b3a4671dcabf8bf3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*IUb8jJMk0y42jEcDVYzRJw.png" /><figcaption>Prediction <strong>Using Convolution</strong></figcaption></figure><p>One important note is that we got rid of the Lambda layer that reshaped the input for us to work with the LSTM’s. So we’re specifying an input shape on the curve 1D here. This requires us to update the <strong>windowed_datasetet</strong> helper function that we’ve been working with all along. We’ll simply use <strong>tf.expand_ dims</strong> in the helper function to expand the dimensions of the series before we process it. Now, adding two Bi-directional LSTMs Layer upon convolution layer and then passing the output sequence to the dense layer we get Mean Absolute Error around <strong>4.985901</strong>.</p><p>Now to reduce loss further, one hint is to explore the batch size and to make sure it’s appropriate for your data. So in this case it’s worth experimenting with different batch sizes. So, for example, experimented with different batch sizes both larger and smaller than the original 32, you can get better results. To know more about the appropriate batch size refer to this <a href="https://www.youtube.com/watch?v=4qJaSmvhxi8"><strong><em>video</em></strong></a>.</p><p>So by combining CNNs and LSTMs we’ve been able to build our best model yet, despite some rough edges that could be refined.</p><h3>Using Real Data ( Sunspot )</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65cxxVTLTLFUB9mbTRVmQQ.jpeg" /><figcaption>Source — <a href="https://www.cosmos.esa.int/web/cesar/rotation-period-and-sunspot-activity">cosmos.esa</a></figcaption></figure><p>I have done Sunspots prediction with the help of CSV data available on <a href="https://www.kaggle.com/robervalt/sunspots">Kaggle</a>. Check out my whole code on <a href="https://github.com/Tirth1306/Sunspots-prediction">Github</a>.</p><h3>Tirth Patel — Computer Science and Engineering Student, Nirma University.</h3><p><a href="https://www.linkedin.com/in/tirth-patel-861303171/">LinkedIn</a> | <a href="https://www.instagram.com/__txrth__/">Instagram</a> | <a href="https://github.com/Tirth1306/">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f674803c03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/time-series-and-prediction-part-2-84f674803c03">Time Series and Prediction (Part-2)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series and Prediction (Part-1)]]></title>
            <link>https://medium.datadriveninvestor.com/time-series-and-prediction-part-1-4a9b55c85276?source=rss-a4b8f5bfb324------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a9b55c85276</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Tirth1306]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 12:45:44 GMT</pubDate>
            <atom:updated>2020-07-15T23:57:11.647Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comprehensive Study of Time Series and Prediction with and without deep learning algorithms.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChHyQD77pT6ecZM8TqrklQ.jpeg" /><figcaption>Source — <a href="https://www.freepik.com/free-photo/magnifying-glass-red-stock-market-graph-paper_3095565.htm#page=1&amp;query=stock%20market%20graph&amp;position=35">freepik</a></figcaption></figure><h3>What is a Time Series?</h3><p>If a sequence of data points have time as one of their dimensions, then they can be said as time series. It is generally plotted using line charts. Examples of time series are sunspot activity, stock market behavior, ocean tides, the spread of disease, Military Planning, Marketing and Sales Forecasting, Inventory Management, Budget Analysis, etc.</p><p><a href="https://www.datadriveninvestor.com/2020/02/19/five-data-science-and-machine-learning-trends-that-will-define-job-prospects-in-2020/">Five Data Science and Machine Learning Trends That Will Define Job Prospects in 2020 | DataDrivenInvestor</a></p><p><strong>Time series data</strong> are a collection of data points recorded at a specific time, for instance, hours, months, or years. It can be found in any domain of applied science and engineering which involves time-based measurements.</p><h3>Time Series Analysis</h3><p>It comprises methods for analyzing time-series data to extract meaningful characteristics and other statistics of time series data. Now, these are just a few examples of the types of things that can be analyzed using time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*Iq3P6W3xzzeFKcHSWqS1Sg.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><ol><li><strong>FORECASTING</strong> — The first and most obvious is the prediction of forecasting based on the data. So for example with the birth and death rate chart for Japan that we showed earlier. It would be very useful to predict future values so that government agencies can plan for retirement, immigration, and other societal impacts of these trends.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*3iynrAC6p-nXQp8ZQXeXSg.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p><strong>2. IMPUTATION </strong>— In some cases, you might also want to project back into the past to see how we got to where we are now. This process is called imputation. Thus, by analyzing past data we can estimate where we stand now and how to improve more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPIBfyYxJefPAlshzzwimQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT0TGIliR5gRaNm6_0vEMA.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p>Or you might simply want to fill in holes in your data for what data doesn’t already exist. For example, in Moore’s law chart, there is no data for some years because there are no chips released in those years, and you can see the gaps here. But with imputation, we can fill them up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*HKu9bVHyhYl65FQauXMEcQ.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p><strong>3. DETECTION — </strong>Time series prediction can be used to detect anomalies. For example, in website logs, so that you could see the potential denial of service attacks showing up as a spike on the time series like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIoFeVyxgADkDT2lNXgP4A.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p><strong>4. Pattern Matching</strong> — The other option is to analyze the time series to spot patterns in them that determine what generated the series itself. A classic example of this is to analyze sound waves to spot words in them which can be used as a neural network for speech recognition. Here, for example, you can see how a sound wave is split into words. Using machine learning, it becomes possible to train a neural network based on the time series to recognize words or subwords.</p><p>To know more refer to this <a href="https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc4.htm">link</a>.</p><h3>Components of Time Series</h3><ol><li><strong>Trend</strong></li></ol><p>The long-term pattern shown by a time series is called a trend. A trend can be negative or positive depending on whether the time series exhibits a decreasing pattern or an increasing pattern. Also, we can say a time series has a downward trend if it has an overall negative growth and for an upward trend, it shows overall negative growth. If a time series fail to show a decreasing or increasing pattern then the series is stationary in the mean.</p><p><strong>2. Seasonality</strong></p><p>Many phenomena that produce time-series data have seasonality. It is a component of a time series in which the data goes under regular and predictable changes that recur in regular periods such as months, a year, or during the same quarter every year. For instance, in the case of sales data of automobile companies, usually, the automobile companies give a huge discount at the time of Festivals, so their sales increase during that period of time. And this happens every year.</p><p><strong>3. Cyclic</strong></p><p>The data is said to have a cyclic component when it exhibit rises and falls that are not of a fixed period. The life of a cycle depends on the type of industry or business being examined.</p><p><strong>4. Irregularity</strong></p><p>This segment is unpredictable. Every event has some unpredictable segment that makes it a random variable. It results from short-term variations in a series that are inconsistent and in some cases not predictable. This segment does not follow any trend or seasonality.</p><p>For extra Knowledge refer to these Articles: <a href="https://www.abs.gov.au/websitedbs/d3310114.nsf/home/time+series+analysis:+the+basics#:~:text=An%20observed%20time%20series%20can,unsystematic%2C%20short%20term%20fluctuations).">Article1</a>, <a href="https://www.toppr.com/guides/business-mathematics-and-statistics/time-series-analysis/components-of-time-series/">Article2</a>.</p><h3>Producing Synthetic Time-Series Data</h3><p><strong>First import the necessary libraries:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf9d5797b028f815e6480ec61c835cd2/href">https://medium.com/media/bf9d5797b028f815e6480ec61c835cd2/href</a></iframe><p><strong>Second, defining the necessary functions needed for generating synthetic time-series data.</strong></p><p><strong>trend</strong> () — used to set the trend for the time-series.<br><strong>seasonal_pattern()</strong> — contains a mixed expression used to get the synthetic values for time-series.<br><strong>seasonality()</strong> — used to give seasonality(regular and predictable changes that recur in the regular intervals) to our data.<br><strong>noise() </strong>— adding random noise to our seasonal data.<br><strong>plot_series() — </strong>plotting the synthetically generated data on the graph using the matplotlib library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da7597addbb14ae0f847d814111cb259/href">https://medium.com/media/da7597addbb14ae0f847d814111cb259/href</a></iframe><p><strong>Third, declaring and passing your appropriate value to the functions to plot your desired synthetic time-series.</strong></p><p>Making a randomly generated NumPy array for 4 years with the seasonality of 1 year. Also, setting the baseline as 10 and amplitude as 40 with a noise level of 5 units. Then, finally plotting my synthetic time-series data. Change the values of these variables and try to generate your own synthetic time-series data. Below is my generated time-series data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1d5f13abaa303db72e9a94b5bec19a/href">https://medium.com/media/9e1d5f13abaa303db72e9a94b5bec19a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*b8sw8I4YflLJxR5tHzTPsQ.png" /><figcaption>My synthetically generated time series</figcaption></figure><h3>Train, Validation, and Test sets</h3><p>The most important part of any prediction is how do you measure performance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwsER4T4o5Bcx2aPpSVOeQ.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCIw6ecnJALaFsSRNh2D-g.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><ol><li><strong>Fixed Partition</strong> — To measure the performance of our forecasting model, we typically want to split the time series into a training period, a validation period, and a test period. If the time series has some seasonality, you generally want to ensure that each period contains a whole number of seasons. For example, one year, or two years, or three years, if the time series has a yearly seasonality. Next, you’ll train your model on the training period, and you’ll evaluate it on the validation period. Here’s where you can experiment to find the right architecture for training and work on it and your hyperparameters until you get the desired performance, measured using the validation set. Often, once you’ve done that, you can retrain using both the training and validation data. And then test on the test period to see if your model will perform just as well. And if it does, then you could take the unusual step of retraining again, using also the test data. But why would you do that? Well, it’s because the test data is the closest data you have to the current point in time and as such it’s often the strongest signal in determining future values. If your model is not trained using that data, too, then it may not be optimal.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYc17eM2SBL190gRWfqO4w.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p><strong>2. Roll-Forward Partitioning — </strong>In this, we start with a short training period, and we gradually increase it, say by one day at a time, or by one week at a time. At each iteration, we train the model on a training period. And we use it to forecast the following day, or the following week, in the validation period. You could see it as doing fixed partitioning a number of times, and then continually refining the model as such.</p><p>Here is the code for splitting the data into train, validation, and test. I have divided my data from 1000 days. So, my test set contains 1000 days, and the validation set contains the remaining days. You can also see the train and validation data below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a60ec708cd8c394f8433cbdfc38f70/href">https://medium.com/media/b2a60ec708cd8c394f8433cbdfc38f70/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*wMKMs0t6J91kg8H9eg4Glw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*6DxWbVnOuhClzu7sJDD2Tw.png" /><figcaption>Left Image: Training set and Right Image: Validation set.</figcaption></figure><h3>Metrics for evaluating performance</h3><p>Once we have a model and a period, then we can evaluate the model on it, and we’ll need a metric to calculate their performance.</p><ol><li><strong>Error = Forecasts — Actual<br></strong>So let’s start simply by calculating the errors, which is the difference between the forecasted values from our model and the actual values over the evaluation period.</li><li><strong>Mean Square Error (mse) = np.square(errors).mean()<br></strong>It is the most common metric to evaluate the forecasting performance of a model where we square the errors and then calculate their mean. Well, why would we square it? Well, the reason for this is to get rid of negative values. So, for example, if our error was two above the value, then it will be two, but if it were two below the value, then it will be minus two. These errors could then effectively cancel each other out, which will be wrong because we have two errors and not none. But if we square the error of value before analyzing, then both of these errors would square to four, not canceling each other out and effectively-being equal.</li><li><strong>Root Mean Aquare Error (rmse) = np.sqrt(mse)<br></strong>And if we want the mean of our errors’ calculation to be of the same scale as the original errors, then we just get its square root, giving us a root means squared error or rmse.</li><li><strong>Mean Absolute Error (mae) = np.abs(error).mean()<br></strong>Another common metric and one of my favorites is the mean absolute error or mae, and it’s also called the main absolute deviation or mad. And in this case, instead of squaring to get rid of negatives, it just uses their absolute value. This does not penalize large errors as much as the mse does. Depending on your task, you may prefer the mae or the mse. For example, if large errors are potentially dangerous and they cost you much more than smaller errors, then you may prefer the mse. But if your gain or your loss is just proportional to the size of the error, then the mae may be better.</li><li><strong>Mean Absolute Percentage Error (mape) = np.abs(error/x_valid).mean()<br></strong>This is the mean ratio between the absolute error and the absolute value, this gives an idea of the size of the errors compared to the values.</li></ol><p>To explore more methods, refer to this <a href="https://scikit-learn.org/stable/modules/model_evaluation.html#median-absolute-error">link</a>.</p><h3>NORMAL Forecasting Methods (Without applying ML)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JgIo1mD5oXD4PaYsNIJlQ.png" /></figure><ol><li><strong>Naive Based Approach — </strong>In this approach, we take the last value and assume that the next value will be the same one, and this is called naive forecasting. I’ve zoomed in to a part of the data set here to show that in action. This baseline can be considered as a baseline and use to compare the different approaches. With the help of Keras functions, I got <strong>Mean Absolute Error (MAE)</strong> as <strong>5.9379086.</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfab018de07053302822bfbb6774ecfa/href">https://medium.com/media/bfab018de07053302822bfbb6774ecfa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f1c6a746e6f7d16c5bb8b2dbbca65b4/href">https://medium.com/media/9f1c6a746e6f7d16c5bb8b2dbbca65b4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbyelkfD9q2i5N13b2nI2A.png" /><figcaption>Source — <a href="https://www.coursera.org/learn/tensorflow-sequences-time-series-and-prediction">Coursera</a></figcaption></figure><p><strong>2. Moving Average<br></strong>A common and very simple forecasting method is to calculate a moving average. The idea here is that the yellow line is a plot of the average of the blue values over a fixed period called an averaging window, for example, 30 days. Now this nicely eliminates a lot of the noise and it gives us a curve roughly emulating the original series, but it does not anticipate trend or seasonality. Depending on the current time i.e. the period after which you want to forecast for the future, it can actually end up being worse than a naive forecast. In this case, I got a <strong>Mean Absolute Error</strong> of about <strong>7.14</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa314e02766b8be29c4ca69df5b36368/href">https://medium.com/media/fa314e02766b8be29c4ca69df5b36368/href</a></iframe><p><strong>3. Moving Average and differencing</strong></p><p>One method to avoid this is to remove the trend and seasonality from the time series with a technique called differencing. So instead of studying the time series itself, we study the difference between the value at time T and the value at an earlier period. Depending on the time of your data, that period might be a year a day, a month, or whatever.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dbb869a2cd79fd0940ff535d57ea5b0/href">https://medium.com/media/0dbb869a2cd79fd0940ff535d57ea5b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*JlhJUiJwL7q-3GJWEEqS4Q.png" /><figcaption>Subtracting past year value from current and then applying moving average.</figcaption></figure><p>Let’s look at a year earlier. So for this data, at time T minus 365, we’ll get this difference time series which has no trend and no seasonality. We can then use a moving average to forecast this time series which gives us these forecasts. But these are just forecasts for the difference time series, not the original time series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd0cd7b816c1c8ea17df4a5b12836cef/href">https://medium.com/media/cd0cd7b816c1c8ea17df4a5b12836cef/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*AglyhHihTBptqHnkCQxnHQ.png" /><figcaption>prediction using <strong>Moving Average and differencing</strong></figcaption></figure><p>To get the final forecasts for the original time series, we just need to add back the value at time T minus 365, and we’ll get these forecasts. They look much better, don’t they? If we measure the <strong>mean absolute error</strong> on the validation period, we get about <strong>5.9032416 error.</strong></p><p><strong>Apparently, with this approach, we’re not too far from the optimal. Keep this in mind before we rush into deep learning in my second part of this article, normal approaches sometimes can work just fine.</strong></p><h3>Tirth Patel — Computer Science and Engineering Student, Nirma University.</h3><p><a href="https://www.linkedin.com/in/tirth-patel-861303171/">LinkedIn</a> | <a href="https://www.instagram.com/__txrth__/">Instagram</a> | <a href="https://github.com/Tirth1306/">Github</a></p><p><strong>Gain Access to Expert View — </strong><a href="https://datadriveninvestor.com/ddi-intel"><strong>Subscribe to DDI Intel</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a9b55c85276" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/time-series-and-prediction-part-1-4a9b55c85276">Time Series and Prediction (Part-1)</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>