<?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 RishiRajak on Medium]]></title>
        <description><![CDATA[Stories by RishiRajak on Medium]]></description>
        <link>https://medium.com/@rishirajak?source=rss-cf9bc46d1a6b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z3qX6BUfBuI43mlQgCe8vA.png</url>
            <title>Stories by RishiRajak on Medium</title>
            <link>https://medium.com/@rishirajak?source=rss-cf9bc46d1a6b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 06 Jun 2026 01:26:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishirajak/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[Bewitching]]></title>
            <link>https://rishirajak.medium.com/bewitching-6c4acd245187?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c4acd245187</guid>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[love]]></category>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[poetry-on-medium]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Mon, 29 May 2023 07:07:48 GMT</pubDate>
            <atom:updated>2023-05-29T16:42:35.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ux1yDeVY9k_kaX7ukkfQHQ.png" /><figcaption>Photo by Pramod Tiwari on Unsplash</figcaption></figure><p>Suddenly something has happened…</p><p>I started seeing colours in my black and white life. I have waited so long, and now I know that it was all worth it.</p><p>If I may compare you,</p><p>I would compare you to the moon for your soothing brightness.</p><p>I would compare you to the stars for completing all my wishes.</p><p>I would compare you to the sea for the depths you have in your eyes.</p><p>I would compare you to sunflowers for your calming smile.</p><p>I would compare you to Lotuses for your piousness.</p><p>I would compare you to the penance of a sage for the hardships I endured.</p><p>And I know you will always win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c4acd245187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ocean Eyes]]></title>
            <link>https://rishirajak.medium.com/ocean-eyes-4d5a8692c594?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d5a8692c594</guid>
            <category><![CDATA[musé]]></category>
            <category><![CDATA[oceans]]></category>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[eyes]]></category>
            <category><![CDATA[poetry-on-medium]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 19:25:16 GMT</pubDate>
            <atom:updated>2022-12-21T19:25:16.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNLk7M7Ftk3Fe8yQZnS5ng.png" /><figcaption>Photo by Kat J on Unsplash</figcaption></figure><p><em>Would you believe if I say,</em></p><p><em>I have seen depth of ocean in her eyes,</em></p><p><em>that I have died and reborn in the moment.</em></p><p><em>Would you believe if I say,</em></p><p><em>I was hypnotized or maybe I am,</em></p><p><em>that she can do magic with her eyes.</em></p><p><em>I have seen her dancing under moon,</em></p><p><em>In a cursed night.</em></p><p><em>Would you believe if I say,</em></p><p><em>she can do a lot with her eyes.</em></p><p><em>For her, it was a moment,</em></p><p>…</p><p><em>And I lived another life.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5a8692c594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lost My Smile]]></title>
            <link>https://rishirajak.medium.com/lostmysmile-2ec292f6ca56?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec292f6ca56</guid>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[agitation]]></category>
            <category><![CDATA[the-power-of-poetry]]></category>
            <category><![CDATA[solitude]]></category>
            <category><![CDATA[love]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Sun, 31 Jul 2022 15:44:02 GMT</pubDate>
            <atom:updated>2022-07-31T19:04:28.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*0q3MdGqo7EKluQAzymA9Sg.jpeg" /><figcaption>src: Isalovesphotography</figcaption></figure><p><em>This has happened so many times; why do love and pain always rhyme?<br>Build a wall around, <br>Make sure not to hear a sound.<br>Hide your emotions deep down, <br>Trusting people will always get you drowned.<br>When will I see the light?<br>Will anyone ever be right?<br>Don’t get too close,<br>I could only trust to lose.<br>Once loved unconditionally. <br>Now, I have lost my smile.</em></p><p><a href="https://medium.com/the-power-of-poetry/the-power-of-poetry-3d8dfd2beecc">The Power of Poetry</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec292f6ca56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Urge]]></title>
            <link>https://rishirajak.medium.com/the-urge-e17c7d801e01?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e17c7d801e01</guid>
            <category><![CDATA[deadly-sins]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[the-power-of-poetry]]></category>
            <category><![CDATA[love]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 13:38:58 GMT</pubDate>
            <atom:updated>2022-03-21T16:13:03.577Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this small piece of work, I have tried portraying the seven deadly sins through the view of a person who is overwhelmed with different kinds of emotions.</blockquote><figure><img alt="The image dictates seven deadly sins in physical form." src="https://cdn-images-1.medium.com/max/1024/1*dWaZrFvhLPICd4rFak-RUg.jpeg" /><figcaption>Credits: cdcblanc. Source: Deviantart.</figcaption></figure><p>A stone hitting the surface of calm water,<br>I am filled with ripples.<br>What have you done to me?</p><p>A dying knight on a war ground,<br>I am filled with a sense of Pride.<br>What have you done to me?</p><p>An Oasis in the middle of a desert.<br>I am filled with thirst.<br>What have you done to me?</p><p>The way the Earth craves rain,<br>I feel insatiable.<br>What have you done to me?</p><p>Rising from ashes of wrath,<br>I burn myself like a Pheonix.<br>What have you done to me?</p><p>The unsatisfied urge,<br>I am filled with greed.<br>What have you done to me?</p><p>A lazy river or a soothing breeze,<br>I am at ease.<br>I feel all the sins,<br>What have you done to me?</p><p><a href="https://medium.com/the-power-of-poetry/the-power-of-poetry-3d8dfd2beecc">The Power of Poetry</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e17c7d801e01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning for Marble Defect Classification]]></title>
            <link>https://rishirajak.medium.com/deep-learning-for-marble-defect-classification-f7928d077056?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7928d077056</guid>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[industrial]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[marbles]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 08:56:04 GMT</pubDate>
            <atom:updated>2022-03-20T08:56:04.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzIpZyuyckNGBr8rlffSUQ.jpeg" /></figure><p>Why building a model for defect detection? <br>Some would say that because after all, we can see it with our own eyes.</p><p>Let me guide you through “Why”.<br>Here are the reasons:</p><ol><li>Not everything goes through the inspector&#39;s eye.</li><li>Saving consumption of power on wasted material.</li><li>Add a middle layer of quality inspection.</li><li>Store the defect data for further analysis.</li></ol><p>It can be implemented as an IoT application for Marble Industry. A lot of industries have been started adopting IoT services.</p><p>So, without delay let’s get started. Here are the contents of the article.</p><p><strong>Content:</strong></p><ol><li>About data</li><li>Imports</li><li>Data Generators and Augmentation</li><li>Model Architecture</li><li>Evaluation</li><li>Prediction</li></ol><p><strong>About Dataset</strong></p><p>The dataset folder has two folders train and test. In train and test folders there are 4 classes namely: <strong>crack</strong>, <strong>dot</strong>, <strong>good </strong>and <strong>joint</strong>.<br>There are a total of 2249 files in the train folder and 688 files in the test folder. The images are 256 x 256 in dimension.<br>The images are cropped from the original <a href="https://www.kaggle.com/wardaddy24/marble-surface-anomaly-detection">dataset</a>. There is no overlapping among the cropped images and the aspect ratio is maintained while generating the crops. Download the dataset <a href="https://www.kaggle.com/wardaddy24/marble-surface-anomaly-detection-2">here</a>. Please upvote their work.</p><p><strong>Data Import</strong></p><p>We will start by importing the required libraries and the main directory paths.</p><pre><strong>import</strong> tensorflow <strong>as</strong> tf<br><strong>import</strong> cv2<br><strong>import</strong> numpy <strong>as</strong> np <em># linear algebra</em><br><strong>import</strong> pandas <strong>as</strong> pd <em># data processing, CSV file I/O (e.g. pd.read_csv)</em><br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> os</pre><p>Here’s the path to the train and test directory. In your case choose the path directed to your notebook.</p><pre>train_dir <strong>=</strong> &quot;marble/train/&quot;<br>test_dir <strong>=</strong> &quot;marble/test/&quot;</pre><p><strong>Visualizing Images</strong></p><p>Let’s create functions to visualize images. For example to fetch an image through a given path. Just to check the size.</p><pre><strong>def</strong> get_image(path):<br>    img <strong>=</strong> cv2<strong>.</strong>imread(path)<br>    print(img<strong>.</strong>shape)<br>    plt<strong>.</strong>imshow(img)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*j2tIBH24AYDYwJTFaLwVvQ.png" /><figcaption>Cracked Marble</figcaption></figure><p><strong>Image Data Generator</strong></p><p>It generates batches of tensor image data with real-time data augmentation. There several parameters to pass in according to your need. Please check the documentation presented <a href="https://keras.io/api/preprocessing/image/#imagedatagenerator-class">here</a>.</p><p>Now, we will build our Image Data Generator which will be used to generate train and valid tests directly from the main directory by using <a href="https://keras.io/api/preprocessing/image/#flowfromdataframe-method">Flow From Directory</a>. We will also apply some image augmentation to our generator. Rotation range of 20 degrees — rotates images randomly, set Horizontal and Vertical flip to be True, shifts in width and height, and the fill mode to be nearest. After initializing the generator, we will set the target size of each image to be 48x48(WxH). Each image is required in color so we will set the color mode to be ‘RGB’. Batch size is the number of extractions from each subfolder. We will fit this generator for both sets i.e. train and valid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e3b8650af333ea8f84cd72e26fd9198/href">https://medium.com/media/7e3b8650af333ea8f84cd72e26fd9198/href</a></iframe><pre>traingen <strong>=</strong> datapreprocessing(train_dir,20)<br>validgen <strong>=</strong> datapreprocessing(test_dir,20)</pre><p>Output:</p><pre>Found 2249 images belonging to 4 classes.<br>Found 688 images belonging to 4 classes.</pre><p>Let’s create a dictionary that contains labels for each class and keys for them. Later it will be used to fetch class names.</p><pre>labelnames <strong>=</strong> traingen<strong>.</strong>class_indices<br>labelnames</pre><p>Now, we will build a data frame that contains an absolute path to each image and its label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e4082f8743a1445ba3e2b9316ff4ba/href">https://medium.com/media/c7e4082f8743a1445ba3e2b9316ff4ba/href</a></iframe><pre><em>#Create Train Dataframe as repository of paths and labels.</em><br>valid <strong>=</strong> getdata(test_dir)</pre><p><strong>Visualizing Images</strong></p><p>Let’s create a function to visualize images. For example to fetch n number of images of good marble from data frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href">https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href</a></iframe><p>This will be used later to visualize if the predictions are correct or not.</p><p>To visualize images from the generator, we will create another function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href">https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href</a></iframe><pre>visualize_gen(traingen)</pre><p>Images look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*2-DcB2dZzKJZ6Db71u9o4w.png" /><figcaption>Marble images from the train generator</figcaption></figure><pre>#Get the shape of images<br>input_shape <strong>=</strong> traingen<strong>.</strong>image_shape<br>input_shape</pre><p><strong>Model Architecture</strong></p><p>The model will contain:</p><ol><li>Two Conv2d layers</li><li>Two Dense Layers</li><li>Two MaxPoolinig and Dropout Layers</li></ol><p>Conv2d layers will extract features from the images in pieces, Dense layer will tune up the weights for them. MaxPooling2D layer will reduce the dimensionality for easier computation and Dropout layers will avoid the overfitting of the model.</p><p>The model summary is given below:</p><pre>Model: &quot;sequential&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>layer1 (Conv2D)              (None, 48, 48, 8)         224       <br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 24, 24, 8)         0         <br>_________________________________________________________________<br>dropout (Dropout)            (None, 24, 24, 8)         0         <br>_________________________________________________________________<br>layer2 (Conv2D)              (None, 24, 24, 8)         584       <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 12, 12, 8)         0         <br>_________________________________________________________________<br>flatten (Flatten)            (None, 1152)              0         <br>_________________________________________________________________<br>layer5 (Dense)               (None, 128)               147584    <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 128)               0         <br>_________________________________________________________________<br>output (Dense)               (None, 4)                 516       <br>=================================================================<br>Total params: 148,908<br>Trainable params: 148,908<br>Non-trainable params: 0</pre><p>Use the below code for building architecture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ae67d20e949490b513c18a3f2e20697/href">https://medium.com/media/4ae67d20e949490b513c18a3f2e20697/href</a></iframe><pre>model01 <strong>=</strong> imageclf2(input_shape)</pre><p><strong>Compile and Evaluate</strong></p><p>To compile the model, we will use :</p><blockquote>loss <strong>= </strong>categorical_crossentropy<br>optimizer <strong>= Adam</strong><br>metrics <strong>= </strong>accuracy<br>callback = Earlystopping</blockquote><p>Categorical cross-entropy as loss function because the task is multi-class classification. We will also use EarlyStopping callback to call the function back if it doesn’t improve after some epochs. We will do this by passing patience as a parameter to the callback.</p><p>Here’s the full code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb0931378d63317e213f37486910d73/href">https://medium.com/media/3cb0931378d63317e213f37486910d73/href</a></iframe><p>Compile and evaluate the model on the validation dataset.</p><pre>model_com01 <strong>=</strong> compiler2(model01,traingen,validgen,100)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ElE-y71m-3CaHYBt0F1mtg.png" /><figcaption>Accuracy Curve</figcaption></figure><pre>Restoring model weights from the end of the best epoch.<br>113/113 [==============================] - 5s 42ms/step - loss: 0.6710 - <strong>accuracy: 0.7617</strong> - val_loss: 0.6584 - <strong>val_accuracy: 0.7791</strong></pre><h4>Get Prediction and visualize the output.</h4><p>Let’s try to predict any image available in the validation data set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e9d4a5d5987f4c5484a7574e5fedb3a/href">https://medium.com/media/2e9d4a5d5987f4c5484a7574e5fedb3a/href</a></iframe><p>Pass in n any number between 0–19 because there are 20 images from each folder since we specified 20 as batch size during Image Generator initialization.</p><pre>get_predictions(11)</pre><p>Output:</p><pre>array([2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*sQIUqok1In20NQ3jaI--BQ.png" /><figcaption>Predicted Image as Good</figcaption></figure><p>Let&#39;s check if other good images are like this or not.</p><pre><em>#Visualise Predictions</em><br>get_n_images(6,valid,&quot;good&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*kKpdnr-p2E1W7UTS0SI2fQ.png" /><figcaption>Good Marble Images</figcaption></figure><ul><li>The model has predicted that there is no deformation which is true.</li></ul><p>Save the model!</p><pre><em># save the model to disk</em><br>model <strong>=</strong> model_com01[0]<br>model<strong>.</strong>save(&#39;saved_models/MarbleModel.tf&#39;)</pre><p><strong>Thankyou!</strong> for reading my story. Don&#39;t forget to try different hyperparameters and see if the score can be improved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7928d077056" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classifying Flower through Sequential-API-Deep Learning.]]></title>
            <link>https://medium.com/analytics-vidhya/classifying-flower-through-sequential-api-deep-learning-192a2c28959b?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/192a2c28959b</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[sequential]]></category>
            <category><![CDATA[flowers]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 08:55:35 GMT</pubDate>
            <atom:updated>2022-03-20T08:55:35.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bx1voYr3SzrYka-gJPMAxg.jpeg" /></figure><p>Classifying different types of flowers based on their images drawn from different datasets. Some classes are very narrow, containing only a particular sub-type of flower (e.g. pink primroses) while other classes contain many sub-types (e.g. wild roses).</p><h3><strong>Task</strong></h3><p>Classification of flowers is a difficult task because there are flowers that look almost the same and flowers that are the same but look different, mainly because of their colors. Consider a rose for the example, it comes in 3 different colors commonly. So, the model has to be perfect in predicting color as well as shape.</p><p>For our purpose, let’s build a flower classifier from scratch using Sequential API available in Keras-Tensorflow. Import the required libraries.</p><pre><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> csv<br><strong>import</strong> imageio<br><strong>import</strong> os<strong>,</strong> shutil<br><strong>from</strong> tensorflow <strong>import</strong> keras</pre><h3><strong>Dataset</strong></h3><p>You can download the flower dataset from <a href="https://www.kaggle.com/spaics/hackathon-blossom-flower-classification/code">here</a>, it contains 102 types of different flowers. We will select the first 10 labels for the classification. Since data is already present inside the subfolders named as labels, you can use Flow-From-Directory and specify the main directory path to it. I have used Flow From DataFrame because it will help you fetching images with absolute path.</p><p>First, let’s take a look at the image from the training data set. The below code lists absolute paths of images available in the training dataset.</p><pre>#lists dirs for train folder<br>label_1 <strong>=</strong> &quot;flower_data/flower_data/train/1&quot;<br>dirs_label_1 <strong>=</strong>  os<strong>.</strong>listdir(label_1)</pre><p>Then, we create a function that can fetch us a single image of any image absolute path.</p><pre><em>#visualise a flower</em><strong><br>def</strong> get_image(path):    <br>    flower <strong>=</strong> imageio<strong>.</strong>imread(path)<br>    <em>print(flower.shape)</em><br>    <em>plt.figure(figsize=(5,5))</em><br>    plt<strong>.</strong>imshow(flower)</pre><p>Now to fetch the image, we need to concatenate the folder path with the image name and then pass it to the <em>get_image </em>function.</p><pre>img <strong>=</strong> &#39;image_06736.jpg&#39;<br>label_path <strong>=</strong> label_1<strong>+</strong>&#39;/&#39;<strong>+</strong>img<br>label_path</pre><p>Here’s how the path will look.</p><pre>&#39;flower_data/flower_data/train/1/image_06736.jpg&#39;</pre><p>Extract Image:</p><pre>get_image(label_path)</pre><p>Output Image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Uea61lTn8YFGQCxCUJznHg.png" /><figcaption>Pink Primrose</figcaption></figure><p>Dataset also contains a .jason file from where you can get the dictionary of flowers and index. Just copy paste and create a Dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd3d035c5252147bf306ec284a27f025/href">https://medium.com/media/fd3d035c5252147bf306ec284a27f025/href</a></iframe><p>Remember that we are going to use only 20 of them, let’s select the first 20.</p><pre>#select first 10<br>few_flowers <strong>=</strong> {}<br><strong>for</strong> i <strong>in</strong> range(1,11):<br>    few_flowers[str(i)]<strong>=</strong>flower_names[str(i)]<br>few_flowers</pre><p>To store the image abs path and labels, we create a function that will first create an empty data frame with absolute pathnames and image labels columns. And then populates it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccfa64d9f0204d5554cc3ec34bf1d0fc/href">https://medium.com/media/ccfa64d9f0204d5554cc3ec34bf1d0fc/href</a></iframe><p>To get train data, specify the path. The path should look like this.</p><pre>path <strong>=</strong> &quot;flower_data/flower_data/train&quot;<br>num_folders = 10</pre><p>The number of subfolders is 10 because we want only 10 of the labels. If you want to build with a complete dataset then use <em>flower_names </em>as a dictionary and 102 as num_folders.</p><p>We have train and valid sets:</p><pre>train <strong>=</strong> getdata(folder_path<strong>=</strong>path,num_subfolders<strong>=</strong>num_folders)<br>valid <strong>=</strong> getdata(folder_path<strong>=</strong>valid_path,num_subfolders<strong>=</strong>num_folders)</pre><h3><strong>Visualize Images</strong></h3><p>To get n number of images from the data frame we have created and visualize it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href">https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href</a></iframe><pre>get_n_images(10,train,&quot;english marigold&quot;)</pre><p>Outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*TlbkY5lR3X1MMi-F5P0ADQ.png" /><figcaption>English Marigold</figcaption></figure><p>Images are having different sizes which we need to take care of during building the Image Generator.</p><p>Let&#39;s check the proportion of flowers available to us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b7070e08b776ecd6b764c2a78df3b43/href">https://medium.com/media/4b7070e08b776ecd6b764c2a78df3b43/href</a></iframe><p>The above function takes in a data frame and a dictionary of flowers to build the horizontal bar graph.</p><pre>plotHbar(train,few_flowers) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*SzuamEGULGQQqvhCjX5IkA.png" /></figure><p>It seems the proportion of the labels are almost the same. Train data is not highly skewed and can be used without any sampling techniques.</p><p>Valid Set:</p><pre>plotHbar(valid,few_flowers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Oi3TOGLLlGZHxDQT6lcxWA.png" /></figure><p>The valid set will be used for validation and not training, proportion doesn&#39;t matter here. The model will train on the train set get experienced over it and then evaluate on the basis of the validation set.</p><h3><strong>Data Preprocessing</strong></h3><p>In this section, we will define a function that can take <strong>data frame </strong>and <strong>batch size</strong> as input and build the <strong>Image Data Generator</strong> through the flow_from_dataframe method. Image Generator takes in different parameters and on the basis of that it generates Images. Parameters are rescaling, flips, rotations, shear range, etc. Check <a href="https://keras.io/api/preprocessing/image/#imagedatagenerator-class">Keras Image Data Generator</a> documentation for more details.</p><p>We will use ImageDataGenerator.flow_from_dataframe() for our purpose. It will take some parameters like:</p><pre>x_col=&quot;filename&quot;    #independent variable<br>y_col=&quot;class&quot;       #dependent/target variable<br>target_size=(150, 150)    #Normalise the size<br>color_mode=&quot;rgb&quot;          #Color Mode to red green blue<br>class_mode=&quot;categorical&quot;  #Multiclass classification<br>batch_size=1              #Images to fetch from each folder<br>shuffle=True              # Shuffle images in the dataframe</pre><p>Also, set the rescaling in ImageDataGenerator to normalize values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25eaae17a16368d130cbdda15b52ba63/href">https://medium.com/media/25eaae17a16368d130cbdda15b52ba63/href</a></iframe><p>Generate sets:</p><pre>train_generated <strong>=</strong> datapreprocessing(train,bsize<strong>=</strong>1) <br>valid_generated <strong>=</strong> datapreprocessing(valid,bsize<strong>=</strong>1)</pre><p>The below code visualizes the images generated by Generator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href">https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*obpqD0GQ90LdYUfzjSVUdw.png" /><figcaption>Some Flowers Read by Generator</figcaption></figure><h3><strong>Classifier Model</strong></h3><p>Our model will have 10 layers i.e. 4 Conv2D each followed by MaxPooling2D and 2 Fully Connected Dense Layers. You can check the parameters required by <a href="https://keras.io/api/layers/convolution_layers/convolution2d/">Conv2D </a>and <a href="https://keras.io/api/layers/core_layers/dense/">Dense </a>layer in the documentation. <br>We will build the model with:</p><pre>Model: &quot;sequential_2&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>layer1 (Conv2D)              (None, 75, 75, 16)        1744      <br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 37, 37, 16)        0         <br>_________________________________________________________________<br>layer2 (Conv2D)              (None, 37, 37, 32)        4640      <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 18, 18, 32)        0         <br>_________________________________________________________________<br>layer3 (Conv2D)              (None, 18, 18, 64)        18496     <br>_________________________________________________________________<br>max_pooling2d_2 (MaxPooling2 (None, 9, 9, 64)          0         <br>_________________________________________________________________<br>layer4 (Conv2D)              (None, 9, 9, 64)          36928     <br>_________________________________________________________________<br>max_pooling2d_3 (MaxPooling2 (None, 4, 4, 64)          0         <br>_________________________________________________________________<br>flatten_2 (Flatten)          (None, 1024)              0         <br>_________________________________________________________________<br>layer5 (Dense)               (None, 128)               131200    <br>_________________________________________________________________<br>output (Dense)               (None, 10)                1290      <br>=================================================================<br>Total params: 194,298<br>Trainable params: 194,298<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>Kernel size and Strides for layers are given in the code for the model architecture below. Padding is ‘same’ throughout the Conv layers. Strides indicate the steps of conversion during filtering and Padding is the padded area to be considered or not.</p><p>Stride Visualisation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*1VJDP6qDY9-ExTuQVEOlVg.gif" /><figcaption>Source: Wikimedia Commons</figcaption></figure><p>Let’s build the classifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ffed746c318413cf0298191901b4362/href">https://medium.com/media/6ffed746c318413cf0298191901b4362/href</a></iframe><p>To compile the model, use <em>Adam </em>as Optimiser with <em>learning_rate = 0.0001</em>, loss = <em>categorical_crossentropy,</em> and <em>accuracy </em>as metrics<em>. </em>I have used Callbacks to save computing time but it is optional and depends on your rig. The function will return compiled model and history associated with it. It will also plot the accuracy curves.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38ed8ace757ac8816763dab7352da4e4/href">https://medium.com/media/38ed8ace757ac8816763dab7352da4e4/href</a></iframe><p><strong>Model Fit &amp; Evaluation</strong></p><p>Model is built using the build function described above and compiled through <em>compileModel</em>. The input shape of the data is (150,150,3) representing height, width, and channel. The model is being evaluated on the validation set.</p><pre>model <strong>=</strong> imageclf2(input_shape<strong>=</strong>input_shape)</pre><pre>model_compiled <strong>=</strong> compiler2(model02,train_generated,<br>                           valid_generated,50,32)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*sJo1Z7qkYLSojccpA50J5Q.png" /><figcaption>Accuracy Curve</figcaption></figure><p>Save your model.</p><pre><em># save the model to disk</em><br>model <strong>=</strong> model_compiled[0]<br>model<strong>.</strong>save(&#39;saved_models/flowerModel&#39;)</pre><h3><strong>Endnote.</strong></h3><p>I have used Keras Auto Tuner to find the best hyperparameters. You can refer to <a href="https://medium.com/sicara/hands-on-hyperparameter-tuning-with-keras-tuner-aeef4a58509">Auto Tuner</a> for details.</p><p><strong>Thank you</strong> for reading my work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192a2c28959b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/classifying-flower-through-sequential-api-deep-learning-192a2c28959b">Classifying Flower through Sequential-API-Deep Learning.</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[Insect Classification]]></title>
            <link>https://medium.com/analytics-vidhya/insect-classification-df8cebe1511d?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8cebe1511d</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[insects]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 08:55:01 GMT</pubDate>
            <atom:updated>2022-03-20T08:55:01.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*G1BrekM6WsENSGTYDwYaLA.gif" /><figcaption>src: <a href="https://gifer.com/en/3BDd">https://gifer.com/en/3BDd</a></figcaption></figure><p>Let’s build a classifier for classifying Insects e.g. Butterfly, Dragonfly, Mosquito, Grasshopper, and Ladybug using Keras Tensorflow Module.</p><p>Here are the steps we will follow:</p><ol><li>Data Import</li><li>Visualizing Images</li><li>Building Image Generators</li><li>Model Architecture</li><li>Prediction</li></ol><p><strong>About Dataset:</strong></p><p>The dataset contains images of insects from different websites and there are 5 directories in this dataset for different kinds of insects. Each directory contains almost ~1000 images of the particular insect type. Data has been scraped from <a href="https://www.google.com/imghp?hl=EN">Google </a>and <a href="https://www.istockphoto.com/">iStock</a>.</p><p><strong>Data Import</strong></p><p>We will start by importing the required libraries and the main directory path.</p><pre><strong>import</strong> tensorflow <strong>as</strong> tf<br><strong>import</strong> cv2<br><strong>import</strong> numpy <strong>as</strong> np <em># linear algebra</em><br><strong>import</strong> pandas <strong>as</strong> pd <em># data processing, CSV file I/O (e.g. pd.read_csv)</em><br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> os</pre><p>Here’s the path to the main directory. In your case choose the path directed to your notebook. I have chosen ‘insects’ as my directory because that is the folder directed to my notebook. I have also created a variable representing the number of subfolders available (5 folders for 5 classes).</p><pre><em># Directory where images are present</em><br>main_dir <strong>=</strong> &#39;insects&#39;<br>num_fldrs <strong>=</strong> 5</pre><p>Let’s create a dictionary that contains labels for each class and keys for them. Later it will be used to fetch class names.</p><pre><em># dictionary of labels</em><br>insect_names <strong>=</strong> {&#39;1&#39;:&quot;Butterfly&quot;,&#39;2&#39;:&quot;Dragonfly&quot;,<br>               &#39;3&#39;:&quot;Grasshopper&quot;,&#39;4&#39;:&quot;Ladybird&quot;,<br>               &#39;5&#39;:&quot;Mosquito&quot;}</pre><p>Now, we will build a data frame that contains an absolute path to each image and its label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cf4f0abb8040d56056ecb6414110565/href">https://medium.com/media/3cf4f0abb8040d56056ecb6414110565/href</a></iframe><pre>train <strong>=</strong> getdata(main_dir,num_fldrs)</pre><p>The above function will return a data frame for main directory images.</p><p><strong>Visualizing Images</strong></p><p>Let’s create functions to visualize images. For example to fetch n number of images of Dragonfly from dataframe. Just to know if they are of the same size or not.</p><pre><em># A function to fetch single images based on path given</em><br><strong>def</strong> get_image(path):<br>    img <strong>=</strong> cv2<strong>.</strong>imread(path,0)<br>    plt<strong>.</strong>imshow(img,cmap<strong>=</strong>&#39;gray&#39;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href">https://medium.com/media/0ff0de219bab57cf35c3ba124138b330/href</a></iframe><p>The output will look like this:</p><pre>get_n_images(10,train,&quot;Dragonfly&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*R7x8K3gpqGjVRCyGHEgQQg.png" /><figcaption>Dragonfly</figcaption></figure><p>Images are not of the same size we will take care of that in Image Generator. The proportion of insects available in the data set is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*CjcIOE0pKsiGlgmP-dpLiw.png" /><figcaption>Proportions of Insects</figcaption></figure><p><strong>Image Data Generator</strong></p><p>It generates batches of tensor image data with real-time data augmentation. There several parameters to pass in according to your need. Please check the documentation presented <a href="https://keras.io/api/preprocessing/image/#imagedatagenerator-class">here</a>.</p><p>Now, we will build our Image Data Generator which will be used to generate train and valid tests directly from the main directory by using <a href="https://keras.io/api/preprocessing/image/#flowfromdataframe-method">Flow From Directory</a>. We will also apply some image augmentation to our generator. Rotation range of 40 degrees — rotates images randomly, set Horizontal flip to be True and fill mode to be nearest. After initializing the generator, we will set the target size of each image to be 150x150 (WxH). Each image is required in color so we will set the color mode to be ‘rgb’. Batch size is the number of extractions from each subfolder. We will do this for both sets i.e. train and valid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d68dc8ee357e6ddb3c67de754b7c44e8/href">https://medium.com/media/d68dc8ee357e6ddb3c67de754b7c44e8/href</a></iframe><pre><em># Build train and validation sets</em><br>traingen,validgen <strong>=</strong> datapreprocessing(main_dir,20)</pre><p>Output:</p><pre>Found 3116 images belonging to 5 classes.<br>Found 1333 images belonging to 5 classes.</pre><p>Let’s look at what is happening inside the generator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href">https://medium.com/media/7fa0dcc96c4351d34de81fced747405b/href</a></iframe><pre>visualize_gen(traingen)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*snblQySsw6M1st6h16RH-Q.png" /><figcaption>Insects image inside the generator</figcaption></figure><p>We have dealt with the size problem of the images. Images have also been augmented using rotation and horizontal flip.</p><p>Now we have our data set fully prepared. Let’s build the model.</p><p><strong>Model Architecture</strong></p><p>We will build our model as per the below summary.</p><pre>Model: &quot;sequential&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>layer1 (Conv2D)              (None, 148, 148, 16)      448       <br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 37, 37, 16)        0         <br>_________________________________________________________________<br>dropout (Dropout)            (None, 37, 37, 16)        0         <br>_________________________________________________________________<br>layer2 (Conv2D)              (None, 35, 35, 32)        4640      <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 17, 17, 32)        0         <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 17, 17, 32)        0         <br>_________________________________________________________________<br>layer3 (Conv2D)              (None, 15, 15, 64)        18496     <br>_________________________________________________________________<br>max_pooling2d_2 (MaxPooling2 (None, 7, 7, 64)          0         <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 7, 7, 64)          0         <br>_________________________________________________________________<br>layer4 (Conv2D)              (None, 5, 5, 128)         73856     <br>_________________________________________________________________<br>max_pooling2d_3 (MaxPooling2 (None, 2, 2, 128)         0         <br>_________________________________________________________________<br>dropout_3 (Dropout)          (None, 2, 2, 128)         0         <br>_________________________________________________________________<br>flatten (Flatten)            (None, 512)               0         <br>_________________________________________________________________<br>layer7 (Dense)               (None, 128)               65664     <br>_________________________________________________________________<br>dropout_4 (Dropout)          (None, 128)               0         <br>_________________________________________________________________<br>layer8 (Dense)               (None, 128)               16512     <br>_________________________________________________________________<br>dropout_5 (Dropout)          (None, 128)               0         <br>_________________________________________________________________<br>output (Dense)               (None, 5)                 645       <br>=================================================================<br>Total params: 180,261<br>Trainable params: 180,261<br>Non-trainable params: 0</pre><p>To understand any of the above-mentioned layers, you can refer <a href="https://keras.io/api/layers/">here</a>.</p><p>We will proceed to our architecture by defining a builder function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c35b56bef7d39523c9e926fd370629/href">https://medium.com/media/b3c35b56bef7d39523c9e926fd370629/href</a></iframe><p>Build a model with the input_shape as the shape of the images.</p><pre><em># Get input shape</em><br>input_shape <strong>=</strong> traingen<strong>.</strong>image_shape<br>#Build Model<br>model01 <strong>=</strong> insectclf(input_shape)</pre><p><strong>Compile</strong></p><p>To compile everything we will use :</p><blockquote>loss <strong>= </strong>categorical_crossentropy<br>optimizer <strong>= Adam</strong><br>metrics <strong>= </strong>accuracy<br>callback = Earlystopping</blockquote><p>Here’s the full code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceea2cd75aef46a1b56311979c666714/href">https://medium.com/media/ceea2cd75aef46a1b56311979c666714/href</a></iframe><p>Let’s fit the model with epoch = 100, batch size = 32, and learning rate = 0.001. I have reached to these parameters after a lot of iterations but you are free to choose whatever you find fit.</p><pre>model01 <strong>=</strong> compiler(model01,traingen,validgen,100,bsize<strong>=</strong>32,lr<strong>=</strong>0.001)</pre><p>After running for 100 Epochs model will plot a curve and restore the best weights available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*KXCUx_-TrX-8XiwJepvz7A.png" /><figcaption>Accuracy Curve</figcaption></figure><p><strong>Get Prediction</strong></p><p>Let&#39;s try to predict any image available in the validation data set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c2d24057acc2eb8422a652a97ffc82/href">https://medium.com/media/26c2d24057acc2eb8422a652a97ffc82/href</a></iframe><p>Pass in n any number between 0–19 because there 20 images from each folder.</p><pre>get_predictions(13)</pre><p>Output:</p><pre>&#39;Butterfly&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*u6izqiL1JpqVWRfTsZXf5w.png" /></figure><p>Save the model for later use.</p><pre>model01[0]<strong>.</strong>save(filepath<strong>=</strong>&#39;Dataset/saved_models/Model01.tf&#39;,save_format<strong>=</strong>&quot;tf&quot;)</pre><p>Congrats! you have built your first insect classifier model using Keras TensorFlow.</p><p><strong>Thank you</strong> for reading my story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8cebe1511d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/insect-classification-df8cebe1511d">Insect Classification</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[Share Price Prediction using RNN and LSTM]]></title>
            <link>https://medium.com/analytics-vidhya/share-price-prediction-using-rnn-and-lstm-8776456dea6f?source=rss-cf9bc46d1a6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8776456dea6f</guid>
            <category><![CDATA[share-price]]></category>
            <category><![CDATA[stock-price-forecast]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[capital-markets]]></category>
            <dc:creator><![CDATA[RishiRajak]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 11:57:02 GMT</pubDate>
            <atom:updated>2024-05-20T09:41:49.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_meWQFx3uP9-lzS9ptMrQ.jpeg" /></figure><p>If you are interested in building an algorithm that can predict a stock’s price trend this might be the page for you.</p><p>This article talks about an approach to stock price prediction using deep learning techniques like Recurrent Neural Network and Long Short Term Memory.</p><p>We will go through each step of building a deep learning model using RNN and LSTM and check which is more suitable for predicting trends. Anyone with basic <br>knowledge of deep neural networks can relate to this article easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE-_txA3mEOFHV1Bs4xFQw.jpeg" /></figure><p><strong>A Deep Learning Approach on Stock’s Share Price Prediction.</strong></p><p>Before proceeding to steps, let’s first understand the concept of RNN and LSTM.</p><p><strong>RNN:</strong></p><p>Recurrent neural networks (RNN) are a class of neural networks that is powerful for modeling sequence data such as time series or natural language. I have used it in predicting stock prices. The logic behind this is that it will remember the price after a particular sequence and the model will gain experience based on that pattern. Schematically, RNN layer uses a for loop to iterate over the timesteps of a sequence, while maintaining an internal state that encodes information about the timesteps it has seen so far. RNN can retain sequence patterns only for a short time thus, we move to LSTM that can remember patterns in Long and Short Term memory.</p><p><strong>LSTM:</strong></p><p>LSTM is an artificial recurrent neural network architecture used in the field of deep learning. It is preferred over feedforward neural networks because it can memorize the data points over a longer period and hence the name Long Short Term Memory. LSTM network consists of cell, input gate, output gate and a forget gate.<br>Cell is like a memory that holds values over arbitrary time and three gates regulate that information in and out of the cell.</p><p>To get a detailed view of RNN and LSTM, click on the image below:</p><figure><a href="https://purnasaigudikandula.medium.com/recurrent-neural-networks-and-lstm-explained-7f51c7f6bbb9"><img alt="" src="https://cdn-images-1.medium.com/max/516/1*HZTEsWqk4b4XUDI0FDnv_Q.png" /></a></figure><p><strong>Data Collection &amp; Preprocessing:</strong></p><p>The first thing that we need to do is install yfinance. If you haven’t already installed it yet.</p><pre>pip install yfinance</pre><p>Import the yfinance module for collecting data of a particular stock. For our case, we will use Escorts Ltd.</p><pre>#importing yfinance<br>import yfinance as yf</pre><pre>#Collecting data<br>data = yf.download(&#39;ESCORTS.NS&#39;,period=&#39;5y&#39;,interval=&#39;1d&#39;)</pre><p>Parameters required for yfinance.download() are ticker which is the symbol for your stock; period: total duration for which you want data to be extracted, and interval: which refers to the consecutive records e.g. for 1 day put ‘1d’. This will extract the stock’s data of 5 years for each day excluding the holidays.</p><p>Import the following libraries:</p><pre>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><p>Now that we have collected the data, we need to select the column which is required. Data contains stock’s historical data on Open, Close, Low, High, Volume, and Adjusted Close. We will be using adjusted close for pattern detection and prediction. Also, split the data into train and test set so that we can evaluate our model later.</p><pre>data_target = data.iloc[:1182,4]<br>data_test = data.iloc[1132:,4]<br>steps = 7</pre><pre>#return numpy representation of data<br>data = data.loc[:,[&quot;Adj Close&quot;]].values<br>test = data[len(data) - len(data_test) - steps:]</pre><pre>#4 the column is Adj Close</pre><p>Let’s check the trend by visualizing it.</p><pre>plot = data_target.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ff2PoRG2N46G02TTMyznEQ.png" /><figcaption>Escorts Ltd on NSE</figcaption></figure><p>Before, proceeding further we need to define some functions for Scaling Down data and converting data into a set of patterns followed for a particular price.</p><p>For scaling down, we will use MinMaxScaler available under ScikitLearn.</p><pre>#Scaling Dataset<br>def scaledata(data_target):</pre><pre>    #Import scaler and initialise it<br>    from sklearn.preprocessing import MinMaxScaler<br>    scaler = MinMaxScaler(feature_range=(0,1))<br>    #transform by converting it to array and shape of (-1,1)<br>    data_target_scaled = scaler.fit_transform(np.array(data_target).reshape(-1,1))<br>    #plot the scaled version of data<br>    plot_scaled = pd.DataFrame(data_target_scaled).plot()<br>    print(data_target.shape)</pre><pre>    #returns scaled data<br>    return data_target_scaled, scaler</pre><p>Before proceeding to the next function, let’s understand why is it required. By now, we know that RNN retains the pattern for example if you wear red on Sunday, blue on Monday, and green on Tuesday and then repeats it, RNN can retain that pattern for a short time. It can predict that you will wear blue tomorrow if you wear a red t-shirt today. Thus, data must have a pattern to be recognized.</p><p>Now, we will build a function that will convert the data into patterns of prices, and the target price achieved after that pattern follows. This way, our model can learn the response of the price patterns.</p><pre>#Create pattern and end price set<br>def createPatternSet(data_target_scaled,steps=7):   <br>    x_patern = []  #Independent Variable<br>    y_price = []   #Dependent Variable</pre><pre>    for day in range(steps,data_target_scaled.shape[0]):<br>        row = data_target_scaled[day-steps:day,0]<br>        #print(len(row))<br>        x_patern.append(row)<br>        y = data_target_scaled[day,0]<br>        #print(y)<br>        y_price.append(y)<br>    <br>    x_patern,y_price = np.array(x_patern),np.array(y_price)<br>    #RNN and LSTM takes 3D inputs, we need to change the shape of array to 3 dimensional.</pre><pre>    x_patern = x_patern.reshape(x_patern.shape[0],x_patern.shape[1],1)</pre><pre>    #returns independent and dependent variable sets<br>    return x_patern,y_price</pre><p>The above function takes data to be converted and the number of steps as steps. By default, we set steps equal to 7 which means that the 7-day pattern and the Price after that will be recorded as independent and dependent variables respectively.</p><pre>#Scale Down Target<br>data_target_scaled = scaledata(data_target)[0]<br>scaler = scaledata(data_target)[1]<br>#prepare test data<br>test = data[len(data) - len(data_test) - steps:]<br>test = scaler.transform(test)</pre><p><strong>Train and Test Set:</strong></p><p>We will use our function to process and build x_train and y_train.</p><pre>#Overwrite steps to 50. it doesnt really matter here because we will be doing a lot of iterations with it (Take anyhthing less than 100).<br>train_pattern = createPatternSet(data_target_scaled,steps=50)<br>x_train = train_pattern[0]<br>y_train = train_pattern[1]</pre><pre>#Input Shape needs to be 3D.<br>x_train.shape<br>&gt;&gt;&gt; (1132, 50, 1)</pre><p>We finished building our train set and we will build the test set.</p><pre>#create pattern and price for test set.<br>test_pattern = createPatternSet(test,steps=50)<br>x_test = test_pattern[0]<br>y_test = test_pattern[1]</pre><pre>#Dont forget to check the shape of x_test (3D reuired).<br>x_test.shape</pre><p>Test data will be used for the model’s evaluation. We will predict the values based on the x_test and then compare them to the original y_test value.</p><p>So, far we have completed data preprocessing, and now the interesting part<strong>.</strong></p><p><strong>Model Architecture:</strong></p><p>We will define a class with methods that can build the architecture, compile it, and fit it on given data. The class will also have methods to set parameters like the number of neurons, batch_size, and epoch. The reason to build this class is that we can run a for loop with the different parameters passed and analyze the result. This will help the readers in trying other combinations of hyperparameters.</p><p>Later on, we can also inherit from this class for LSTM and overwrite the architecture building method. There are other options available for hyper tuning the model but we stick to this for the most basic understanding.</p><p>Build the Class for RNN:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aca34783a089015ce3b0684cae370a2/href">https://medium.com/media/9aca34783a089015ce3b0684cae370a2/href</a></iframe><p>By default the model’s architecture contains the following layers:</p><pre>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>simple_rnn_44 (SimpleRNN)    (None, 50, 50)            2600      <br>_________________________________________________________________<br>dropout_32 (Dropout)         (None, 50, 50)            0         <br>_________________________________________________________________<br>simple_rnn_45 (SimpleRNN)    (None, 50, 50)            5050      <br>_________________________________________________________________<br>dropout_33 (Dropout)         (None, 50, 50)            0         <br>_________________________________________________________________<br>simple_rnn_46 (SimpleRNN)    (None, 50, 50)            5050      <br>_________________________________________________________________<br>dropout_34 (Dropout)         (None, 50, 50)            0         <br>_________________________________________________________________<br>simple_rnn_47 (SimpleRNN)    (None, 50)                5050      <br>_________________________________________________________________<br>dropout_35 (Dropout)         (None, 50)                0         <br>_________________________________________________________________<br>dense_19 (Dense)             (None, 1)                 51        <br>=================================================================<br>Total params: 17,801<br>Trainable params: 17,801<br>Non-trainable params: 0</pre><p>For compilation, I have used Adam and for loss function Mean Squared Error.</p><p>Build the Class for LSTM:</p><p>Inherit the previous class’ attribute and overwrite the architecture.</p><pre>class LstmModel(StocksPriceRNN):<br>    StocksPriceRNN.model = tf.keras.Sequential()<br>    def __init__(self,x_train,y_train,epoch):<br>        super().__init__(x_train,y_train,epoch)<br>    <br>    def buildArchitecture(self,dense=1):<br>        StocksPriceRNN.model = tf.keras.Sequential()<br>        StocksPriceRNN.model.add(tf.keras.layers.LSTM(<br>                                 StocksPriceRNN.neurons,<br>                                 input_shape=(None,1)))<br>        #Output<br>        StocksPriceRNN.model.add(tf.keras.layers.Dense(units=1))<br>        return StocksPriceRNN.model.summary()</pre><p><strong>Visualization:<br></strong>Next, we build a function to plot the validation curves.</p><pre>def plotting(org_vals,output):<br>    plt.figure(figsize=(10,5), dpi=80, facecolor=&#39;w&#39;, edgecolor=&#39;k&#39;)<br>    plt.plot(org_vals,color=&quot;Green&quot;,label=&quot;Org value&quot;)<br>    plt.plot(output,color=&quot;Yellow&quot;,label=&quot;Predicted&quot;)<br>    plt.legend()<br>    plt.xlabel(&quot;Days&quot;)<br>    plt.ylabel(&quot;Price&quot;)<br>    plt.grid(True)<br>    plt.show()</pre><p>That was a lot of work but we have built the pieces of our algorithm and the only thing left is to put them together.</p><p><strong>Iterations &amp; Evaluations:</strong></p><p>First, we will iterate on RNN and then on LSTM. The best output of both will be compared for the evaluation.</p><p>Build a For-Loop statement for passing different epochs and batch sizes. Run the model on the data and visualize the output:</p><pre>for steps in [7,30,90]:<br>    for epoch in [20,30,50]:<br>        #prepare train data<br>        train_pattern = createPatternSet(data_target_scaled,steps=steps)<br>        #prepare test data<br>        test = data[len(data) - len(data_test) - steps:]<br>        test = scaler.transform(test)</pre><pre>        test_pattern = createPatternSet(inputs,steps=steps)<br>        x_test = test_pattern[0]<br>        y_test = test_pattern[1]<br>        #Build Model<br>        RNN1 = StocksPriceRNN(x_train,y_train,epoch)<br>        RNN1.buildArchitecture(2,0)<br>        RNN1.compiler()<br>        #fit model<br>        history = RNN1.modelfit()<br>        #Predict Values<br>        pred = RNN1.model.predict(x=x_test)<br>        output = scaler.inverse_transform(pred)<br>        org_vals = scaler.inverse_transform(y_test)<br>        #visualise<br>        print(&quot;Plotting for Steps {} and Epoch {}&quot;.format(steps,epoch))<br>        plotting(org_vals,output)</pre><p>This will output in 9 iterations. After comparing the iterations, I found that RNN gives sloppy but comparatively best results on a combination of 90–30 and 90–50 (steps-epoch).</p><p>Here is the Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*Bweld_eLgriNMYtoDICW6Q.png" /><figcaption>RNN: Plotting for Steps 90 and Epoch 50</figcaption></figure><p>Not much difference between 30–50 epoch but accuracy can increase on the increase of epochs.</p><p>Similarly, we run iterations for LSTM:<br>Please note that there will be some warnings related to “out of calls” and this is natural as we have split the test data with 100 records only. To avoid this, Make sure that experimental_relax_shapes=True, an option that relaxes argument shapes that can avoid unnecessary retracing (not necessarily required).</p><pre># for different epochs, batch size, and neurons/units. <br>for epch in [60,100,200]:<br>    for batch in [2,4,6]:<br>        for neurons in [8,10,12]:<br>            LSTM2 = LstmModel(x_train,y_train,epoch=epch)<br>            LSTM2.changeBatchSize(batch)<br>            LSTM2.changeNeurons(neurons)</pre><pre>            LSTM2.buildArchitecture()<br>            LSTM2.compiler()<br>            history = LSTM2.modelfit()</pre><pre>            pred = LSTM2.model.predict(x_test)<br>            pred = scaler.inverse_transform(pred)<br>            #org = scaler.inverse_transform(y_test)</pre><pre>            print(&quot;For epch {}, neurons {} and batch {}&quot;.format(epch,neurons,batch))<br>            plotting(org,pred)</pre><p>The output will contain 27 iterations.</p><p>Analyzing the output of LSTM, it is clear that LSTM performs better on the dataset than the RNN. LSTM gave better results at batch_size = 2, units = 10 and epoch = 200.</p><p>Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*LyATHGlVodC5V8f1JEPO1g.png" /><figcaption>LSTM</figcaption></figure><p><strong>EndNote:</strong><br>The model that we have built is capable of a lot more iterations. We have only tried a few of them and still managed to get closer to the original price curve. Go ahead! and try other hyperparameters on your own, since we have built a class instance we can do a lot of modifications without writing the whole code or making changes to the same one.</p><p>Here’s the complete code:<br><a href="https://www.kaggle.com/rishirajak/share-price-prediciton-using-lstm-and-rnn">https://www.kaggle.com/rishirajak/share-price-prediciton-using-lstm-and-rnn</a></p><p><strong>Thank you</strong> for reading my work.</p><p>As a token of appreciation 😄 and if you are into books 📚, please visit and follow @<a href="https://www.instagram.com/musings_of_bibliophile?igsh=dThtZHJ6bnFueHVi">musings_of_bibliophile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8776456dea6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/share-price-prediction-using-rnn-and-lstm-8776456dea6f">Share Price Prediction using RNN and LSTM</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>
    </channel>
</rss>