<?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 Divyanshu Raj on Medium]]></title>
        <description><![CDATA[Stories by Divyanshu Raj on Medium]]></description>
        <link>https://medium.com/@divyanshu-raj?source=rss-5556e9ffcf23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aPh9In0ehxealkB__u9p2w.jpeg</url>
            <title>Stories by Divyanshu Raj on Medium</title>
            <link>https://medium.com/@divyanshu-raj?source=rss-5556e9ffcf23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:55:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divyanshu-raj/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[Behavior Cloning with RLBench]]></title>
            <link>https://divyanshu-raj.medium.com/behavior-cloning-with-rlbench-b3e59950a9b8?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e59950a9b8</guid>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[behavior-cloning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 23:21:16 GMT</pubDate>
            <atom:updated>2024-10-12T23:21:16.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dataset generation process for change point detection and behavior cloning with RLBench simulator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoNYWIq5p-L1PEF_2kGtag@2x.jpeg" /><figcaption>Franka Emika Robot hand used for data generation with expert demonstrations (Image by Author)</figcaption></figure><p>In my recent paper¹ “<strong>Learning Temporally Composable Task Segmentations with Language,</strong>” published at the IROS 2024 conference, I presented a method for detecting change-points in long-horizon robotics trajectories. To achieve this, I needed to create a specialized dataset, which was done using the RLBench² simulator. RLBench provides both low- and high-dimensional data, and I leveraged its capabilities to mark change-points that split longer tasks into smaller subtasks, like picking and placing a block. I generated <strong>10,000 demonstrations</strong> across 20 manually curated long-horizon tasks. I’ll walk you through the data creation process in detail in this article.</p><h4>RLBench²</h4><p>RLBench is a learning environment that is widely used to benchmark robot learning with over 100 tasks at varying levels of difficulty. The simulator allows us to capture proprioceptive observations and visual observations, including RGB, depth, and segmentation masks from cameras of multiple different angles. Each individual task in RLBench includes various initial configurations of objects to guarantee the robustness of the benchmark, with demonstrations provided by the in-built planner and the waypoints<br>from the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fbsyLLPhmBchVzd9XwXww.png" /><figcaption>RLBench simulator in edit mode for the task of “Place the blue block in the drawer” (Image by Author)</figcaption></figure><p>For installation, you can follow the awesome Github repository for RLBench: <a href="https://github.com/stepjam/RLBench">Git Repo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CYXbvW_q0rGNg4vg78IZA.gif" /><figcaption>Visual representaion of dataset, for wrist camera, front camera, overhead camera and proprioceptive data (Image by Author)</figcaption></figure><p>The RLBench simulator&#39;s dataset includes low- and high-dimensional data. The low-dimensional data also referred to as proprioceptive data, captures the robot’s internal states, such as the force, velocity of the 7 joints, and the gripper status. On the other hand, the high-dimensional data consists of visual inputs from multiple camera angles. For this dataset, we utilized three cameras: a wrist camera, a front-facing camera, and an overhead camera, providing comprehensive visual coverage of the task environment.</p><h4>Success Condition</h4><p>In long-horizon tasks, a sub-task like “open the drawer” is marked complete when specific success conditions are met, allowing for a change-point to be defined in the trajectory. In simulations, these success conditions need to be clearly defined. For instance, a <strong>virtual wall</strong> can be used to mark the completion of the sub-task — when the drawer touches this virtual boundary, it signals that the sub-task is complete and a change-point can be recorded. Similarly, for a task like “pick up the block,” a change-point can be defined when the block crosses a predefined virtual boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4jKjZTWsFsGHCDYM9vAAw.gif" /><figcaption>Visual represenstation of change-points. Left: “<strong>Open the middle drawer</strong>”. Right: “<strong>Pick up the blue block</strong>”. (Image by Author)</figcaption></figure><p>In the simulator, object positions are randomized, and the virtual walls defining success or change points are set relative to the objects. This flexibility allows us to generate data in a randomized fashion, varying elements such as object position, color, and background. For example, in the “open drawer” task, I can generate 250 demonstrations where both the starting and end positions, as well as the positions of nearby objects, will differ for each demonstration. This approach enhances the dataset’s diversity and robustness, ensuring that model can generalize better across different environments and conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGmuxNn5N-qYcVOajrQlqg.gif" /><figcaption>Complete example with change-points/success conditions for the task of “<strong>Put the ball in the basket</strong>” (Image by Author)</figcaption></figure><p>This diagram visually represents a trajectory for the task “Put the ball in the basket,” which can be broken down into two distinct subtasks, marked by change-points: “Pick up the ball” and “Place the ball in the basket.” In the accompanying GIF, the first change-point is marked when the ball exits the virtual red box, signifying the completion of the picking action. The second change-point is triggered when the ball enters a second virtual red box, indicating it is now positioned correctly for placing. Green markers labeled 1 and 2 visually indicate these change-points, providing clear boundaries between the subtasks.</p><h4>Code Changes</h4><p>Click on “Run Pen” to understand the changes required for this dataset creation. It shows the diff in changes made to each file in codebase, and shows how the “Put the ball in the basket” should look in code. For full code, clone <a href="https://github.com/divraz/TrajectorySegmentation">this</a> git repository.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2FDivyanshu-Raj-the-decoder%2Fembed%2Fpreview%2FrNbRZKQ%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DrNbRZKQ&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2FDivyanshu-Raj-the-decoder%2Fpen%2FrNbRZKQ&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FrNbRZKQ-512.jpg%3Fversion%3D1714160551&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/a66cdce3ba3d9c3bf5e1ac23b43c827c/href">https://medium.com/media/a66cdce3ba3d9c3bf5e1ac23b43c827c/href</a></iframe><h4>Examples</h4><p>Let’s see a few examples of how change-points are defined in the 20 tasks.</p><p><strong>Build Pyramid</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R01yuPEYkLAXADSXx7WLNw.gif" /><figcaption>Visual representation of decomposition for the taks “<strong>Build pyramid</strong>” into sub-tasks of <strong>pick</strong> and <strong>place</strong>. (Image by Author)</figcaption></figure><p>The process of building a pyramid with 3 levels can be divided into clear “<strong>pick</strong>” and “<strong>place</strong>” actions, where each block is distinguished by color:</p><ol><li>Constructing the Base Layer (<strong>Level 1</strong>)<br>- <strong>Pick up the Orange Block</strong><br>- <strong>Place the Orange Block in the center</strong><br>- <strong>Pick up the Pink Block</strong><br>- <strong>Place the Pink Block on the right of the Green center<br>- Pick up the Green block<br>- Place the Green Block on the left of the Green center</strong></li><li>Building the Middle Layer (<strong>Level 2</strong>)<br><strong>- Pick the Gray Block<br>- Place the Gray block on the right of the middle layer<br>- Pick the Purple Block<br>- Place the Purple block on the left of the middle layer</strong></li><li>Completing the Top Layer (<strong>Level 3</strong>)<br><strong>- Pick up the Pink Block<br>- Place the Pink Block on the top of the pyramid</strong></li></ol><p>This sequence of actions ensures a stable pyramid assembly, with each colored block marking a clear stage in the construction. The robot trajectory is decomposed into sub-tasks of picking and placing blocks in a structured order from the base to the top. Further, we can collect all the <strong>pick</strong> sub-tasks and train a behavior cloning model conditioned on language instructions to perform a “pick” action for a specific colored block (e.g., “Pick the red block”). Similarly, we can train another behavior cloning model for the <strong>place</strong> action, which is also conditioned by language (e.g., “Place the red block on the base”). This method enables the robot to effectively learn both picking and placing actions based on color and task context.</p><p><strong>Change Channel</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhKSx1IheRfpGzxZZumfNw.gif" /><figcaption>Visual representation of decomposition for the taks “<strong>Change channel</strong>” into sub-tasks of <strong>pick, rotate, </strong>and <strong>push</strong>. (Image by Author)</figcaption></figure><p>The process of changing a channel with remote control can be broken down into clear “pick,” “rotate,” and “press” actions, each defined by specific sub-tasks:</p><ol><li><strong>Pick Up the Remote</strong></li><li><strong>Change Remote Orientation</strong></li><li><strong>Press the Button on the Remote</strong></li></ol><p>The robot’s trajectory is decomposed into these structured sub-tasks of picking, orienting, and pressing. Furthermore, we can collect all the pick sub-tasks and train a behavior cloning model conditioned on language instructions to perform the “pick” action for the remote (e.g., “Pick up the remote”). Similarly, we can develop another behavior cloning model for the orientation adjustment, conditioned by commands like “Change the remote’s angle,” and a separate model for pressing the button, based on instructions such as “Press the channel up button.” This method enables the robot to effectively learn the complete task of changing channels, adapting its actions based on context and specific language cues.</p><p><strong>Empty Dishwasher</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5hNVZ68_hARP5KiFcU4pw.gif" /><figcaption>Visual representation of decomposition for the taks “<strong>Empty dishwasher</strong>” into sub-tasks of <strong>open, pull, pick, </strong>and <strong>place</strong>. (Image by Author)</figcaption></figure><p>The process of emptying a dishwasher can be broken down into clear “open,” “pull,” “pick,” and “place” actions, structured as follows:</p><ol><li><strong>Open the Dishwasher</strong></li><li><strong>Pull the Tray Out</strong></li><li><strong>Pick up the plate from the tray</strong></li><li><strong>Place the Plate on Top of the Dishwasher</strong></li></ol><p>The robot’s trajectory is decomposed into these structured sub-tasks of opening, pulling, picking, and placing. Additionally, we can collect all the pick sub-tasks and train a behavior cloning model conditioned on language instructions to perform the “pick” action for the plates (e.g., “Pick up the plate”). Similarly, we can create models for the other actions, such as “Open the dishwasher” and “Place the plate on top of the dishwasher,” enabling the robot to learn the complete task of emptying the dishwasher effectively, following natural language instructions throughout the process.</p><p><strong>Play Hockey</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngG8baKDpJJfNf0h_iGSgA.gif" /><figcaption>Visual representation of decomposition for the taks “<strong>Play hockey</strong>” into sub-tasks of <strong>pick, </strong>and <strong>slide</strong>. (Image by Author)</figcaption></figure><p>The process of playing hockey can be broken down into clear “pick” and “slide” actions, structured as follows:</p><ol><li><strong>Pick Up the Hockey Stick</strong></li><li><strong>Slide the Pink Ball to the Goal</strong></li><li><strong>Slide the Gray Ball to the Goal</strong></li></ol><p>The robot’s trajectory is decomposed into these structured sub-tasks of picking and sliding. Moreover, we can collect all the pick and slide sub-tasks and train separate behavior cloning models conditioned on language instructions to perform specific actions, such as “Pick up the hockey stick” and “Slide the pink ball to the goal.”</p><p><strong>More Examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKMT7F968Nh5nt56SwFcIA.gif" /><figcaption>Visual representation of decomposition of several tasks into sub-tasks marked by fulfilling success conditions for change-point detection dataset creation. (Image by Author)</figcaption></figure><h4>Feature Generation</h4><p>We extract compact features from the trajectory observations by first converting visual observations into 10 FPS videos. These videos are then segmented into 2-second clips, each labeled with the associated language instruction. We use the HERO³ feature extractor to convert these clips into features and concatenate the features from all the cameras. At the end of every 2-second clip, we capture the robot’s proprioceptive data as part of the observation. These observations, along with the visual features extracted from the clip constitute the trajectory features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tZ6HzKBdsncHwh_KCoaTg.gif" /><figcaption>Visual representation of capturing visual(high-dimensional data) and proprioceptive(low-dimensional data) data from robotics trajectory to be used for extracting trajectory features (Image by Author)</figcaption></figure><h4>Results</h4><p>This dataset is then used for language conditioned task segmentation approach for high-dimensional robot trajectories. This dataset helped to demonstrate significant improvements in trajectory segmentation accuracy on high dimensional data (34% improvement) while demonstrating sample efficiency(mAP of 61.41 with only 100). Moreover, this method of data generations provides the ability to change sub-task granularity and a pathway towards sim-to-real transfer of the changepoint detection models. Further, behavior cloning models trained on the<br>segmented trajectories from this dataset outperform a single model trained on the whole trajectory by up to 20%. The detailed results can be found in the following website:</p><p><a href="https://sites.google.com/asu.edu/change-point">Trajectory Segmentation</a></p><h4>Demonstrations</h4><p>I am presenting two demonstrations that illustrate the improvements achieved by utilizing this dataset to separate sub-tasks such as “pick” and “place.” By training distinct behavior cloning (BC) models that specialize in individual actions, we can effectively stitch these models together to complete more complex tasks, rather than relying on a single unified policy.</p><p>The results shown below use the same amount of data but employ different approaches to demonstrate the effectiveness of this method. For a deeper understanding of the techniques and findings, please refer to my paper¹.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwsBfnI8csutaO2AU2bS0Q.gif" /><figcaption>Comparison of single behavior cloning policy vs stitched specialized multiple behavior cloning policies to perform a task (Image by Author)</figcaption></figure><p>In the gif, you will see two demonstrations, each divided into upper and lower segments, highlighting the effectiveness of our approach to task segmentation using the dataset.</p><p><strong>Upper Segment:</strong> This segment showcases a traditional method where a single policy is trained to perform the entire long horizon task. While this method utilizes the same amount of data, it struggles with accuracy and efficiency in executing sub-tasks, leading to inconsistencies in performance.</p><p><strong>Lower Segment</strong>: In contrast, this segment illustrates the advantages of training separate behavior cloning models for the sub-tasks such as “pick” and “place” actions. Each model is fine-tuned to specialize in its respective sub-task, resulting in smoother and more precise movements. These models are effectively stitched together, demonstrating a more coherent and efficient execution of the complete task.</p><p>Overall, the video clearly demonstrates how separating sub-tasks and training specialized models can lead to significant improvements in robotic performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b48r8WxdVSZ3f7PtCYGNcA.gif" /><figcaption>Comparison of single behavior cloning policy vs stitched specialized multiple behavior cloning policies to perform a task (Image by Author)</figcaption></figure><h4><strong>References:</strong></h4><ol><li>D. Raj et al., “<strong>Learning Temporally Composable Task Segmentations with Language,</strong>” IEEE/RSJ International Conference on Intelligent Robots and Systems, 2024.</li><li>S. James et al., “<a href="https://ieeexplore.ieee.org/document/9001253"><strong>Rlbench: The robot learning benchmark &amp; learning<br>environment</strong></a>,” IEEE Robotics and Automation Letters, 2020.</li><li>L. Li et al., “<a href="https://aclanthology.org/2020.emnlp-main.161/"><strong>Hero: Hierarchical encoder for video+language omni-<br>representation pre-training</strong></a>,” EMNLP, 2020.</li><li>GitHub: <a href="https://github.com/divraz/TrajectorySegmentation.git">https://github.com/divraz/TrajectorySegmentation.git</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e59950a9b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Codespaces: C++ ‘Hello World’ Project with Unit Tests]]></title>
            <link>https://towardsdev.com/codespaces-c-hello-world-project-with-unit-tests-1cbc899213b5?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cbc899213b5</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[gtest]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[github-codespaces]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 11:07:29 GMT</pubDate>
            <atom:updated>2023-09-08T13:39:31.519Z</atom:updated>
            <content:encoded><![CDATA[<h4>Streamline Your C++ Development Workflow with GitHub Codespaces and GoogleTest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*086iYdTjfdEdijlr" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will create a simple “Hello World” C++ structured project with GitHub¹ Codespaces². The task will have two executables, one to run the unit tests and the other to run the project.</p><h4>Installations</h4><p>To use GitHub Codespaces, first, you need to create a repository. Then you need to open Codespaces and link⁷ it with your repository. Once you have your workspace open, you can install three extensions and GoogleTest for Unit tests.</p><p><strong>Extensions Installations:<br></strong>1. C++ Extension³<br>2. Makefile Tools⁴<br>3. CMake Tools⁵</p><p><strong>GoogleTest Installations:<br></strong>GoogleTest⁶ can be installed as a standalone project:</p><pre>git clone https://github.com/google/googletest.git -b v1.14.0<br>cd googletest        # Main directory of the cloned repository.<br>mkdir build          # Create a directory to hold the build output.<br>cd build<br>cmake ..             # Generate native build scripts for GoogleTest.</pre><p>After running the above commands, run the following:</p><pre>make<br>sudo make install    # Install in /usr/local/ by default</pre><p>Once all the installations are complete, we will move forward with defining the project structure.</p><h4>Code Structure</h4><p>We need to have 5 files as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c07yJ8NnM-dB-J3mUA7gQ.png" /><figcaption>Project Structure for Hello World (Image by Author)</figcaption></figure><p><strong>hello_world.h<br></strong>We will define all function definitions in this file. For now, we need a function, <strong>hello</strong>, that takes an input string and returns a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a910e671ac955030b7e31c3fa5713abe/href">https://medium.com/media/a910e671ac955030b7e31c3fa5713abe/href</a></iframe><p><strong>hello_world.cpp<br></strong>All the functions that are defined in hello_world.h will be written in this file. So, we write the <strong>hello</strong> function, where we concatenate the String name to hello and return the String.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02a3d800f1cca84ac7527b41045493e1/href">https://medium.com/media/02a3d800f1cca84ac7527b41045493e1/href</a></iframe><p><strong>test.cpp<br></strong>In this file, we will write all the unit tests for all the functions that are defined in <strong>hello_world.h</strong>, testing the functionalities. Note that we will define a main function in this file. You can view the samples⁸ in GoogleTest GitHub codebase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de90e0dbf36a2cf5ae000d96926ce7e0/href">https://medium.com/media/de90e0dbf36a2cf5ae000d96926ce7e0/href</a></iframe><p><strong>main.cpp<br></strong>This is the main file, where we import all the functions from hello_world.h and use it as per requirement. For this project, we will input the String <strong>name, </strong>call the <strong>hello </strong>function with <strong>name</strong>, and print the returned String value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/883e0bcfc33e5be9171122090c0393dc/href">https://medium.com/media/883e0bcfc33e5be9171122090c0393dc/href</a></iframe><p><strong>Makefile<br></strong>Finally, we write the Makefile, to compile all the files. As per this Makefile, there will be two executables. First is <strong>MAIN</strong>, that is for main.cpp file. It will input a String and output a String. Second is <strong>TEST</strong>, which is for test.cpp which will run all the unit tests written for the functions.</p><p>Note, that both main.cpp, and test.cpp have <strong>main()</strong> functions defined so they cannot be compiled together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d90fbff0c2f7e39b5a459b357a9ebf2/href">https://medium.com/media/5d90fbff0c2f7e39b5a459b357a9ebf2/href</a></iframe><p>Once, all the files are ready, we will compile them.</p><h4>Compile</h4><p>To compile all the files, we run the <strong>make </strong>command in the directory where Makefile is there. It will compile all files in order as defined in Makefile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abZ1UdH0W9KxCzGGwwHk_A.png" /><figcaption>Output of “make” command (Image by Author)</figcaption></figure><p>After compilation, there will be two executable files created, <strong>MAIN</strong> and <strong>TEST</strong>.</p><h4>Run</h4><p><strong>Tests</strong>: We run the ./TEST, to view the status of all the tests. If some test cases are failing, we need to correct them, re-compile, and check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Du_ZN06q-lx81r3UQG1LCQ.png" /><figcaption>Output of Unit Tests (Image by Author)</figcaption></figure><p><strong>Main</strong>: After all the test cases are successfully passed, we can run our main code and get the expected functionality of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BEviDD-Ohpkw8Cjlbo1Iw.png" /><figcaption>Output of MAIN (Image by Author)</figcaption></figure><p>In conclusion, by leveraging the power of GitHub Codespaces and GoogleTest, you can simplify and enhance your C++ development process. With a well-structured project and efficient unit testing, you’ll be better equipped to build robust and reliable C++ applications. So, go ahead, explore the capabilities of Codespaces, and streamline your C++ development workflow. Happy coding!</p><h3>References:</h3><p>[1] GitHub<br><a href="https://github.com/"><strong>https://github.com/</strong></a></p><p>[2] GitHub Codespaces<br><a href="https://github.com/features/codespaces"><strong>https://github.com/features/codespaces</strong></a></p><p>[3] Visual Studio Code: C++ Extension<br><a href="https://code.visualstudio.com/docs/languages/cpp"><strong>https://code.visualstudio.com/docs/languages/cpp</strong></a></p><p>[4] Visual Studio Code: Makefile Tools<br><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.makefile-tools"><strong>https://marketplace.visualstudio.com/items?itemName=ms-vscode.makefile-tools</strong></a></p><p>[5] Visual Studio Code: CMake Tools<br><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools"><strong>https://marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools</strong></a></p><p>[6] GoogleTest: Generic Build Instructions<br><a href="https://github.com/google/googletest/tree/main/googletest"><strong>https://github.com/google/googletest/tree/main/googletest</strong></a></p><p>[7] Codespaces: Link to GitHub repository<br><a href="https://docs.github.com/en/codespaces/developing-in-codespaces/creating-a-codespace-for-a-repository"><strong>https://docs.github.com/en/codespaces/developing-in-codespaces/creating-a-codespace-for-a-repository</strong></a></p><p>[8] GoogleTest: Sample Examples for usage<br><a href="https://github.com/google/googletest/tree/main/googletest/samples"><strong>https://github.com/google/googletest/tree/main/googletest/samples</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cbc899213b5" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/codespaces-c-hello-world-project-with-unit-tests-1cbc899213b5">Codespaces: C++ ‘Hello World’ Project with Unit Tests</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS 2 with Docker [Part 1]]]></title>
            <link>https://divyanshu-raj.medium.com/ros-2-with-docker-part-1-9060f3095811?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/9060f3095811</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 23:26:51 GMT</pubDate>
            <atom:updated>2023-09-06T11:28:17.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>ROS 2 and it’s GUI with docker containers and GIT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_3CepvaaOh7gUvqB" /><figcaption>Photo by <a href="https://unsplash.com/@calebrussell?utm_source=medium&amp;utm_medium=referral">Caleb Russell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a part 1 of tutorial series, on how to setup and run ROS 2 (humble) within docker containers along with GUI display for rqt_graphs, etc. This will directly pull and push the code to GitHub. We will not dig deeper into ROS 2 itself for this part, but focus on the setup. This will run on any OS with a working docker.</p><h4>Contents</h4><ul><li>Installation</li><li>Docker for noVNC (for GUI display)</li><li>Docker for ROS 2 (Humble)</li><li>Drawing Circle with TurtleSim</li></ul><h4>Installation</h4><p><strong>Docker: </strong>Install docker and make sure that docker is up and running and has been tested with “hello-world” image.</p><p><a href="https://docs.docker.com/get-docker/">https://docs.docker.com/get-docker/</a> follow this link for installation.</p><p>For windows, WSL (Windows Subsystem for Linux) is required. You can use this link for installation: <a href="https://learn.microsoft.com/en-us/windows/wsl/install">https://learn.microsoft.com/en-us/windows/wsl/install</a></p><p>After installation, run this command:</p><pre>docker run hello-world</pre><p>This will print a message, which means it is installed and running. If not, please debug and make sure you have a running docker.</p><p><strong>GitHub: </strong>Have a github profile and fork <a href="https://github.com/divyanshuraj6815/experiments"><strong>this</strong></a> repository. Make sure it is public and copy the link for cloning it.</p><h4>Docker for noVNC</h4><p>We can use <a href="https://novnc.com/info.html">noVNC</a>, a remote-desktop web client, to visualize the GUIs of ROS applications in a browser.</p><p>First of all we need to create a Docker network that our containers can use to communicate. Let’s create a Docker network called <em>ros</em>:</p><pre>docker network create ros</pre><p><strong>Set up noVNC:</strong></p><p>Thanks to <a href="https://github.com/theasp/docker-novnc">this project</a>, we can launch noVNC in a Docker container using the Docker image theasp/novnc:latest. Download the image:</p><pre>docker pull theasp/novnc:latest</pre><p>Then run this image in a new container:</p><pre>docker run -d --rm --net=ros \<br>   --env=&quot;DISPLAY_WIDTH=3000&quot; \<br>   --env=&quot;DISPLAY_HEIGHT=1800&quot; \<br>   --env=&quot;RUN_XTERM=no&quot; \<br>   --name=novnc -p=8080:8080 \<br>   theasp/novnc:latest</pre><p>noVNC should now be running as a web application inside the container and listening on port 8080. Since we have mapped that port to 8080 on the host, we should be able to see the noVNC interface at http://&lt;host name&gt;:8080/vnc.html . For example, if the host is our local machine then that will be <a href="http://localhost:8080/vnc.html">http://localhost:8080/vnc.html</a> . Open this in a modern web browser (not IE) and click the <em>Connect</em> button. You should see see a blank desktop, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijWYs-gwrPtrWTD5gZPpZA.png" /><figcaption>noVNC browser view (image by Author)</figcaption></figure><p>When we run the GUI command in ros2, we can come back to this screen and click on “Connect” to view the GUI.</p><h4>Docker for ROS 2 Humble</h4><p>We will create a Dockerfile to define the environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb1110ee5e63a35b300194db17ec7e1e/href">https://medium.com/media/fb1110ee5e63a35b300194db17ec7e1e/href</a></iframe><p>We have used the image from docker hub “osrf/ros:humble-desktop-full” as the base image, on top of which we have installed:</p><ul><li><strong>git</strong>: to pull and push code directly from container</li><li><strong>pip3</strong>: to resolve a dependency issue</li><li><strong>vim</strong>: to run a code editor inside container</li></ul><p>After the installation is complete, we have cloned a git repository and set user email and name. In your case, you would fork the given repository and put your git clone link, mail and user. When the container is opened in interactive mode, we can write code and commit to github before we exit the container.</p><p>We have added a ENV variable to connect to noVNC for the GUI display.</p><p>Let’s build the image with tag as “draw_circle”. You need to be in the file path where above Dockerfile is present.</p><pre>docker build -t draw_circle .</pre><p>Once it is successfully built, we will launch the container in interactive mode. If you face issues with Windows (Docker Desktop), change the config:</p><p>Docker Desktop → <em>Settings</em> → <em>Docker Engine</em> → change the “features”: { buildkit: true} to “features”: { buildkit: false}.</p><pre>docker run -it --net=ros draw_circle bash</pre><p>In this command:</p><ul><li><strong>-it</strong> means interactive mode,</li><li><strong>--net=ros</strong> is to connect to docker network that we created named “ros”</li><li><strong>draw_circle</strong> is the tag name of image</li><li><strong>bash</strong> is for getting a terminal to execute commands</li></ul><p>After the execution of above command, you will enter into the container in interactive mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCB4MfEKThkacoGFp7vCog.png" /><figcaption>docker interactive mode (image by Author)</figcaption></figure><p>Every time we enter into interactive mode, we will execute the below 2 statements:</p><pre>source /opt/ros/humble/setup.sh<br>source /experiments/ros_experiment_1_ws/install/setup.sh</pre><p>This allows the “ros2” command to be executable.</p><p>We are all set now!</p><h4>Drawing Circle with TurtleSim</h4><p>We will open 3 terminals connected to the same container ID. To do this, start a interactive container, then open another terminal and fetch the ID using this command:</p><pre>docker ps -l</pre><p>This will display all the containers running along with the ID’s. We need to look for the container with IMAGE name as “draw_circle”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eL4iEMe4H6yQMI7J83XcwA.png" /><figcaption>List of running containers (image by Author)</figcaption></figure><p>Once we have the container ID, we will connect to the container using this command:</p><pre>docker exec -it &lt;Container_ID&gt; bash</pre><p>Once connected, we will run these 2 commands again:</p><pre>source /opt/ros/humble/setup.sh<br>source /experiments/ros_experiment_1_ws/install/setup.sh</pre><p>Similarly we want to have 3 terminals running, one for publisher, one for subscriber and one to run command to view rqt_graph.</p><p><strong>Subscriber:</strong></p><pre>ros2 run turtlesim turtlesim_node</pre><p>This will start the turtlesim node which is a subscriber, and when we click on the noVNC “Connect”, we can see a static turtle. In one of the terminal we will also run the command “rqt_graph” to view the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TlVpUsP-kobc5VWoTwxrQ.png" /><figcaption>Subscriber and rqt_graph (image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MD8tlj4qRDevjOJ6GD3Opg.png" /><figcaption>noVNC display for Turtlesim and rqt_graph (image by Author)</figcaption></figure><p>We can observe here, that the turtlesim node that we ran is a subscriber to the topic “/turtle1/cmd_vel”.</p><p><strong>Publisher:</strong></p><p>We will run the publisher that will publish to cmd_vel topic.</p><p>The code to draw circle is at this path:</p><pre>/experiments/ros_experiment_1_ws/src/my_robot_controller/my_robot_controller/draw_circle.py</pre><p>Let’s have a quick look at the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3847a5497e8c1ec1508c681e7f929cf/href">https://medium.com/media/f3847a5497e8c1ec1508c681e7f929cf/href</a></iframe><p>In the above code, we have set the timer for every 0.5 second to publish a message to the given topic, in the Twist format, to move a certain distance with linear and angular momentum.</p><p>The structure is created using ROS 2 workspaces. (No need to run this for now)</p><pre>ros2 pkg create my_robot_controller --build-type ament_python --dependencies rclpy</pre><p>We will build using colcon build:</p><pre>cd /experiments/ros_experiment_1_ws/<br>colcon build --symlink-install</pre><p>Once the build is successful, we can run the publisher using this command:</p><pre>ros2 run my_robot_controller draw_circle</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vxel73LSUazYVrcdjzVocQ.png" /><figcaption>draw circle with Turtlesim (image by Author)</figcaption></figure><p>As we can see, the turtle is moving in circles. The rqt_graph shows, that draw_circle is publishing to the “/turtle1/cmd_vel” topic to which the turtlesim is subscribed.</p><p>These are the 3 terminals running publisher, subscriber and graph within same container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Lda5dfvox5o-RLyRrQ3lIA.png" /><figcaption>3 terminal connected to same container in interactive mode (image by Author)</figcaption></figure><p>You can try to make changes to draw_circle file such that the turtle draws some other shape such as square, oval or some other patterns and test it out. Make sure to commit the code to github, before you exit the interactive terminal.</p><p>Don’t forget to kill all the container at the end. We will do more interesting stuff in the coming parts.</p><h4>References</h4><ul><li><a href="http://wiki.ros.org/docker">Wiki</a></li><li><a href="https://hub.docker.com/r/osrf/ros">Docker</a></li><li><a href="https://docs.ros.org/en/humble/index.html">ROS 2 Documentation - ROS 2 Documentation: Humble documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9060f3095811" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baby Steps to Quantum Machine Learning]]></title>
            <link>https://medium.com/data-science/baby-steps-to-quantum-machine-learning-796715c19d32?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/796715c19d32</guid>
            <category><![CDATA[quantum-machine-learning]]></category>
            <category><![CDATA[penny-lane]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 16:00:33 GMT</pubDate>
            <atom:updated>2022-11-08T16:00:33.182Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Basic concepts related to Quantum Machine Learning and training a hybrid model for Iris Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4frHkomysNHcAKC" /><figcaption>Photo by <a href="https://unsplash.com/@vlisidis?utm_source=medium&amp;utm_medium=referral">Terry Vlisidis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Quantum Machine Learning is the next step in the tech field. In this article, we will understand the basic concepts involved in Quantum with Machine Learning. Then we will understand how to train a multi-class hybrid classifier with Keras and Pennylane using the Iris dataset. <a href="https://github.com/divyanshuraj6815/QUANTUM-ML/blob/main/Quantum_Machine_Learning_(Iris_Dataset).ipynb"><strong>Code</strong></a></p><h4><strong>Basic Concepts</strong></h4><p>The representation in Quantum chemistry can be understood with the below diagram, say if there are 3 energy levels and each energy level have 2 electrons, one electron will have an upward spin whereas the other will have a downward spin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWJd0_G70c3A3mc1nCHgug.png" /><figcaption>Quantum Chemistry, representation (Image by Author)</figcaption></figure><p>The 2nd diagram has one electron with a downward spin in the first energy level and one electron with an upward spin in the third energy level.</p><p>In Quantum Machine learning we leverage this concept and define circuits, where we have several functionalities, such as giving a rotation on the X, Y, and Z axis for an energy level, tying a knot between energy levels, splitting, etc.</p><h4><strong>Q Node:</strong></h4><p>A Q Node consists of a circuit and a device on which the circuit will be executed.</p><p><strong>Devices:</strong></p><p>There is a list of available devices here (<a href="https://pennylane.ai/plugins.html">https://pennylane.ai/plugins.html</a>) that can be used. In general “default.qubit” is used. For the hybrid model used to train Iris data, we will use the “strawberryfields.fock” device. These devices are used as a plugin, so make sure the plugin is installed. For strawberryfields, run this to install:</p><pre>pip install PennyLane<strong>-</strong>SF</pre><p>Let’s define the device:</p><pre>dev <strong>=</strong> qml<strong>.</strong>device(&quot;default.qubit&quot;, wires<strong>=</strong>num_modes)</pre><p><strong>Circuit:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*8_DsBtaC7D6jrjWha4CmYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*l3hUbYZJC5fJTfXI7avOrw.png" /><figcaption>Circuit Diagram (Left), Equivalent Code (Right), Image by Author</figcaption></figure><p>We defined the circuit given in the diagram to the left. There are 2 wires, 0 and 1. If we look at it as a time series, first there is an X on wire 1,</p><pre>qml.PauliX (wires = 1)</pre><p>then there is an intersection from wire 0 onto 1,</p><pre>qml.CNOT (wires = [1, 0])</pre><p>then there is a rotation along Ry with theta angle on wire 0.</p><pre>qml.RY (theta, wires = 0)</pre><p>The output Z also comes out of wire 1 along the Z axis.</p><pre>qml.PauliZ (wires = 0)</pre><p>Finally, we are returning the expectation value along the Z axis.</p><pre>qml.expval ()</pre><p>Now, that we know about the device and the circuit, we can easily define a Q node by a decorator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*fqcRFAZu9YwrglBc5ec0YA.png" /><figcaption>Q Node (Image by Author)</figcaption></figure><p>Now, let’s vary the angle from -π to π, and see the value of the circuit function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*N8_wPorsL7osc_PFCflRCg.png" /><figcaption>Circuit (theta) v/s [-π, π] (Image by Author)</figcaption></figure><p>So, when we are trying to optimize the circuit, from the machine learning perspective, we are trying to find the value of weights with which we can achieve the minimum value i.e. -1. given random weights as input to a circuit. In general, we do not know what this graph looks like, hence we use an optimizer.</p><p>An <strong>ansatz</strong> is <strong>a basic architecture of a circuit, i.e., a set of gates that act on specific subsystems</strong>. The architecture defines which algorithms a variational circuit can implement by fixing the trainable parameters. A circuit ansatz is analogous to the architecture of a neural network</p><h4>The Hybrid Model</h4><p>Now, that we understand the basics, let&#39;s define the architecture of a hybrid model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NdS6HWU2gPGTmIuDiPZYA.png" /><figcaption>High-Level hybrid Architecture (Image by Author)</figcaption></figure><p><strong>Dense Layers:</strong></p><p>The Iris dataset has 4 features, which go as Input. After that, we have 2 dense layers of 14 channels which will be fed to the data encoding layer or the circuit. By directly not feeding the features to the quantum circuit and using dense layers, we allow the input to be more flexible and able to learn what inputs should be given to the circuit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOBPDutrB48dP_0dxhm8EA.png" /><figcaption>Dense Layers (Image by Author)</figcaption></figure><p><strong>Quantum Layers:</strong></p><p>First, we encode the 14 channels to a circuit and then each channel goes through a quantum neural network that is defined with Keras and Pennylane libraries. For the circuit, we have 2 wires and 14 inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDb5TT-Jl7-vicJ2cjCVQg.png" /><figcaption>Data Encoding Layer (Image by Author)</figcaption></figure><p>The output from the data encoding layer is fed into the Quantum Neural Network defined below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlg5-QROT-04LpYhWJeZWA.png" /><figcaption>Quantum Neural Network (Image by Author)</figcaption></figure><p><strong>Output:</strong></p><p>The output is a 16-dimension vector. 3 for output labels and 13 for padding with 0. When we are dealing with quantum machine learning, the output of a circuit just cannot be a one-hot encoding of the total number of labels. So, we need to define a custom one-hot encoding function for it, which will have more dimension than the number of classes.</p><p>For Instance, if there are 3 classes, one-hot encoding will have 8 dimensions, 3 for actual classes, and the remaining 5 padded with 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zab8wnNFvajNSBLwqnk6WQ.png" /><figcaption>One Hot encoding for labels (Image by Author)</figcaption></figure><p>The overall model architecture looks like this:</p><pre>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> dense (Dense)               (None, 14)                70        <br>                                                                 <br> dense_1 (Dense)             (None, 14)                210       <br>                                                                 <br> keras_layer (KerasLayer)    (None, 4)                 56        <br>                                                                 <br>=================================================================<br>Total params: 336<br>Trainable params: 336<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>These are the results, after training for 30 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*_rw4MqnBpuzZbTTfsW9HnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*QZFjMYezOf1ovhQi0pxx0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*bSAl65vT-Yr4wCXGqHDFrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*m0BJpRu-X7TvWKKyAArICA.png" /><figcaption>Accuracy and Loss Graphs for Train and Validation splits (Image by Author)</figcaption></figure><p>This article focus on an understanding of functioning with Quantum Neural Network and the concepts behind that. Quantum Machine learning has benefits over traditional machine learning methods used now in terms of computing and learning capacity. I will write more on the use cases with traditional datasets such as MNIST, CIFAR10, etc in future blogs. Let me know your thoughts on this.</p><p><strong>References:</strong></p><p><a href="https://pennylane.ai/qml/demonstrations.html">Pennylane Demonstrations</a></p><p><a href="https://arxiv.org/pdf/1806.06871v1.pdf">Continuous-variable quantum neural networks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=796715c19d32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/baby-steps-to-quantum-machine-learning-796715c19d32">Baby Steps to Quantum Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are 1000 Seconds Enough to Train?]]></title>
            <link>https://medium.com/data-science/are-1000-seconds-enough-to-train-538f45635537?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/538f45635537</guid>
            <category><![CDATA[cyclic-learning-rate]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 18:30:51 GMT</pubDate>
            <atom:updated>2024-04-23T17:42:34.968Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designing a single strategy with 3 datasets—MNIST, Fashion MNIST, and CIFAR 10—to achieve near SOTA accuracy within 1000 seconds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgrEAQTunVFqZZVDOfkWgg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kevin Ku</a> on <a href="https://unsplash.com/s/photos/time?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is an experiment where several optimization techniques for faster convergence have been tried for MNIST, Fashion MNIST, and CIFAR 10 dataset, with the only restriction of 1000 seconds on the Google colab provided GPUs. This is helpful when building in-house models or experimenting with a dataset, this technique can be used as base case accuracy.</p><p>The main goal is <strong>Faster Convergence and a Generalized model</strong>. Final result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42791f61d8887425540b7697117de43/href">https://medium.com/media/b42791f61d8887425540b7697117de43/href</a></iframe><p><strong>Content (step-by-step optimization):</strong></p><ul><li>The Model</li><li>The Data</li><li>The Learning Rate</li><li>Explainability with heatmap</li></ul><h4>The Model</h4><p>The first step is to find the right model. The model should have fewer parameters as well as residual properties for faster convergence. There is an online competition about fast training called <a href="https://dawn.cs.stanford.edu/benchmark/#cifar10">DAWNBench</a>, and the winner (as of April 2019) is David C. Page, who built a custom 9-layer Residual ConvNet, or ResNet. This model is referred to as “DavidNet”, named after its author. Below is the architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jt56AJlwDDo5PYXf_E63Lg.png" /><figcaption>ResNet Architecture (Image by Author)</figcaption></figure><p>We will use the above model architecture and define it in PyTorch. See the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c588d29b7a667f435d469a5ea392d9/href">https://medium.com/media/b5c588d29b7a667f435d469a5ea392d9/href</a></iframe><p>This model has 6.5 million parameters which is a very small model compared to other larger residual models such as ResNet50 or Vision Transformers.</p><p>The model itself will not be enough to achieve high accuracy in a short span of time. We need to optimize the data as well.</p><h4>The Data</h4><p>There are 2 optimizations that will be performed with the data.</p><p><strong>Augmentation:</strong></p><ul><li><strong>Normalize</strong> the Image with the mean and standard deviation of the entire dataset. Normalized Images help in faster convergence.</li><li>Pad the Image that increases 8 pixels in both height and width and then takes a <strong>random crop</strong> of the image. This helps in creating different x, and y coordinates of the original image.</li><li><strong>Horizontal flip</strong> with 50% probability.</li><li>Randomly mask a percentage of Image. <strong>Random cutout </strong>helps to avoid overfitting.</li></ul><p>All the above augmentation when applied simultaneously will generate a lot of combinations of images and it is highly unlikely that the model will be trained with the same image with the same orientation in any of the epochs. Below are some examples from all the 3 datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*2Sw_K-XPbF0pNwaAvx0iGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*gdC-rZFlsPOVPuEjAcpaXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*x1ZXd76iCDFBHL1x4__6TA.png" /><figcaption>Random Images from Fashion MNIST dataset (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*YolHVa8nmMI8GYQ3jiyHbw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*6Ln_h3v3INljf9WnL6Ylpw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*PgtZeJCizZJszOTpQWwtwA.gif" /><figcaption>Showing various <strong>Data Augmentation</strong> done after normalization for Images from <strong>Fashion MNIST</strong> dataset (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*Ugd5Y3brWD5IdR6pbRfDjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*QUFOoarhTEUpHE1Xk1qQHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*aGPTzAgnfrWYmC_X1d9oBg.png" /><figcaption>Random Images from MNIST dataset (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*JWl-wy_bWS3uZSR-FjQYfQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*0V6dBOTRIKcxyqIXntSzyw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*mEk6d54_MVkXA8eqLEOA0g.gif" /><figcaption>Showing various <strong>Data Augmentation</strong> done after normalization for Images from <strong>MNIST</strong> dataset (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*n9hZLY1jZ1-dcuP1-xD-Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*0c0Reueb35GvW9p-qVXgnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*jhDXyxTF20qwsN74KUk3ZQ.png" /><figcaption>Random Images from CIFAR 10 dataset (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*RvH1NoA_ZjUFu_aksP6Y0Q.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*9RH0aJ9CeilxUyLBoqBYEA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*BbqzsW7VI1elpev6csCzAw.gif" /><figcaption>Showing various <strong>Data Augmentation</strong> done after normalization for Images from <strong>CIFAR 10</strong> dataset (Image by Author)</figcaption></figure><p><strong>Pre Computation:</strong></p><p>The augmentation when applied while training slows down the training process. Say when a batch is to be given to the model, first the augmentation needs to be applied to the Image. During that time the GPU is idle and it is not being utilized to most of its capacity.</p><p>Therefore, we will compute all the data augmentations for the number of epochs we plan to train and store all the data variations as tensor flow records. Even when the data is huge, computing augmentation will take time, but once stored as <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">tf records</a>, it can be loaded on the flow from disk without causing any delays.</p><p>So with this, we remove the time taken for augmentation from the total training time, which is a significant amount of time. Code below to read and write tf records.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8b0591b78909e2772cba28e7d4e9835/href">https://medium.com/media/f8b0591b78909e2772cba28e7d4e9835/href</a></iframe><p>Now, we are done with model and data optimizations. But that still is not enough to achieve the results we desire. We need to optimize one more parameter for faster convergence and that is the optimizer and learning rate scheduler.</p><h4>The Learning Rate</h4><p>We will be using one cycle policy for 25 epochs. Below is the learning rate scheduler graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XK8CruB3FElnui1r1R-oyA.png" /><figcaption>One Cycle Learning Rate for training (Image by Author)</figcaption></figure><p>The reason for faster convergence is explained in the below gif.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*6A2KzCRb_WdEYRPW9t-fLQ.gif" /><figcaption>Intuition for Gradient Descent finding minima with varying Learning rate techniques (Image by Author)</figcaption></figure><p>To develop the intuition behind it, we can observe the above gif. The highest accuracy is the lowest possible minima we can find. A constant learning rate will help to find a minima that might not be best. So, to find the best minima we first provide momentum to the algorithm. This will allow it to bounce off the local minima. Then we gradually decrease the learning rate, assuming that at this point in time it is in the global minima section instead of the local minima. Decreasing the learning rate will help it settle down at the bottom as indicated in the gif above.</p><p>Now we are all set to train the model and record the time and accuracy.</p><h4><strong>Training</strong></h4><p>We train for 25 epochs on all the 3 datasets. These are the stats:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42791f61d8887425540b7697117de43/href">https://medium.com/media/b42791f61d8887425540b7697117de43/href</a></iframe><p>We can observe that we are able to achieve very good accuracy that is not very far from SOTA accuracies for all the 3 datasets given the time and resource constraints.</p><p>The accuracy and loss graphs for all three datasets are provided below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_sERuwCDW2J_v5vHvpgOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hX3L-Ap1HLxE_R1rK-amFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3jzDvS5VYb8PKjzatdoPA.png" /><figcaption>Accuracy and Loss Curves for <strong>MNIST</strong> (left), <strong>Fashion MNIST</strong> (center), and <strong>CIFAR 10</strong> (right) (Image by Author)</figcaption></figure><p>Finally, we also want to know if our model is robust. To do so, we will see the heatmap, by slicing it out of the last few layers to see which part of the image, neurons are more active just before making the predictions.</p><h4>Explainability with heatmap</h4><p>In the diagram below, the heatmap of all images run through the trained model is presented for 2 scenarios, one without data augmentation and one with data augmentation. The accuracy is low without data augmentation and as you can see in the diagram below, the model is looking at a more logical section of the image while making predictions when data augmentation techniques are used. Thus making the model more generalized and helping in faster convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRd8tHRPnewfraPnfa_fJg.png" /><figcaption><strong>Heatmap for CIFAR 10</strong>, to understand where the model is looking to make the predictions (Image by Author)</figcaption></figure><p>The same experiment can be tried with other datasets as well. Although this might not scale for larger datasets with larger image sizes, it will work best for smaller datasets such as those used in this experiment. This can be used as a base case to further optimize and get better accuracy.</p><p>In this article, we have explored various techniques for faster training and faster convergence starting with a small but efficient residual network, effective data augmentation techniques that maximize the GPU usage utilization, and one cycle learning rate policy. Combining all this we were able to achieve near SOTA accuracy with publicly available resources within 1000 seconds and 25 epochs. Finally, we evaluate the heatmap to understand the model explainability and whether the model is generalized enough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538f45635537" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/are-1000-seconds-enough-to-train-538f45635537">Are 1000 Seconds Enough to Train?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semi-Supervised Approach for Transformers [Part 2]]]></title>
            <link>https://medium.com/data-science/semi-supervised-approach-for-transformers-part-2-8f8bf6edd912?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8bf6edd912</guid>
            <category><![CDATA[siamese-networks]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 15:26:03 GMT</pubDate>
            <atom:updated>2024-04-23T17:39:51.306Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Siamese Network structure to fine-tune the RoBERTa model and train a Natural Language Inference Classification task</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_1ZfBDO1MdORxAXTmPmMw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@fcornish?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Faye Cornish</a> on <a href="https://unsplash.com/s/photos/reflection?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article will use Siamese architecture to fine-tune the RoBERTa model. We will also observe the dataset&#39;s embedding distribution with PCA and TSNE as we fine-tune and train it. Training will happen on the fine-tuned RoBERTa model for Natural Language Inference classification (a subset of SNLI).</p><p><a href="https://github.com/divyanshuraj6815/END-NLP/blob/main/Experiment%2022/Semi_Supervised_NLI_(Small)_Training_(Siamese).ipynb"><strong>Code</strong></a> for this article. To understand the intuition behind the semi-supervised approach for transformers read <a href="https://towardsdatascience.com/semi-supervised-approach-for-transformers-38722f1b5ce3"><strong>Part 1</strong></a>.</p><h4>Dataset</h4><p>A subset of the <a href="https://huggingface.co/datasets/snli"><strong>SNLI</strong></a> dataset is used for training. <strong>20,000 training samples</strong>, 10,000 validation samples, and 10,000 test samples. The NLI (Natural Language Inference) dataset has a premise and a hypothesis. The goal of the model is to predict whether the hypothesis is in contradiction, entailment, or neutral to the premise.</p><p>The original dataset has ~550,000 training samples. This experiment done on the full set will yield better results.</p><p>Let’s view the dataset analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnVK3nN7tI-losv4alh55g.png" /><figcaption>Dataset Analysis (Image by Author)</figcaption></figure><p>We can observe from the above graph that the dataset is balanced. Max sentence length can be estimated as <strong>64 words</strong> after concatenating the premise with the hypothesis.</p><h4>Model</h4><p>We will be using 2 models for this. The first one is for Siamese architecture to fine-tune RoBERTa. The second model will have a classification head to predict whether the sentences are entailment, contradiction, or neutral to each other.</p><p><strong>Sentence Transformer Model:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaaa2d6c3c0a1eec741ec1c0351eaa0c/href">https://medium.com/media/aaaa2d6c3c0a1eec741ec1c0351eaa0c/href</a></iframe><p>The output of this model is a 768 feature or the context vector. We will compute embeddings for premise and hypothesis simultaneously and use <strong>cosine similarity loss</strong> to fine-tune the model.</p><ul><li>-1 for contradiction</li><li>0 for neutral</li><li>1 for entailment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*gCf4TbP6OlkNySHjESptMQ.png" /><figcaption>Siamese Architecture (Photo from <a href="https://sbert.net/examples/training/sts/README.html">sbert.net</a>)</figcaption></figure><p>The above diagram represents the architecture. After the fine-tuning is done, the weights of the RoBERTa model are saved for further downstream tasks.</p><p><strong>Auto Model For Sequence Classification:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b73cfa1d8a38580bb7b976e75a9e0e0/href">https://medium.com/media/9b73cfa1d8a38580bb7b976e75a9e0e0/href</a></iframe><p>After fine-tuning the model with the Siamese architecture we will use the same RoBERTa weights to define a sequence classification model. In this model, the new weights will be assigned only to the last “classifier” layer. This will be further trained on the training data with a cyclic learning rate and Adam optimizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*y_PDqPdlaRk-b3BtPInBlQ.png" /><figcaption><strong>Cosine Scheduler</strong> for Learning Rate (Image from <a href="https://huggingface.co/docs/transformers/main_classes/optimizer_schedules#transformers.get_cosine_with_hard_restarts_schedule_with_warmup">HuggingFace</a>)</figcaption></figure><p>A learning rate 2e-5 with a cosine scheduler having 2 cycles is used for training. This is to avoid overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSbx77Vx4OlrYr8RqJRKFQ.png" /><figcaption>Graphs for Loss (<strong>left</strong>) and Accuracy (<strong>right</strong>) (Image by Author)</figcaption></figure><p>The above graph displays the loss and accuracy curves for the sequence classification. Test accuracy of 87% is achieved.</p><blockquote>After training, we will save the weights. These weights can be again loaded to the Sentence Transformer model, and trained for a couple of epochs to get even better sentence embeddings.</blockquote><h4>Sentence Embeddings Analysis</h4><p>We have trained the model 3 times:</p><ul><li>Load the original RoBERTa weights into Sentence Transformers to train with Siamese architecture. We can save these fine-tuned weights.</li><li>Load the fine-tuned weights from the above training into a sequence classification model with RoBERTa. After training, we save these weights.</li><li>Load the weights from the above step into Sentence Transformers to train with Siamese architecture for a couple of epochs and then save the weights.</li></ul><p>The sentence embeddings for all the sentence pairs in the training set are saved 3 times:</p><ul><li>Original RoBERTa weights.</li><li>After fine-tuning with Siamese architecture.</li><li>After sequence classification and fine-tuning with Siamese architecture again.</li></ul><p>On these 3 versions of sentence embeddings, we will run PCA and TSNE fit to analyze the effect of fine-tuning with the dataset. The following graphs represent the analysis:</p><p><strong>Graph 1: </strong>We run PCA with n_components = 3 on all the 3 instances of sentence embeddings and plot the graph for 2 dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Kic8Jz1k_ePPk4y5AjjVHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*U65CQmHMfxrhejhKazZipA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*9Jfit7LT9zD7kv9NoONlcA.png" /><figcaption>PCA (n = 3), Graph for <strong>PCA-x, PCA-y</strong> : Original RoBERTa (<strong>left</strong>), Fine Tuning with Siamese (<strong>center</strong>), After NLI Classification (<strong>right</strong>). (Image by Author)</figcaption></figure><p><strong>Graph 2: </strong>We run PCA with n_components = 3 on all the 3 instances of sentence embeddings and plot a 3D graph for all the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*CyY_hnAI3TlrCKNrc9oSKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*K1ns95FuDLeYBQdiWHd7xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*cI7uWeHd2Dg2GGPm-N_tng.png" /><figcaption>PCA (n = 3), Graph for <strong>PCA-x, PCA-y, PCA-z</strong> : Original RoBERTa (<strong>left</strong>), Fine Tuning with Siamese (<strong>center</strong>), After NLI Classification (<strong>right</strong>). (Image by Author)</figcaption></figure><p><strong>Graph 3: </strong>We run TSNE fitting with n_components = 2 on all the 3 instances of sentence embeddings and plot the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*NDxwurc1E8yCu_ZNtsFNdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*sgBcv_T2nxPrbSFqxOg50g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*-CMKK0MEO_7eLg_0wY99Qg.png" /><figcaption>TSNE (n = 2), Graph for <strong>X, Y</strong> : Original RoBERTa (<strong>left</strong>), Fine Tuning with Siamese (<strong>center</strong>), After NLI Classification (<strong>right</strong>). (Image by Author)</figcaption></figure><p><strong>Graph 4: </strong>We run PCA with n_components = 50 and run TSNE fitting on top of it with n_component = 2 on all the 3 instances of sentence embeddings. In this graph, we compare the plot for the previous 2 plots and the current plot.</p><p><strong>Graph 4.1: </strong>For original RoBERTa weights. The observation on this is that all the data points are scattered and no logic is sufficient to show a clear distinction between sentence pair embeddings based on their label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Ig20-3-xiywm51i-Ml1SUg.png" /><figcaption>Comparison of <strong>PCA[</strong>n = 3<strong>][X, Y] </strong>(<strong>left</strong>), <strong>TSNE[</strong>n = 2<strong>][X, Y] </strong>(<strong>center</strong>), <strong>TSNE[</strong>n = 2, PCA[n = 50]<strong>][X, Y]</strong> (<strong>right</strong>) for <strong>Original RoBERTa</strong> (Image by Author)</figcaption></figure><p><strong>Graph 4.2: </strong>After fine-tuning the Siamese architecture we can observe some distinctions between sentence pair embeddings based on their label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*0SukfuUfeADtOz9X6CAnhQ.png" /><figcaption>Comparison of <strong>PCA[</strong>n = 3<strong>][X, Y] </strong>(<strong>left</strong>), <strong>TSNE[</strong>n = 2<strong>][X, Y] </strong>(<strong>center</strong>), <strong>TSNE[</strong>n = 2, PCA[n = 50]<strong>][X, Y]</strong> (<strong>right</strong>) for <strong>Siamese RoBERTa</strong> (Image by Author)</figcaption></figure><p><strong>Graph 4.3: </strong>After sequence classification and fine-tuning the Siamese architecture we can observe that there is a clear distinction between sentence pair embeddings based on their label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*uHil_sFbwtM7jci9vTr-JA.png" /><figcaption>Comparison of <strong>PCA[</strong>n = 3<strong>][X, Y] </strong>(<strong>left</strong>), <strong>TSNE[</strong>n = 2<strong>][X, Y] </strong>(<strong>center</strong>), <strong>TSNE[</strong>n = 2, PCA[n = 50]<strong>][X, Y]</strong> (<strong>right</strong>) for <strong>RoBERTa</strong> after <strong>NLI</strong> Classification (Image by Author)</figcaption></figure><p>I have presented the impact of training a transformers model with a semi-supervised approach that always leads to a robust model. This experiment was done on a small set of 20,000 data points. Doing this on an actual dataset will have a bigger impact. There are already fine-tuned models with Siamese architecture on huggingface that be used directly.</p><p>Other techniques can be used to better cluster or visualize the sentence pair embeddings. These visualizations can also be done for any other NLP task.</p><h4>References:</h4><ol><li><a href="https://arxiv.org/abs/1908.10084">Sentence BERT</a></li><li><a href="https://papers.nips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf">Attention is all you need</a></li><li><a href="https://sbert.net/examples/training/sts/README.html">Sentence Transformers for Semantic Textual Similarity</a></li><li><a href="https://hamedhelali.github.io/project/Fine-tuning-BERT-For-NLI/">Fine Tuning BERT for Natural Language Inference</a></li><li><a href="https://towardsdatascience.com/visualising-high-dimensional-datasets-using-pca-and-t-sne-in-python-8ef87e7915b">Visualizing high-dimensional datasets using PCA and t-SNE in Python</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8bf6edd912" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/semi-supervised-approach-for-transformers-part-2-8f8bf6edd912">Semi-Supervised Approach for Transformers [Part 2]</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semi-Supervised Approach for Transformers]]></title>
            <link>https://medium.com/data-science/semi-supervised-approach-for-transformers-38722f1b5ce3?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/38722f1b5ce3</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Tue, 03 May 2022 15:18:34 GMT</pubDate>
            <atom:updated>2022-05-12T05:26:47.403Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical approach to training Transformers-based models to achieve robustness and high accuracy with a semi-supervised approach.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWeMU99YSCE4BPEPotLg_A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arseny Togulev</a> on <a href="https://unsplash.com/s/photos/transformers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Transformers models have become the go-to model for NLP tasks. In this article, we will go through the end-to-end process of training highly robust NLP models using Transformers architecture, following a top-down approach. We always try to use a semi-supervised approach to train an NLP model be it classification or generation.</p><p>Majorly, we will be discussing fine-tuning BERT, and Text Classification. Let’s start by getting an overall picture and then get into details.</p><p>For data augmentation with Text, read this <a href="https://medium.com/analytics-vidhya/data-augmentation-for-text-with-code-6da46aad443d">article</a>.</p><h4><strong>Understanding the Semi-Supervised Transformers Architecture</strong></h4><p>Training a semi-supervised model requires 2 steps:</p><ul><li>Train the unsupervised part first. That is training the language model. For transformers, it can be fine-tuning BERT, GPT, etc. For this part of training, we only need unlabeled data or sentences. This step adjusts the weights of the model so that it can understand the context of the data we want to train it on. Context can be fashion, news, sports, etc. For example, the word “sleeping” can have a different context when we are trying to train a model for “fashion” v/s a model for “news”.</li><li>Train the supervised part second. That is train the model with the labeled data. If the first part had a huge amount of data, the supervised part will have high accuracy even with a low amount of data, but vice versa is not true.</li></ul><p>The below diagram is a GIF of semi-supervised training. First, we fine-tune BERT, then we train a Text Classifier or a Named Entity Recognition model. It gives a visual idea of the linkage between fine-tuning language model and then using the fine-tuned model for classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*O2GSObfbVdNEpLXxbx2cFQ.gif" /><figcaption>End to End Flow for <strong>Fine-tuning BERT</strong>, training a <strong>Text Classification</strong> Model, and training a <strong>NER</strong> Model (Image by Author)</figcaption></figure><p>Let’s go over all the components of the above diagram:</p><h4><strong>Embeddings Layer:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*bof_cbEin8qfRYNQ30luMQ.jpeg" /><figcaption>Embedding Layer (Image by Author)</figcaption></figure><p>The main job of the embedding layer is to convert the textual input data to a model understandable format. It has three main components:</p><ul><li><strong>word embeddings:</strong> This is to get the matrix representation of each word. For BERT this has a vocabulary size of 30,522 and an array of 768 values represents a word. So, if the input is of 4 words, the output of word embeddings will be 4 x 768.</li><li><strong>position embeddings: </strong>This is used to get the position of the word. In transformers, the position of the word is passed as input as the context of the sentence is highly dependent on the position of the word in the sentence.</li><li><strong>linear layer: </strong>This layer is a linear convolution layer, to merge the layers and finally provide a matrix with 768 features.</li></ul><h4><strong>Encoder Layers:</strong></h4><p>There are a total of 11 BERT Layers in this encode layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*KTOqOXZwOz8I3y5reXexTw.jpeg" /><figcaption>BERT encoder layers (Image by Author)</figcaption></figure><p>Each layer has 2 main components:</p><ul><li><strong>Self Attention Layer: </strong>This is the core of the Transformers model that helps in determining the importance of each word w.r.t all the other words in the sentence and in the overall context of the sentence. The diagram below shows an embedding being used as the key (K), query (Q), and value (V). K, Q, and V go through a couple of layers of convolution, dot-product, and softmax to get the desired output. Self-Attention in itself is a topic that requires much more explanation. If you are not aware of self-attention I suggest you watch this youtube <a href="https://youtu.be/-9vVhYEXeyQ?t=146"><strong>video</strong></a><strong> </strong>for a better understanding.<br>This layer takes an input of 768 features, does a multi-head attention operation, and outputs the matrix with 768 features.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4SBoRFqjleSiDRekvPO9hQ.png" /><figcaption>Multi-Head Attention (Image from <a href="https://wiki.math.uwaterloo.ca/statwiki/index.php?title=STAT946F20/BERT:_Pre-training_of_Deep_Bidirectional_Transformers_for_Language_Understanding"><strong>wiki.math.waterloo</strong></a>)</figcaption></figure><ul><li><strong>Convolution Layers: </strong>These layers are followed by the self-attention layer. It includes a couple of dense layers, layer normalization, dropout, and GELU Activation functions. The number of input and output features for these layers is 768.</li></ul><h4><strong>Context Vectors:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*QHsKDlSBTLmhEe-Xp1v8GQ.jpeg" /><figcaption>Context Vector (Image by Author)</figcaption></figure><p>Not by the definition, but the output of the above 2 layers, embeddings and encodings layers, gives out a matrix with 768 features which is the context of the sentence, therefore we will refer to this as the context vector. This is the <strong>most important part of the model</strong>, as all the training done in the unsupervised part was to train the weights to get context vectors correctly.</p><p>In models such as RNN and LSTM, the input to the model is word embeddings which are unable to capture the context of the sentence. So we train a neural network on top of the word embeddings layer to capture the context of the sentence. Now, this output captures the context with 768 features. This output can be passed as input to classification or generation models making the overall model highly robust and accurate.</p><h4><strong>Language Models:</strong></h4><p>This is an unsupervised part of training. Additional convolutional layers are added to the output of the context vectors. The final output of this model is the matrix with vocabulary size i.e. 30,522. This model needs to predict a word from the existing vocabulary. We feed millions of unlabeled sentences and allow the model to adjust the weights to get appropriate context vectors.</p><p>There are two ways to train a language model:</p><p><strong>Masked Language Model:</strong></p><p>We mask 10–30% of the input sentence and ask the model to predict the masked words. As you can see in the below diagram the input sentence is “women floral printed [MASK] top”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*VAxYiYWJnOnP3D_LE3znsA.jpeg" /><figcaption>Input for MLM (Image by Author)</figcaption></figure><p>Convolution layers are added to the encoder layer to predict the missing word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*fiXZkUem_SRrBOlZkWRSVA.jpeg" /><figcaption>Masked Language Model bottom layers (Image by Author)</figcaption></figure><p>The output of the model is the matrix with vocab size (30,522 in this case) to predict the missing word. Based on the model’s prediction loss is computed and the weights of the models are adjusted.</p><p>After training a BERT language model using Masked Language Model technique for the fashion domain with 20 million sentences, you can clearly observe the difference in the below GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbgB2hoeJH7sSMqhGBQZUw.gif" /><figcaption>Left: <strong>BERT trained on Fashion</strong> data, Right: <strong>original BERT</strong> (Image by Author)</figcaption></figure><p><strong>Input</strong>: women [MASK] top<br><strong>BERT (Fashion)</strong>: women floral printed crop top<br><strong>BERT (Original)</strong>: women who on were top</p><p><strong>Casual Language Models:</strong></p><p>With CLM, the model tries to predict the next word from the existing vocabulary and compares it with the true output. Generally, CLM is used for generative models i.e. GPT architectures. We are not covering GPT-based architectures in this article, but you can have a look at the GIF below showing the difference between a fashion-specific GPT2 model v/s the GPT2 model with original weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*as-AIk35I9rmsp6SzbVqmw.gif" /><figcaption>Left: <strong>GPT2 trained on Fashion</strong> data, Right: <strong>original GPT2</strong> (Image by Author)</figcaption></figure><p>Once BERT/GPT is fine-tuned with the custom dataset, the second part is to train the classification and generation models over it.</p><p>Although while training the weights of the entire model gets updated, for our understanding, we can assume that the context vector is now the input to the models.</p><h4>Text Classification</h4><p>It is a simple classification problem now. In the below diagram, dense layers have been added to the output of context vectors, and finally reduced the features to the number of classes. The better the context layer output, the more robust and accurate the model will be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*fH8GhnZ45uwy_7vAmw3OrA.jpeg" /><figcaption>Text Classification with Context Vectors (Image by Author)</figcaption></figure><p>When we are dealing with Transformers, we can also get the word-level confidence scores that contributed to the prediction of the said class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*drJPihcMHbINmhwqwAjmnA.png" /><figcaption>Analyzing Text Classification Output, Green means positive, Red means negative (Image by Author)</figcaption></figure><p>For the sentence <strong>pantaloons green shirt with jacket, wear it with black jeans, </strong>we are trying to predict a fashion category. The above sentence has lots of categories in it including shirts, jackets, and jeans. But as you can see in the first example it is correctly predicting shirts, with the word shirt having the highest confidence. In other examples, we have changed the ground truth to different labels and then tried to observe the behavior. With changing labels, the word level confidence of the sentence changes, and it automatically points to the words that are contributing positively to the prediction of the new labels. For e.g. in the second example when we change the True Label to jeans, the confidence of the word jeans becomes positive and other words such as shirt and jacket become negative. This is the beauty of the self-attention models.</p><h4>Named Entity Recognition</h4><p>Same as text classification, we assume the context vector as input and write the layers for the NER task. The NER model predicts labels for each input word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*AAvCSw6r7m-VTDurU5lzRg.jpeg" /><figcaption>Named Entity Recognition with context vectors (Image by Author)</figcaption></figure><p>Since the data is fashion specific, the labels are granular. NER also helps is phrase discovery, which in turn leads to trends discovery. There are lots of methods for NER, but the scope of this article is to understand the semi-supervised approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*f4yL7BvZ-pX3SU-cYhi6uA.jpeg" /><figcaption>NER for Fashion (Image by Author)</figcaption></figure><p>Now that we have gone through all the components, I suggest, you look again at the Transformers end-to-end training GIF.</p><p>The code for training is available at <a href="https://huggingface.co/docs/transformers/notebooks">Hugging face</a>.</p><ul><li>Fine Tune Langauge Model: <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb">Colab Notebook</a></li><li>Train a Text Classification Model: <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb">Colab Notebook</a></li><li>Train a NER Model: <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb">Colab Notebook</a></li></ul><p>In this article, I have tried to give an idea of the semi-supervised training that we can do with transformers to train highly accurate models. Let me know your thoughts on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38722f1b5ce3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/semi-supervised-approach-for-transformers-38722f1b5ce3">Semi-Supervised Approach for Transformers</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB: Join between large collections]]></title>
            <link>https://medium.com/analytics-vidhya/mongodb-join-between-large-collections-a1a59a6d6dd1?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1a59a6d6dd1</guid>
            <category><![CDATA[mongodb-joins]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[application-layer-joins]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[join]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Sun, 01 May 2022 06:18:04 GMT</pubDate>
            <atom:updated>2024-04-23T17:35:53.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8R9HkNMvvGgYz_cFYJx3Q.png" /><figcaption>MongoDB</figcaption></figure><p>In this article, we will discuss how to deal with joining the data across open source versions of MongoDB databases/collections when data is in the order of millions. When we are designing a data model for MongoDB, we might come to a decision whether to normalize this further or store it in its original format. If you decide not to normalize it then you struggle with indexes since the number of indexes can not exceed 64 for a given collection. If you decide to normalize it, that means breaking it into 2 collections with a foreign key or a common key.</p><p>“MongoDB is a source-available cross-platform <strong>document-oriented</strong> database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.” By design, Mongo is a documented-oriented and non-relational database, so it does not perform joins very well at the database level. Let’s go through an example.</p><p>Say, we have 2 collections.</p><ul><li>collection_a has 1 million data points</li><li>collection_b has 3 million data points.</li><li>While inferring the data, if you do a mongo level join or aggregation as mentioned in the Mongo documentation, you are likely to cause memory, CPU, and time-intensive fetch from the database.</li><li>One fetch is still fine, but multiple fetches can cause the mongo performance to deteriorate.</li><li>Just to give an example the above fetch for join of collection_a with collection_b can take up to 8 minutes if proper indexes are not in place.</li><li>The mongo behavior when it performs this order of joins, is difficult to predict.</li></ul><p>I am assuming that you already know the mongo aggregation and have tried it out. So, let’s go directly to the solution.</p><p>The solution lies in <strong>Application layer joins</strong>:</p><ul><li>The fetch for <strong>collection_a (query_a, projections:common_field)</strong>, given that all the indexes are in place should be less than 500ms. Say we got 100,000 entries from this fetch.</li><li>The fetch for <strong>collection_b (query_b, projections:common_field)</strong>, given that all the indexes are in place should be less than 1000ms. Say we got 500,000 entries from this fetch.</li><li>Whichever language you are using, use an optimized algorithm to find the intersection of both the fetch. i.e. intersection of a list of 100,000 entries to 500,000 entries with a common field. This should take less than 3 seconds.</li><li>So in a total of 5 seconds, we are able to find the intersection between collection_a and collection_b. Even with a larger collection size, this method will work faster.</li></ul><p><strong>The algorithm in python:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da77692c1e1992be015157bd6208bfdc/href">https://medium.com/media/da77692c1e1992be015157bd6208bfdc/href</a></iframe><p>The above algorithm is just an example of performing app layer intersection. You can modify it to write an algorithm for intersection with much better performance.</p><p><strong>Why use application layer joins?</strong></p><ul><li>The load is always on the application layer, and MongoDB performance would not have any effect.</li><li>Given that the application layer is containerized, it can scale much more because the load will be on the application layer.</li><li>The memory requirement, assuming the common field is a UUID (16-byte string), 1 MB for 62,500 UUIDs, 10 MB for 625,000 UUIDs. Which is reasonably available with pods.</li><li>Time taken will always be much lower than MongoDB aggregation even with proper indexes for joins.</li><li>These joins can even be extended to other mongo databases if needed.</li></ul><p>There are other ways as well, to deal with collection joins like sharding, using a third-party library, or using the elastic search with mongo. It depends on the use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1a59a6d6dd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/mongodb-join-between-large-collections-a1a59a6d6dd1">MongoDB: Join between large collections</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[Event-Driven Scalability in Data Processing Pipeline]]></title>
            <link>https://medium.com/data-science/event-driven-scalability-in-data-processing-pipeline-aa4417d7950a?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa4417d7950a</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 14:53:29 GMT</pubDate>
            <atom:updated>2022-05-13T04:58:52.340Z</atom:updated>
            <content:encoded><![CDATA[<h4>The architectural backbone to auto-scale in terms of infra and cost, based on the volume of data to be processed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhewRU3QgoEkKjbZOoJmDw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@edwardhowellphotography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Edward Howell</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Building a data processing pipeline is one of the most common problem statements, for which you would have written small scripts or built a full-fledged scalable system based on the amount, and frequency of data. In this article, we will talk about the idea of event-driven scalability, the backbone that will be cost-optimized, and requires a minimum amount of development and operations.</p><p><strong>Why build an event-driven and scalable data processing pipeline?</strong></p><p>While working with startups or building a team project or a personal project, that requires a pipeline for data processing, there is always a constraint of cost. There are 2 ways to tackle this:</p><ul><li>Write a script or build a small-scale system at the start of the project and re-work building a large-scale system when requirements increase.</li><li>Build an event-driven and scalable system, which means when not in use, zero cost, when in use the cost will be proportionate to the usage, and even when there is a high scale requirement, it will easily be handled.</li></ul><p><strong>Problem Statement Examples:</strong></p><ul><li>Data creation and pre-processing pipeline for training a Deep Learning model.</li><li>Extraction of metadata from the incoming raw data.</li><li>Crawling of data and extracting metadata. etc.</li></ul><p>We will use a simple example for building a metadata extraction system for e-commerce products. The metadata then is used to provide e-commerce solutions offered by <a href="https://www.streamoid.com/"><strong>Streamoid</strong></a>. The problem statement is that the client will provide their data. Metadata needs to be extracted, in order for internal services to work. Just for easy understanding, the internal systems need standard data to function, while the data received from clients is raw and may not adhere to the standards. So this calls for a data processing pipeline to convert the raw data to standard metadata that is understood well by the internal systems.</p><p>This metadata will be used by various systems across the organization to build several products such as (similar and outfitter recommendations), provide marketplace equivalent data (Amazon, Myntra, Tatacliq, etc.), train multiple classifiers, and understand trends and behavior.</p><p>Let’s see an example of the extraction of metadata for an e-commerce product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*N4UQkGUaCrgOp7SxFD2Sjg.gif" /><figcaption>Metadata Extraction of an e-commerce product (Image by Author)</figcaption></figure><p>Looks simple? Yes, the task is simple:</p><ul><li>Run Text Classification on Title and Description of the product.</li><li>Run Image Classification on Images and output of Text Classification.</li><li>There are many more steps, such as changing background, enrichment, metadata conversion to other marketplaces such as Amazon, etc. but for ease let’s assume there are just 2 steps Text and Image Classification.</li></ul><p>The challenges come when we combine this data processing pipeline with a business use case:</p><ul><li><strong>Priority-based processing</strong>. Enterprise clients are at the highest priority, then clients using the free tier, after that data for internal evaluation, demo, and training purposes.</li><li><strong>Cost optimization</strong>, some days the number of products to process would be up to 500,000 whereas on some days it will be less than 1,000. A scalable system’s cost should be directly proportional to the number of products processed at a given date.</li><li><strong>Limited resource</strong> usage. The deep learning classifiers require heavy computing and cannot scale infinitely. So optimized and full usage of these resources based on priority.</li></ul><p>Before we move ahead, let’s see the GIF of the architecture’s backbone, which we will be covering in this article. This is for the 2 processes (Text and Image Classification) in the data processing pipeline.</p><p>The below diagram shows 2 iterations, one is for scaling when processing 10 products are there, and the other when 100,000 products are there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijCPgKePy0ScgC9yuGuWng.gif" /><figcaption>Event-Driven Scaling of Data Processing Systems (Image by Author)</figcaption></figure><p>In this architecture we have used:</p><ul><li>MongoDB as the database (production database used by all the services)</li><li>RabbitMQ as the message broker</li><li>Google Kubernetes with KEDA for RabbitMQ consumer scaling</li><li>Google Cloud Run for heavy compute classifiers and auto-scaling</li></ul><p>The diagram can be divided into 4 major components. Let’s discuss each component in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mc8IfbwhGnnTPnLn_ALNIg.gif" /><figcaption>Image by Author</figcaption></figure><p><strong>MongoDB</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7Lz0bX1vjszk_no76tIcQ.jpeg" /><figcaption>MongoDB (Image by Author)</figcaption></figure><p>A no-SQL shared database is used, to handle easy scalability for a huge number of reading and write operations. As you can observe the database here is just like a plugin, if read and write need to happen to separate or multiple databases, that can be easily plugged in with Push and Pull services which also is deployed on Cloud Run.</p><p><strong>RabbitMQ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IC8yIIG7CJ2EaG22BvAJ2A.jpeg" /><figcaption>RabbitMQ (Image by Author)</figcaption></figure><p>An open-source message broker. There are other message brokers as well such as Kafka, or cloud-bound message brokers such as pub-sub, etc. But the reason to choose rabbitmq:</p><ul><li>Supports <strong>priority queue</strong> by design, which is one of the important requirements for this pipeline. For other message brokers, priority can be supported with bucketing, meaning maintaining 3 queues for the same process with different levels of priority and the priority requirements will be handled by consumers.</li><li>It is a <strong>push-based</strong> system, which means no race conditions with consumers. It assigns the messages based on priority to all the connected consumers in a round-robin manner and waits till it gets acknowledgment for successful processing of the messages before popping the message out of the queue.</li><li>Broadcasting or notification is not a requirement here for which Kafka or pub-sub would have been the better choice.</li></ul><p>Other message brokers could also be used. The choice of message broker depends on the use case.</p><p><strong>Google Kubernetes with KEDA</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psTVq1ekw0MhmRpuGd1UcQ.jpeg" /><figcaption>GKE (autopilot) with KEDA (Image by Author)</figcaption></figure><p>Google Kubernetes cluster is used here. Here, we have used an autopilot cluster, which means that there is no need to assign nodes to a cluster for autoscaling. The resources scaling is managed by the cluster itself that will create and remove new pods.</p><p>We have used KEDA (Kubernetes Event-Driven Scaling). The reason to do this is rabbitmq. If scaling needs to happen on memory/CPU usage or HTTP hits, then scaling is easy. But here scaling needs to happen based on the number of messages in the queue. Also, rabbitmq will not send an invocation, it will send messages to already connected consumers. To tackle this challenge we used KEDA, which will keep track of the number of messages in the queue and accordingly bring up new pods (rabbitmq consumers) in the Google Autopilot Clusters.</p><p><strong>Google Cloud Run</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U80aeKOQy0tCp8UuSqA4OA.jpeg" /><figcaption>Google Cloud Run (Image by Author)</figcaption></figure><p>Cloud run is used here to handle all the heavy computing such as classifiers. This scales down to 0 and scales based on HTTP invocations. In any pipeline, the major cost incurs from hiring the servers for heavy compute processing and keeping it up even while there is no usage for it. With Cloud Run, you can deploy your heavy compute services as a containerized solution, but only pay when you are using it. There are zero amount of operations involved once you deploy it. Here, we can use an Amazon Elastic Container Service (ECS) which is comparable to Cloud Run or if the GPU requirement is there, we can build our service on a GPU node. Basically, it is dependent on the service compute requirements. We use all three GCR, ECS, and GPU nodes based on requirements.</p><p>I would also like to mention that Cloud Run is probably the best cloud solution among all the cloud scaling solutions. The primary reason is it has all the functionality and is developer-friendly with the deployment of literally 2 lines of code.</p><p>Also, the limitations of this kind of design are on scaling the heavy computing resources.</p><p><strong>Why build this kind of architecture?</strong></p><ul><li>It is an <strong>event-driven system</strong>, therefore scaling and cost are incurred when there is an event, and the event is the availability of new data to be processed, update of data, or request for re-processing of data.</li><li>All components are like a <strong>plugin</strong>. We can change the database, or use multiple databases. We can change the message broker if the requirement asks. We can change Google Cloud Run or use multiple scaling services. All that the design consumes is an HTTP URL for heavy compute services.</li><li>Adding a <strong>new process</strong> is super easy in the pipeline. There is no need to spend time on any other part of the system while adding a new process. The work required would be adding consumers as consumers might be process specific.</li><li>The same pipeline/system can be used by other services for a completely different set of tasks. That means if we set up this pipeline once, this can be used across the board for different data processing requirements.</li><li>Once deployed, there are literally <strong>zero operations</strong> involved and <strong>minimum development</strong> required.</li></ul><p>This architecture represents the backbone and the idea of having event-driven scaling. The actual systems are much more complex than this.</p><p>To understand the tech mentioned above:</p><ul><li><a href="https://www.mongodb.com/"><strong>MongoDB</strong></a></li><li><a href="https://www.rabbitmq.com/"><strong>RabbitMQ</strong></a>: <a href="https://cloudplatform.googleblog.com/2014/06/rabbitmq-on-google-compute-engine.html">Cluster Deployment</a> on Google Cloud Platform</li><li><a href="https://www.simplilearn.com/kafka-vs-rabbitmq-article"><strong>RabbitMQ</strong> vs <strong>Kafka</strong></a></li><li>Google <a href="https://cloud.google.com/run"><strong>Cloud Run</strong></a></li><li>Amazon <a href="https://aws.amazon.com/ecs/"><strong>Elastic Container Service</strong></a> with Fargate</li><li><a href="https://lonare.medium.com/comparison-google-cloud-run-gcr-vs-azure-container-instances-aci-vs-aws-ecs-with-fargate-d419bc56cf90"><strong>Cloud Run</strong> v/s <strong>Elastic Container Service</strong></a></li><li>Google <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview"><strong>Autopilot Cluster</strong></a></li><li><a href="https://keda.sh/"><strong>KEDA</strong></a>: Kubernetes event-driven autoscaling</li><li><a href="https://medium.com/geekculture/understanding-kubernetes-hpa-with-keda-and-rabbitmq-4bf87216606b#:~:text=KEDA%20RabbitMQ%20Auto%2DScaler&amp;text=To%20achieve%20this%2C%20KEDA%20has,%E2%80%9CHPAQueue%E2%80%9D%20for%20any%20messages."><strong>Autoscaling</strong></a> with <strong>KEDA</strong> for <strong>RabbitMQ</strong> on <strong>Google Autopilot Cluster</strong></li></ul><p>Choosing a tech is solution specific. The same architecture with a little change in tech can serve a different kind of requirement. So it is always better to analyze all the tech and then select one.</p><p>Example of Decision Points:</p><ul><li>Which Cloud Provider to use or should we deploy on a local setup?</li><li>Which database to use?</li><li>Which queue/message broker to use? etc.</li></ul><p>For decision points on tech, I always refer to <a href="https://landscape.cncf.io/"><strong>CNCF</strong> Landscape</a> to see all the available options and analyze them based on my requirements.</p><p><a href="https://landscape.cncf.io/">CNCF Landscape</a></p><p>Let me know your thoughts on this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa4417d7950a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/event-driven-scalability-in-data-processing-pipeline-aa4417d7950a">Event-Driven Scalability in Data Processing Pipeline</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Augmentation for Text [with code]]]></title>
            <link>https://medium.com/analytics-vidhya/data-augmentation-for-text-with-code-6da46aad443d?source=rss-5556e9ffcf23------2</link>
            <guid isPermaLink="false">https://medium.com/p/6da46aad443d</guid>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[pos-tagging]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[text-generation]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[Divyanshu Raj]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 00:17:14 GMT</pubDate>
            <atom:updated>2024-04-23T17:35:03.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lM_z3cZjAN-Vm3qAijfIQ.jpeg" /><figcaption>image from <a href="https://unsplash.com/@randyfath">unsplash</a></figcaption></figure><p>This article will show how to code in PyTorch, data augmentation techniques for deep learning problems such as text classification, text generation, etc.</p><p>For data augmentation with Image related problems, you can find the implementations <a href="https://medium.com/analytics-vidhya/learn-to-code-in-tensorflow2-fe735ad46826?source=friends_link&amp;sk=e112de37ddacbf54982daf7eb803f1fe"><strong>here</strong></a>.</p><h3>Data Augmentation Techniques</h3><h4>1. Back Translation</h4><h4>2. Random Insertion</h4><h4>3. Random Deletion</h4><h4>4. Random Swap</h4><p><strong>Note</strong>: The data augmentation for text is a costly operation, if we try to use it in the training loop, it will increase the training time significantly. Unlike the image, for text augmentation, first, we need to replace the words and then use the related word embedding for that word. So, we will create an augmentation beforehand and use it in training.</p><p>I have done the data augmentation for the English language but these techniques are language agnostic.</p><h3>Back Translation</h3><p>The idea is to have different sentences mean the same thing use for training.</p><p><strong>Step 1</strong>: Select the English sentence.</p><pre>The Best Way To Get Started Is To Quit Talking And Begin Doing.</pre><p><strong>Step 2</strong>: Select a random language (Korean) and convert the sentence to that language using language translation.</p><pre>시작하는 가장 좋은 방법은 말하기를 그만두고 시작하는 것입니다.</pre><p><strong>Step 3:</strong> Now translate it back to English.</p><pre>The best way to start is to stop talking and start.</pre><p>Now, you can see that your sentences will mean the same thing but have a different structure.</p><p>To achieve this we need not train a language translation model, but we can leverage <strong>Google translate</strong>.</p><p>Let’s install the library required:</p><pre>sudo pip install google_trans_new</pre><p>Let’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46622084767108e20b95aee652059c4a/href">https://medium.com/media/46622084767108e20b95aee652059c4a/href</a></iframe><p>Please remember that while using Google translate API, there will be a limit to the number of sentences you can convert. So there are 2 ways to handle it:<br>1. Take a paid subscription for the API<br>2. Do data augmentation for your dataset multiple times. Say if 800 calls are the limit, then do data augmentation for 800 sentences and save it. After some time again do the augmentation for the next 800 sentences and so on.</p><h3>Random Insertion</h3><p>The idea here is to find the non stop-words in the sentence and randomly replace few words with their synonyms.</p><p><strong>Step 1</strong>: Select the English sentence.</p><pre>The Best Way To Get Started Is To Quit Talking And Begin Doing.</pre><p><strong>Step 2</strong>: Filter out the stop words.</p><pre>[&quot;Best&quot;, &quot;Way&quot;, &quot;Started&quot;, &quot;Quit&quot;, &quot;Talking&quot;, &quot;Begin&quot;, &quot;Doing&quot;]</pre><p><strong>Step 3</strong>: Choose 3 random words and find their closest synonyms.</p><pre>words = [&quot;Way&quot;, &quot;Quit&quot;, &quot;Talking&quot;]<br>synonyms = [&quot;Method&quot;, &quot;Leave&quot;, &quot;Speaking&quot;]</pre><p><strong>Step 4</strong>: Replace those words in the original sentence.</p><pre>The Best <strong>Method</strong> To Get Started Is To <strong>Leave</strong> <strong>Speaking </strong>And Begin Doing.</pre><p>To achieve this we can use the existing pre-trained word embeddings. However, for better results, you should use custom-trained word embeddings or a language model.</p><p>Download and extract the Google word2vec with 300 dimensions.</p><pre>wget -c &quot;https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz&quot;<br>gzip -d GoogleNews-vectors-negative300.bin.gz</pre><p>Let’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0507be593e8e49e2f5a9a662257c176b/href">https://medium.com/media/0507be593e8e49e2f5a9a662257c176b/href</a></iframe><p>This can be done in one shot but still takes time to generate for all the datasets.</p><h3>Random Deletion</h3><p>The idea here is to randomly delete few words from the sentence.</p><p><strong>Step 1</strong>: Select a sentence</p><pre>The Best Way To Get Started Is To Quit Talking And Begin Doing.</pre><p><strong>Step 2</strong>: Assign random probability to all the words</p><pre>0.3 The <br><strong>0.2 Best <br></strong>0.3 Way <br>0.8 To <br>0.8 Get <br>0.3 Started <br>0.7 Is <br><strong>0.2 To <br></strong>0.3 Quit <br>0.9 Talking <br>0.4 And <br>0.4 Begin <br>0.9 Doing.</pre><p><strong>Step 3</strong>: Remove all the words where the score is less than 0.3</p><pre>The Way To Get Started Is Quit Talking And Begin Doing.</pre><p>Let’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f64b0c6d041f6aa6bba9d9c10c9ccf7c/href">https://medium.com/media/f64b0c6d041f6aa6bba9d9c10c9ccf7c/href</a></iframe><h3>Random Swap</h3><p>The idea here is to randomly pick 2 words at a time and swap their position in the sentence. This can be done n number of times.</p><p><strong>Step 1</strong>: Select the sentence</p><pre>The Best Way To Get Started Is To Quit Talking And Begin Doing.</pre><p><strong>Step 2</strong>: Select the words and swap them</p><pre>The Started Way To Get Quit Is To Best Talking And Begin Doing.</pre><p>Let’s code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f569382c4550e1b2558306c0ea310d15/href">https://medium.com/media/f569382c4550e1b2558306c0ea310d15/href</a></iframe><p>Once, we have all the augmented data ready with us we can begin our training. All the above methods defined above are general approaches. To apply it to your dataset first you need to understand your dataset and then apply customized augmentation techniques.</p><p>These techniques can also be mixed and matched among themselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6da46aad443d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-augmentation-for-text-with-code-6da46aad443d">Data Augmentation for Text [with code]</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>