<?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 Virajdatt Kohir on Medium]]></title>
        <description><![CDATA[Stories by Virajdatt Kohir on Medium]]></description>
        <link>https://medium.com/@kvirajdatt?source=rss-4fa440f949cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iPNiRbC3eRlvv6BKkQco4A.jpeg</url>
            <title>Stories by Virajdatt Kohir on Medium</title>
            <link>https://medium.com/@kvirajdatt?source=rss-4fa440f949cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:58:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kvirajdatt/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[A Data Scientist’s Guide to GPU Part 1]]></title>
            <link>https://kvirajdatt.medium.com/a-data-scientists-guide-to-gpu-part-1-0a4b9dca0d9e?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4b9dca0d9e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 23:53:00 GMT</pubDate>
            <atom:updated>2024-10-15T23:53:00.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QRz_HyiDh-G7tTHh" /><figcaption>Photo by <a href="https://unsplash.com/@nanadua11?utm_source=medium&amp;utm_medium=referral">Nana Dua</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>As a child, I always dreamed of owning a powerful graphics card to enhance my gaming experience. Little did I know that this same hardware would become indispensable for my career as a data scientist, particularly in the realm of deep learning (DL) and large language models (LLMs).</p><p>This article aims to provide a concise overview of GPUs, their role in accelerating DL and LLM development, and key considerations for data scientists selecting the right GPU for their needs.</p><p>In recent weeks, I’ve made significant strides in optimizing my GPU training practices. Previously, I relied heavily on just the to_device(&#39;cuda&#39;) function in PyTorch (it works well in most cases), but I&#39;ve since discovered more efficient ways to utilize GPU resources. These insights inspired me to write this article. I’m committed to deepening my understanding of GPU computing and fine-tuning/pre-training LLMs. Join me on this journey by following my future content.</p><h3>Table of Contents:</h3><ol><li>Definition</li><li>Nvidia’s CUDA</li><li>Nvidia’s cuDNN</li><li>How CUDA and cuDNN Work Together</li><li>How GPU and Transformer Architecture</li><li>Key Considerations for GPU Selection</li><li>Brief recommendation for GPUs</li><li>Best Practices for Training Deep Learning Models with GPUs</li></ol><h3><strong>1. Definition:</strong></h3><p>A Graphics Processing Unit (GPU) is a specialized piece of hardware originally designed for rendering graphics, primarily in video games. However, its parallel processing capabilities have made it invaluable for data scientists, particularly in the field of deep learning.</p><ul><li><strong>Parallelism:</strong> GPUs possess thousands of smaller cores, each capable of performing simple calculations simultaneously. This is ideal for the matrix operations and neural network computations common in machine learning.</li><li><strong>Synchronization:</strong> GPUs employ efficient synchronization mechanisms to ensure data consistency and prevent race conditions in parallel computations.</li></ul><h3><strong>2. </strong>Nvidia’s <strong>Compute Unified Device Architecture</strong> (CUDA)</h3><p>CUDA is a parallel computing platform and API model created by NVIDIA. It allows developers to write C++ code that can be executed on NVIDIA GPUs, harnessing their parallel processing power.</p><p><strong>Key Features:</strong></p><ul><li><strong>Parallel Processing:</strong> CUDA enables the simultaneous execution of thousands of threads on a GPU, significantly accelerating computationally intensive tasks.</li><li><strong>Kernel Functions:</strong> These functions are the building blocks of CUDA programs. They are executed on the GPU and can operate on large arrays of data in parallel.</li><li><strong>Memory Management:</strong> CUDA provides mechanisms for managing GPU memory, including allocating, copying, and freeing memory.</li><li><strong>Interoperability:</strong> CUDA can be used with popular programming languages like C++, Python, and Java.</li></ul><h3>3. Nvidia’s cuDNN</h3><ul><li><strong>CUDA Deep Neural Network Library:</strong> cuDNN is a GPU-accelerated library optimized for deep neural network training and inference. It provides highly optimized implementations of common deep learning primitives, such as convolutional layers, recurrent layers, and pooling layers.</li></ul><p><strong>Key Benefits:</strong></p><ul><li><strong>Performance:</strong> cuDNN offers significant performance improvements over CPU-based implementations, especially for large-scale deep learning models.</li><li><strong>Ease of Use:</strong> It provides a high-level API that abstracts away the complexities of GPU programming, making it easier for developers to build and train deep learning models.</li><li><strong>Compatibility:</strong> cuDNN is compatible with popular deep learning frameworks like TensorFlow, PyTorch, and Caffe.</li></ul><h3>4. How CUDA and cuDNN Work Together</h3><ol><li><strong>CUDA provides the foundation:</strong> It enables the execution of code on the GPU and manages memory allocation and transfer.</li><li><strong>cuDNN leverages CUDA:</strong> It uses CUDA to efficiently perform deep learning operations on the GPU.</li><li><strong>Deep Learning Frameworks:</strong> Popular frameworks like TensorFlow and PyTorch utilize cuDNN to accelerate their operations, making it possible to train large-scale deep learning models in a reasonable amount of time.</li></ol><h3><strong>5. How GPU and Transformer Architecture accelerated LLM development :</strong></h3><p><strong>LSTM vs Transformers</strong>: Transformers and Long Short-Term Memory<strong> (LSTM)</strong> networks are both popular architectures for sequential data processing, particularly in natural language processing. While both have their strengths, Transformers offer a significant advantage in terms of parallelism, which can lead to faster training and inference times. The core computations in attention layers involve matrix multiplications, which are highly parallelizable operations. Modern GPUs and TPUs are optimized for these matrix operations. It’s this Transformer architecture that is at the core of most recent LLMs like LaMA/GPT.</p><p>The transformer’s N-heads work in parallel on a GPU and then the results are merged/synchorized. The diagram below shows working of the n-heads. This is opposite to how LSTM process data in sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*VLArHWypgmIrk9Zl.png" /><figcaption>Image from <a href="https://towardsdatascience.com/transformers-explained-visually-part-3-multi-head-attention-deep-dive-1c1ff1024853">https://towardsdatascience.com/transformers-explained-visually-part-3-multi-head-attention-deep-dive-1c1ff1024853</a></figcaption></figure><p>GPU Implementation of Transformers</p><ul><li><strong>Head-Level Parallelism:</strong> Each attention head can be processed independently, allowing for parallel execution.</li><li><strong>Matrix Multiplication Optimization:</strong> GPUs are optimized for matrix operations, making them well-suited for the computations involved in attention layers.</li></ul><h3><strong>6. Key Considerations for GPU Selection</strong></h3><p>When choosing a GPU for deep learning and LLMs, consider the following factors:</p><ul><li><strong>Budget:</strong> GPUs can vary significantly in price. Determine your budget before starting your search.</li><li><strong>Model Complexity:</strong> The size and complexity of your models will influence the required GPU performance.</li><li><strong>Data Volume:</strong> The amount of data you’ll be training on will also impact GPU requirements.</li><li><strong>Framework Compatibility:</strong> Ensure your preferred deep learning framework (e.g., TensorFlow, PyTorch) is compatible with the GPU.</li></ul><p>Tip for beginners:</p><ul><li>Google Colab offers a convenient and free introduction to GPU computing, but its free tier often has short runtimes (typically 2–3 hours). Additionally, sessions can disconnect unexpectedly, even during training loops or when loading larger models like 8-bit Quantized Laama2 for inference.</li></ul><h3>7. Recommendation for GPUs:</h3><p>While specific recommendations can change over time, here are some popular choices for deep learning as of now :</p><ul><li><strong>NVIDIA GeForce RTX Series:</strong> Known for their excellent performance in both gaming and deep learning, especially those with higher-end models like the RTX 3080 / 4090.</li><li><strong>NVIDIA Tesla Series:</strong> Specifically designed for data centers and scientific computing, offering exceptional performance and reliability for demanding deep learning workloads.</li><li><strong>Cloud-Based Solutions:</strong> If you have limited hardware resources, consider cloud-based platforms like Google Colab (Free or Learn more about paid version <a href="https://mccormickml.com/2024/04/23/colab-gpus-features-and-pricing/">here</a>), Amazon SageMaker, or Microsoft Azure Machine Learning, which provide GPU-accelerated instances.</li><li><strong>Used GPUs:</strong> You might find good deals on used GPUs, but be mindful of their condition and potential performance degradation.</li><li><strong>Future-Proofing:</strong> If you anticipate scaling your deep learning projects, invest in a GPU with sufficient headroom to handle future demands.</li></ul><h3>8. Best Practices for Training Deep Learning Models with GPUs:</h3><p>1. <strong>Utilize Mixed Precision Training: FP16/BF16:</strong> Employ mixed-precision training (FP16 or BF16) to reduce computational costs without sacrificing accuracy. This is especially beneficial for large models.</p><p>2. <strong>Optimize Data Loading and Preprocessing</strong>: <strong>GPU-Based Preprocessing:</strong> Perform data preprocessing operations directly on the GPU to minimize data transfer overhead. Use asynchronous data loading and preprocessing to overlap these tasks with model training. PyTorch makes it easy to leverage GPU acceleration. You can quickly transfer data loaders and models to the GPU using to_device(&#39;cuda&#39;) if you have an NVIDIA GPU.</p><p>3. <strong>Select Appropriate Batch Sizes</strong>: Experiment with different batch sizes to find the optimal balance between training speed and memory usage. Larger batch sizes can often improve performance, but excessive sizes may lead to memory constraints.</p><p>4. <strong>Monitor GPU Utilization and Memory Usage</strong>: nvidia-smi provides valuable information about GPU performance by tracking utilization and memory usage. While not always a definitive measure, these metrics can often help identify performance issues.</p><p>5. <strong>Consider Distributed Training with Multiple GPUs:</strong> For extremely large models or datasets, consider distributed training across multiple GPUs or even multiple machines to accelerate training. Pytorch lighting makes it easier with Data Parallelism in PyTorch Lightning (DDP): <a href="https://lightning.ai/docs/pytorch/stable/accelerators/gpu_intermediate.html">https://lightning.ai/docs/pytorch/stable/accelerators/gpu_intermediate.html</a> .</p><p>6. <strong>Allocate Memory Efficiently:</strong> Allocate GPU memory as needed and release it when no longer required.</p><p>If there’s interest, I’ll provide more details on different GPU options and architectures you can choose from for local or cloud-based GPU computing.(as mentioned briefily in the Cloud-Based Solutions)</p><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ul><li><a href="https://cnvrg.io/deep-learning-gpu/">https://cnvrg.io/deep-learning-gpu/</a></li><li><a href="https://www.youtube.com/watch?v=6stDhEA0wFQ">https://www.youtube.com/watch?v=6stDhEA0wFQ</a></li><li><a href="https://mccormickml.com/2024/04/23/colab-gpus-features-and-pricing/">https://mccormickml.com/2024/04/23/colab-gpus-features-and-pricing/</a></li><li><a href="https://medium.com/@romxzg/maximizing-computing-power-a-guide-to-google-colab-hardware-options-a68469415291">https://medium.com/@romxzg/maximizing-computing-power-a-guide-to-google-colab-hardware-options-a68469415291</a></li><li><a href="https://medium.com/codenlp/cost-of-running-ml-experiments-on-gpu-aws-cloud-vs-local-gpu-56efac599525">https://medium.com/codenlp/cost-of-running-ml-experiments-on-gpu-aws-cloud-vs-local-gpu-56efac599525</a></li><li><a href="https://www.youtube.com/watch?v=6stDhEA0wFQ">https://www.youtube.com/watch?v=6stDhEA0wFQ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4b9dca0d9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Equivalents in Pyspark]]></title>
            <link>https://kvirajdatt.medium.com/pandas-equivalents-in-pyspark-7ed78b453c87?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed78b453c87</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 00:31:45 GMT</pubDate>
            <atom:updated>2023-07-13T00:35:20.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ibc60kEY_oT7xpTb" /><figcaption>Pandas Equivalents in Pyspark</figcaption></figure><p>This year I have been using pyspark extensively at my job. It’s been nearly 6 months and I have grown to love pyspark for it’s efficiency for handling millions of rows of data. When I started to learn pyspark I was an extensive pandas user and had done a lot of data wrangling with pandas. One thing I really missed in my early days of learning pyspark and getting some quick work done was having a list/cheatsheet of pandas equivalents in pyspark. In this article I complied a few snippets that can help you with the transition and get some quick work done as you also start your pyspark journey.</p><h3>0. Preliminary steps:</h3><h4>Quick imports and setup for our examples</h4><pre>from pyspark.sql import SparkSession<br>import pandas as pd<br>import pyspark.sql.functions as sf<br>from pyspark.sql.types import (<br>    StringType,<br>)<br><br>data_fr_df = [[1, &#39;python&#39;], [2, &#39;C&#39;], [3, &#39;C++&#39;], [4, &#39;scala&#39;], [5, &#39;python&#39;]<br>             ]<br># Create pandas Dataframe<br>simple_df = pd.DataFrame(data_fr_df, columns=[&#39;user_id&#39;, &#39;programming_language&#39;])<br><br><br>#Create spark Dataframe with same data<br>simple_sdf = spark.createDataFrame(simple_df)<br>spark = SparkSession.builder.getOrCreate()</pre><h3>1. Number of rows/records:</h3><p>use <strong>count</strong> from pyspark dataframe.</p><pre># Number of rows<br>## pandas<br>len(simple_df)<br><br>## pyspark<br>simple_sdf.count()</pre><h3>2. List datatypes of columns</h3><p>use <strong>printSchema</strong> from pyspark dataframe.</p><pre># Listing datatypes of columns<br><br>## pandas<br>simple_df.dtypes<br><br>## pyspark<br>simple_sdf.printSchema()</pre><h3>3. Adding a new column</h3><p>Use <strong>withColumn</strong> from pyspark dataframe</p><pre># Adding a new column<br><br>## pandas<br><br>simple_df[&#39;new_col&#39;] = &#39;pandas_new_col&#39;<br>simple_df.head()<br><br>## pyspark<br>simple_sdf = simple_sdf.withColumn(&#39;newColumnPyspark&#39;,<br>                       sf.lit(&#39;pyspark_new_col&#39;))<br>simple_sdf.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZjbhb2nJtiksFk2HJm2jQ.png" /><figcaption>Img: Adding a new column</figcaption></figure><h3>4. value_counts</h3><p>Use grouby, followed by count from pyspark dataframe.</p><pre># value_counts<br><br>## pandas<br>simple_df[&#39;programming_language&#39;].value_counts(dropna=False)<br><br>## pyspark<br>simple_sdf.groupBy(&#39;programming_language&#39;).count().orderBy(&#39;count&#39;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbZ_a4Dk2Gv_Ad4wU5bFRg.png" /><figcaption>Img: value_counts</figcaption></figure><h3>5. Sorting</h3><p>Use orderby from pyspark dataframe.</p><pre># sorting<br>## pandas<br>simple_df.sort_values(&#39;user_id&#39;, ascending=False)<br><br>## pyspark<br>simple_sdf = simple_sdf.orderBy(&#39;user_id&#39;, ascending=False)<br>simple_sdf.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz_0B54PmCa-MzKWM995NA.png" /><figcaption>Img: Sorting</figcaption></figure><h3>6. Min and Max Values</h3><p>Use sf.max and sf.min which are part of the pyspark.sql.functions module.</p><pre>## pandas<br>print(f&#39;pandas max value {simple_df[&quot;user_id&quot;].max()}&#39;)<br>print(f&#39;pandas min value {simple_df[&quot;user_id&quot;].min()}&#39;)<br><br>## pyspark<br>print(f&#39;pyspark max value {simple_sdf.agg(sf.max(&quot;user_id&quot;)).show()}&#39;)<br>print(f&#39;pyspark min value {simple_sdf.agg(sf.min(&quot;user_id&quot;)).show()}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuJRBVj69ae1KUa8le6PUA.png" /><figcaption>img: Max and Min Values</figcaption></figure><h3>7. Data Filtering</h3><p>Use filter method from pyspark dataframe.</p><pre>## pandas<br>simple_df[simple_df[&#39;user_id&#39;]==3]<br><br>## pyspark<br>simple_sdf.filter(sf.col(&#39;user_id&#39;)==3).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJHUJkNpFXd2dShcSYqJSw.png" /><figcaption>Img: Filtering</figcaption></figure><h3>8. Calculating Nulls/Nans values</h3><p>Pyspark unlike pandas isnull() function treats Nulls and Nans differently so they need to be counted seperately. We will use <strong>isnull</strong> and <strong>isnan</strong> from pyspark.sql.functions.</p><pre>## pandas <br>simple_df.isnull().sum()<br><br><br>## pyspark<br><br># nans<br>simple_sdf.select([sf.count(sf.when(sf.isnan(c), c))\<br>          .alias(c) for c in simple_sdf.columns]).show()<br><br># nulls<br>simple_sdf.select([sf.count(sf.when(sf.isnull(c), c))\<br>          .alias(c) for c in simple_sdf.columns]).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2SBVXDMxw7C9_X53CSX8g.png" /><figcaption>Nulls/Nans values</figcaption></figure><h3>9. Type Casting</h3><pre>## pandas<br>simple_df[&#39;user_id&#39;] = simple_df[&#39;user_id&#39;].astype(&#39;str&#39;)<br><br>## pyspark<br>cast_column = &#39;user_id&#39;<br>simple_sdf = simple_sdf.withColumn(cast_column, simple_sdf[cast_column]\<br>                       .cast(StringType()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4Sv-X_TjY9Jxt5eHmTK_Q.png" /><figcaption>Type Casting</figcaption></figure><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed78b453c87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial on Hyper-parameter tuning of Vanilla Transformer Encoder of non-textual sequence data for…]]></title>
            <link>https://kvirajdatt.medium.com/tutorial-on-hyper-parameter-tuning-of-vanilla-transformer-encoder-of-non-textual-sequence-data-for-83136601e98?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/83136601e98</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Sun, 28 May 2023 23:02:55 GMT</pubDate>
            <atom:updated>2023-05-28T23:02:55.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutorial on Hyper-parameter tuning of Vanilla Transformer Encoder of non-textual sequence data for Classification tasks using Tensorflow and Keras tuner.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*boPZHH65ycJCrLx4.png" /></figure><h3>Table of Contents:</h3><ol><li>Introduction.</li><li>Code.</li><li>Hyer-parameter explanation.</li><li>Conclusion.</li><li>References.</li></ol><h3>1. Introduction:</h3><p>At the time of writing this article, OpenAi, and the GPT architectures are the rages of the town for sequence modeling, especially in the Natural Language Processing domain. This article doesn’t focus on any of the latest Transformer models rather it focuses on the <strong>original Transformer architecture</strong> (which I refer to as vanilla in this article&#39;s title). The first Transformer model was introduced in the seminal paper “Attention is all you need”[1]. This article does assume that the user is well aware of this Transformer architecture.</p><p>Here are a couple of articles that can be helpful if you are just getting started with Transformers:</p><ol><li><a href="https://towardsdatascience.com/attention-is-all-you-need-discovering-the-transformer-paper-73e5ff5e0634">Attention is all you need: Discovering the Transformer paper</a></li><li><a href="https://sh-tsang.medium.com/review-attention-is-all-you-need-transformer-96c787ecdec1">Review — Attention Is All You Need (Transformer)</a></li><li><a href="https://keras.io/examples/nlp/text_classification_with_transformer/">Coding Attention Is All you Need using Tensorflow and Keras</a></li><li><a href="https://machinelearningmastery.com/implementing-the-transformer-encoder-from-scratch-in-tensorflow-and-keras/">Implementing the Transformer Encoder from Scratch in TensorFlow and Keras</a></li></ol><p>In my recent experience with sequence modeling with healthcare datasets where tokens are medical diagnoses in contrast to natural language tokens that BERT, GPT-2, GPT-3, etc are trained on. <strong>Hence I couldn’t use the pre-trained weights of the models mentioned for my work</strong>. In addition to that the healthcare dataset I had wasn’t huge to train billions of parameters of these models. So, I began exploring LSTM, and Bi-LSTM models. Once these models had reached their limits with their generalization next, <strong>I trained the dataset with the Vanilla Transformer model, where the performance was in fact not as good as the Bi-LSTM model</strong>. As a next step, I wanted to tune the parameters of the Vanilla Transformer model to better its performance. It was then that I realized that there weren’t a lot of articles detailing the steps for this task. After spending some time and experimenting I was able to tune the Transformer to beat the performance of LSTM-based models. Now I am putting together <strong>this article for hyper-parameter tuning of the Vanilla Transformer model </strong>for classification for people who want to do it on their own datasets<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*ihGNoUTZM1dLYXZD.png" /><figcaption>Transformer Architecture from “Attention is all you need”</figcaption></figure><h3>2. Code:</h3><p>This article will focus on tuning the encoder part of the transformer as it is the only component used during a classification task. This article will use the sample dataset of IMDB to tune parameters. This dataset is publicly available and is used here for demonstration purposes. You can plug in your personal dataset (text-based or <strong>non-text-based sequence data</strong>)and use the code and tips mentioned below.</p><p>Following is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ed267c9843f587b4a19583b2e52fe7/href">https://medium.com/media/02ed267c9843f587b4a19583b2e52fe7/href</a></iframe><p>Sample output from the code above when run on <a href="https://colab.research.google.com/drive/1fukm-phOr7lsj6Nt4TWTVQfJL81AMkIZ#scrollTo=oyTLuSkeakR0">Google Colab</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMT3Xb1rFz6Xub5KsVVdDg.png" /></figure><h3>3. Hyer-parameter explanation:</h3><p>Following are the hyper-parameters that I tweak in the build_model(hp) function in the code displayed above. I found tweaking the below gave some of the best results for me in my case (vanilla transformer on the sequential healthcare dataset where the diagnosis and healthcare providers were the input sequence tokens).</p><p>1. <strong>emb_vector_size</strong> Embedding Vector Dimensions, Number of dimensions for the embedding positional vector that is input into the encoder.</p><p>2. <strong>num_heads</strong>: Number of heads in Transformer Encoder. Increasing the number of heads can lead to better-represented vectors for classification tasks.</p><p>3. <strong>ff_dim</strong>: Hidden layer size in a feed-forward network inside the transformer. These are the layers in the Transformer encoder that have learnable parameters.</p><p>4. <strong>num_transformer_blocks</strong>: Total number of encoder layers. Increasing the number of these blocks may also lead to better-represented vectors for classification tasks. <strong>But this will increase the train time.</strong></p><p>5. <strong>num_mlp_layers</strong>: Number of mlp layers after the encoder layer</p><p>6. <strong>mlp_units</strong>: Number of units in the Dense networks after the encoder layer.</p><p><strong>Some additional hyper-parameters that can be tweaked are:</strong></p><ol><li>The <strong>vocabulary size</strong> (VOCAB_SIZE in the code above).</li><li>The <strong>max sequence length</strong> (MAX_LEN in the code above).</li><li>Increasing <strong>Dropout Probability</strong> if you see the transformer overfitting the train set in small epochs (mlp_dropout and dropout in the code above).</li></ol><p>These additional hyper-parameters mentioned above can be increased or decreased based on your particular dataset/use case. For me <strong>reducing the VOCAB_SIZE and MAX_LEN</strong> helped while <strong>increasing Dropout Probability combated the overfitting</strong>.</p><h3>4. Conclusion:</h3><p>This article articulated steps for tuning hyperparameters of a Vanilla Transformer Encoder for classification tasks. As mentioned earlier BERT, GPT-2, GPT-3, etc cannot be readily used if the sequence data isn’t consisting of Natural Language Tokens, and also training these models from scratch if the dataset is small won’t be fruitful given the billions of parameters they have. Instead starting with a simple RNN and bi-LSTM model can help establish the baseline and then one can experiment with Vanilla Transformer to beat these baselines and see if that achieves the performance improvement required.</p><h3>The code for this tutorial can be found at:</h3><ol><li>On <a href="https://colab.research.google.com/drive/1fukm-phOr7lsj6Nt4TWTVQfJL81AMkIZ#scrollTo=oyTLuSkeakR0">google-collab</a></li></ol><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://arxiv.org/abs/1706.03762">Attention is all you need paper</a></li><li><a href="https://towardsdatascience.com/attention-is-all-you-need-discovering-the-transformer-paper-73e5ff5e0634">Attention is all you need: Discovering the Transformer paper</a></li><li><a href="https://sh-tsang.medium.com/review-attention-is-all-you-need-transformer-96c787ecdec1">Review — Attention Is All You Need (Transformer)</a></li><li><a href="https://keras.io/examples/nlp/text_classification_with_transformer/">Coding Attention Is All you Need using Tensorflow and Keras</a></li><li><a href="https://machinelearningmastery.com/implementing-the-transformer-encoder-from-scratch-in-tensorflow-and-keras/">Implementing the Transformer Encoder from Scratch in TensorFlow and Keras</a></li><li><a href="https://keras.io/examples/nlp/text_classification_with_transformer/">Time series classification with a Transformer model using Tensorflow Keras</a></li><li><a href="https://www.tensorflow.org/tutorials/keras/keras_tuner">Introduction to the Keras Tuner</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83136601e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science and Machine Learning Interview tips and questions for new grads.]]></title>
            <link>https://kvirajdatt.medium.com/data-science-and-machine-learning-interview-tips-and-questions-for-new-grads-6d9ff089bcba?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9ff089bcba</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 02:08:19 GMT</pubDate>
            <atom:updated>2022-12-31T02:08:19.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yit1EfOHvWDCRZOe" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently graduated with a Masters&#39;s Degree in Data Science. For the past year, I have been preparing for interviews initially for internships and then for full time, and during this preparation, I have collected notes on things that helped me over time to better myself in interviews and land a job. In this article, I want to summarize the things I have learned and provide some tips for new grads out there wanting to break into Data Science and Machine Learning field. Along with tips, I also will be sharing interview questions that I faced during my search for internships and full-time. I hope the reader finds this guide helpful during their preparation.</p><blockquote>Note:<br>I won’t be talking on how to prepare resume in this guide. I feel there are lot of materials out there to guide an individual.</blockquote><p>I am gonna list typical steps that follow once your resume is picked up.</p><ol><li>Recruiter screening call or Online Assessment.</li><li>Behavioral round.</li><li>Technical rounds (2–5 rounds)</li><li>Final Negotiation round.</li></ol><h3>SECTION 1: THE TIPS</h3><h4>Tip 1: Work on Data Science projects in varying domains/industries:</h4><p>The preparation to land a job starts with your course work and projects you work on during your course. Before the start, of course, my master’s I was given this tip to work on data science projects in different domains like finance, healthcare, eCommerce, etc. This tip really helped in tailoring my resume for various industries. This is a great preparation that you can do to land a job during your coursework. If not done during course work this tip can be followed anytime during the job application process.</p><p>I had prepared a bunch of resumes with projects specific to the job and the industry. For example:</p><ol><li><strong>VDK_Resume_DS_health_care</strong>: For data science positions focused on health care.</li><li><strong>VDK_Resume_DS_NLP</strong>: For data science positions focused on Natural Language Processing.</li></ol><p>Etc…..</p><h4>Tip 2: Prepare for Python and SQL assessments early in your job search:</h4><p>There are a lot of companies out there that send out the online assessment(s) when you apply for their Data Science position. These online assessments can contain coding in python and SQL queries or a take-home data science project. In the initial days of my job search, I didn’t focus much on coding and SQL steps and was exclusively preparing for the Data Science interview question and I realized that it was a bad strategy. Coding and SQL questions also make up the initial round in technical rounds.</p><p>So my advice is to focus on coding (python) and SQL during the start of your preparation and not to delay these.</p><p>For <strong>python</strong> I focused on strings, array, and hashmap problems from Leetcode (easy and medium around 100 questions )and eventually worked on data structures and algorithms. I was able to develop good skills by focusing on strings, arrays, and hashmap-related problems and was able to get through many Online Assessments and Coding sessions in Technical Interviews. There were a couple of interviews where I was asked to write simple unit tests so I would recommend working on unit test skills as well during preparation.</p><p>For <strong>SQL</strong>, I practiced easy and medium problems from <a href="https://datalemur.com/sql-interview-questions">DataLemur</a> and <a href="https://www.hackerrank.com/domains/sql">hackerrank</a>. I solved all these problems twice over course of a month and was comfortable with SQL questions. If you are someone who is starting out in SQL, I would recommend solving the problems on this platform twice.</p><p>To develop coding and SQL skills along with the required thought process for coding rounds and online assessments I would recommend being consistent in the preparation. Allow yourself 1–2 hours each day for 3–4 times a week.</p><p><strong>Take home Data Science Project</strong>:</p><p>I have seen some companies that send out take-home data science projects as part of their online assessment. I found the following article to be a great help in my preparation to tackle this kind of online assessments:</p><blockquote>Tackling the Take-Home Challenge: <a href="https://towardsdatascience.com/tackling-the-take-home-challenge-7c2148fb999e">link</a></blockquote><p>This kind of assessment may seem challenging at first but as you keep working on data science projects you will get comfortable and will eventually prefer such assessments.</p><h4>Tip 3: Sell a very good project you have worked on to the recruiter who calls for a screening round.</h4><p>If you are not sent an online assessment then the most probable next step after your resume is picked up would be for a recruiter will reach out to you for a screening call. This can be an online video call or usually it&#39;s a phone call. The recruiter who calls you is your friend who will push your resume to the technical manager who is hiring for the role. So this is an important call for you in the process.</p><p>The preparation for this round:</p><ol><li><strong>Research about the company (their projects, services, products, and values)</strong>:<br>This is a step that you may miss since you are applying for a lot of jobs and will be lined up for calls from n companies. But in my opinion, researching a company is vital to selling yourself better when you get that recruiter call. <br>Go to the company website and read up on their <strong>projects, services, products, and their company values</strong>. During this step also familiarize yourself with the job description.</li><li><strong>Narrative to introduce yourself</strong>: <br>Once the recruiter calls you, they will provide you with a little bit of background of the company, the team, and the projects they have for the role you applied to. Once this has been communicated to you the first question you will be asked by the recruiter is to introduce yourself. When introducing yourself be sure to <strong>include skills that you have and are part of the job description</strong>, align your <strong>soft skills with the company values </strong>and relay them to the recruiter. <strong>Be sure to communicate how your education, background, skills, and projects make you a good fit for the position.</strong><br>For example, if you are applying for a company that works in the finance domain: “<em>I am enthusiastic about possibilities of Data Science in the field of fintech. I have worked on xxx projects to predict xxx in the finance industry. XXX courses really helped deepen my understanding of math concepts that are important for the role of…</em>”</li><li><strong>Sell the projects you worked on (focus on outcomes rather than technicality)</strong>: <br>It is always best to talk about a project that you have worked that aligns with the company&#39;s domain (talk about a healthcare project if you are being reached out by a healthcare company). The focus when you are talking about the project should be to <strong>communicate and sell the impact/outcome/end results</strong> as opposed to technical prowess. Yes, you can mention about the coding language and packages you used to complete your project but remember that the recruiter isn’t looking for technical expertise at this point in the recruitment process. <br>For example: “<em>The XXX project lead to an accuracy of XX %, these results can be used to make better decisions which are backed by historic data.</em>”<br>Practice your project pitch and try to keep it under 2–3 mins. This is a skill that can be improved with practice.</li><li><strong>Behavioral Questions</strong>: <br>The recruiter can also ask a couple of behavioral questions so be sure to prepare for those. Some typical questions that I have been asked during the initial screening rounds have been:<br>- Tell me about your strengths?<br>- Why this role and this company?<br>Here is an article that I used to prepare for preparing my answers for behavioral rounds: <a href="https://www.thebalancemoney.com/how-to-answer-behavioral-interview-questions-2059622">link</a></li><li>Finally, be enthusiastic about the company, and the role you are applying for and ask questions to the recruiter to show your vested interest. Some example questions I typically like to ask are:<br>- What is the most challenging project the team is working on?<br>- Career Development opportunities within the team and the company?</li></ol><p>Once you are past the online assessment and/or recruiter call, the next steps in the Data Science recruitment process are technical rounds (some of them may include behavioral aspects)</p><h4>Tip 4: Interviewers in the coding round are there to help so don’t hesitate to ask them questions.</h4><p>Coding rounds are it is programming or SQL can be daunting given the sheer amount of problems that you may be asked to solve. But don’t sweat on it too much, typically these rounds with an interviewer are to assess your thought process at arriving at a solution (out of the many possible ways of solving them). If you have any doubts or are confused about the problem my advice is to talk about it with the interviewer. The clarity he provides will be very helpful in developing your solution. In the first few coding rounds I was part of I hesitated to ask questions and get more clarity on the problem I was asked to solve and this approach didn’t work out. With time I realized that asking questions and getting clarity on the problem is part of the problem itself. The interviewer wants to assess how you navigate with a problem especially when it’s new to you, so asking questions and putting your thought process out will not only aid you in arriving at a solution but also show the interviewer your approach when you are faced with unknown circumstances.</p><h4>Tip 5: Sell your project to the technical recruiter the same way but this time cover the typical data science project life cycle.</h4><p>You have prepared to sell one of your projects earlier in the recruitment round. There you have completed the preparation for selling the results of your project. During the technical round when you are asked to talk about one of your projects take an additional couple of minutes to talk about the life cycle of your data science project. Include the steps starting from <strong>data acquisition to training validation strategy, and why certain metrics were chosen for the evaluation of the model(s).</strong></p><h4>Tip 6: Prepare for pandas, sklearn, numpy, tensors</h4><p>In some interviews coding questions, I was asked were related to pandas, sklearn, numpy, and tensors. With these questions, you are typically expected to write optimized and vectorized versions of code.</p><p>Here is an article that can help you get started with preparation in this direction: <a href="http://: https://towardsdatascience.com/how-to-speedup-data-processing-with-numpy-vectorization-12acac71cfca#:~:text=The%20concept%20of%20vectorized%20operations,to%20simple%20non%2Dvectorized%20operations.">link</a></p><h4>Sklearn Interview Questions:</h4><ul><li><a href="https://www.mlstack.cafe/blog/scikit-learn-interview-questions">https://www.mlstack.cafe/blog/scikit-learn-interview-questions</a></li></ul><h4>Pandas Interview Questions:</h4><ul><li><a href="https://www.mlstack.cafe/blog/pandas-python-interview-questions">https://www.mlstack.cafe/blog/pandas-python-interview-questions</a>1.</li></ul><h3>SECTION 2: Data Science and Machine Learning Interview Questions</h3><p>The Data Science interview questions range from statistics, probabilities, and machine learning algorithms to evaluation methods. In this article, I want to focus on Machine Learning Algorithms and some of the associated questions and concepts.</p><h3>Questions on Machine Learning Algorithms</h3><p>One interesting thing that I have observed over the interviews is that the recruiters usually ask you questions about Machine Learning Algorithms that you have mentioned in your resume. There are tons of Machine Learning Algorithms out there and you don’t have to feel daunted by learning them all for every interview you have. Be thorough with the algorithms you have used and mentioned in your resume without fail.</p><p>For every algorithm the questions will range in the following:</p><ol><li>Intuitive explanation of the working of the algorithm.</li><li>Pros and Cons of the Algorithm.</li><li>Hyper-parameters of the algorithm and how you tune it (list the most important hyperparameter based on the algorithm).</li><li>Assumptions of the algorithm (ex: Linear Regression expects correlation between the feature(s) and target variable)</li></ol><p>For most of my interviews I prepare for the following algorithms and here are links to some interesting questions on them:</p><h4><strong>1. Linear Regression:</strong></h4><ul><li><a href="https://blog.minitab.com/en/adventures-in-statistics-2/how-to-interpret-regression-analysis-results-p-values-and-coefficients">How to Interpret Regression Analysis Results: P-values and Coefficients</a></li><li><a href="https://www.notion.so/Linear-Regression-d64f50b087214a8fb75b6b90dce92c1f">Relationship between R-squared and p-value in a regression</a></li><li>Heteroscedasticity in LR: <a href="http://www.statsmakemecry.com/smmctheblog/confusing-stats-terms-explained-heteroscedasticity-heteroske.html">link</a></li><li><a href="https://towardsdatascience.com/intuitions-on-l1-and-l2-regularisation-235f2db4c261">Regularization</a> in Linear Regression</li></ul><p>Interview questions on Linear Regression:</p><ul><li><a href="https://www.mlstack.cafe/blog/linear-regression-interview-questions">https://www.mlstack.cafe/blog/linear-regression-interview-questions</a></li><li><a href="https://www.digitalvidya.com/blog/most-commonly-asked-interview-questions-on-linear-regression/">https://www.digitalvidya.com/blog/most-commonly-asked-interview-questions-on-linear-regression/</a></li><li><a href="https://www.projectpro.io/article/linear-regression-machine-learning-interview-questions/446">https://www.projectpro.io/article/linear-regression-machine-learning-interview-questions/446</a></li></ul><h4>2. Decision Tree:</h4><p><strong>Interview Questions:</strong></p><ul><li><a href="https://www.analyticsvidhya.com/blog/2021/05/25-questions-to-test-your-skills-on-decision-trees/">https://www.analyticsvidhya.com/blog/2021/05/25-questions-to-test-your-skills-on-decision-trees/</a></li></ul><h4>3. Random Forest:</h4><p>How does it work?:</p><ul><li><a href="https://www.analyticsvidhya.com/blog/2021/06/understanding-random-forest/">https://www.analyticsvidhya.com/blog/2021/06/understanding-random-forest/</a></li></ul><p>Interview Questions</p><ul><li><a href="https://www.analyticsvidhya.com/blog/2021/05/bagging-25-questions-to-test-your-skills-on-random-forest-algorithm/">https://www.analyticsvidhya.com/blog/2021/05/bagging-25-questions-to-test-your-skills-on-random-forest-algorithm/</a></li></ul><h4><strong>4. xgboost:</strong></h4><p>Interview Questions:</p><ul><li><a href="https://analyticsindiamag.com/top-xgboost-interview-questions-for-data-scientists/">https://analyticsindiamag.com/top-xgboost-interview-questions-for-data-scientists/</a></li><li><a href="https://towardsdatascience.com/data-science-interview-questions-ef87a3543b84">https://towardsdatascience.com/data-science-interview-questions-ef87a3543b84</a></li></ul><h3>Evaluation Metrics:</h3><h4>1. Classification metrics:</h4><ul><li>When do you use accuracy as your metric?</li><li>When do you use the ROC curve and AUC?</li><li>When do you optimize for Precision and Recall? Ans: <a href="https://support.madkudu.com/hc/en-us/articles/4407471867405-Recall-and-Precision-how-is-the-performance-of-a-model-measured-#:~:text=Optimizing%20for%20Recall%20means%20accepting,leave%20leads%20on%20the%20table.">link</a></li></ul><h4>2. Regression metrics:</h4><ul><li>When to use MSE and when to use MAE? (MSE vs MAE)<br>Ans: <a href="https://stephenallwright.com/mse-vs-mae/">https://stephenallwright.com/mse-vs-mae /</a></li></ul><p>Following are links to additional concepts and questions that I have faced in interviews:</p><h3>Additional Questions and Topics to prepare for:</h3><h4>Concepts on handling Missing Values:</h4><p><a href="https://towardsdatascience.com/7-ways-to-handle-missing-values-in-machine-learning-1a6326adf79e">https://towardsdatascience.com/7-ways-to-handle-missing-values-in-machine-learning-1a6326adf79e</a></p><p><a href="https://towardsdatascience.com/6-different-ways-to-compensate-for-missing-values-data-imputation-with-examples-6022d9ca0779">https://towardsdatascience.com/6-different-ways-to-compensate-for-missing-values-data-imputation-with-examples-6022d9ca0779</a></p><h4>Concepts on handling Outliers:</h4><p><a href="https://medium.com/analytics-vidhya/how-to-remove-outliers-for-machine-learning-24620c4657e8">https://medium.com/analytics-vidhya/how-to-remove-outliers-for-machine-learning-24620c4657e8</a></p><p><a href="https://www.analyticsvidhya.com/blog/2021/05/why-you-shouldnt-just-delete-outliers/">https://www.analyticsvidhya.com/blog/2021/05/why-you-shouldnt-just-delete-outliers/</a></p><h4>Principal Component Analysis:</h4><ul><li>Working of PCA: <a href="https://builtin.com/data-science/step-step-explanation-principal-component-analysis">link</a></li><li>Interview Questions PCA: <a href="https://www.analyticsvidhya.com/blog/2022/09/principal-component-analysis-interview-questions/">link</a></li><li>Pros and Cons of PCA: <a href="https://www.i2tutorials.com/what-are-the-pros-and-cons-of-the-pca/">link</a></li></ul><h4>Standardization and Normalization in Machine Learning:</h4><ul><li><a href="https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/">https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/</a></li></ul><h4>Handling imbalanced data:</h4><ul><li><a href="https://www.analyticsvidhya.com/blog/2021/06/5-techniques-to-handle-imbalanced-data-for-a-classification-problem/#:~:text=Imbalanced%20data%20refers%20to%20those,very%20low%20number%20of%20observations">https://www.analyticsvidhya.com/blog/2021/06/5-techniques-to-handle-imbalanced-data-for-a-classification-problem/#:~:text=Imbalanced%20data%20refers%20to%20those,very%20low%20number%20of%20observations</a>.</li></ul><h4>How to choose k in k-fold cross-validation?</h4><ul><li><a href="https://stats.stackexchange.com/questions/27730/choice-of-k-in-k-fold-cross-validation">https://stats.stackexchange.com/questions/27730/choice-of-k-in-k-fold-cross-validation</a></li></ul><p>Thank you for reading. This article is the culmination of my recent experience in preparing for interviews (Data Science and Machine Learning Engineer role). I will also be sharing a few more questions in the domain of Probability, Statistics, and some interesting questions with concepts in Machine Learning, please make sure to follow me and get notified when I publish my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9ff089bcba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow, writing custom operators and publishing them as a package: Part 2.]]></title>
            <link>https://kvirajdatt.medium.com/airflow-writing-custom-operators-and-publishing-them-as-a-package-part-2-3f4603899ec2?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f4603899ec2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 22:04:39 GMT</pubDate>
            <atom:updated>2022-08-26T22:04:39.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UxbJonFd2B6a8Uwq" /></figure><p>Welcome back to the second part of the series of building and packaging a custom airflow operator. In the previous <a href="https://kvirajdatt.medium.com/airflow-writing-custom-operators-and-publishing-them-as-a-package-part-1-177031b40c01">part</a>, we set up our local environment for packaging using poetry, we then set up our environment for running airflow in docker, and finally tested our airflow in the docker environment. In this article, we will build a simple operator in our local environment and then package it using poetry. Let us get started!!</p><h3>Table of Contents:</h3><ol><li>Setting up the plugins folder for building the operator</li><li>Details of the custom operator.</li><li>Implementing the simple custom operator.</li><li>Testing our custom operator in an Airflow Dag.</li><li>Packaging the operator (with optional formatting using the black package).</li></ol><h3>1. Setting up your plugins folder for building the operator:</h3><p>We will build our simple operator in our airflow docker setup. We have already set up the dev environment along with the required folders. The docker-compose file we ran created the plugins folder for us. Now to build a custom operator we need to create an <strong>operators</strong> folder within the dev folder we have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*eaUbeoAEZU1ci9HHTuEvZA.png" /><figcaption>operators folder created under dev/plugins</figcaption></figure><p>The hooks folder is something I created. Hooks are ways using which airflow talks and connects to external systems like a snowflake database or MySQL database. We won’t be writing any hooks in this article. To learn more about the connections and hooks in airflow you can visit the official docs <a href="https://airflow.apache.org/docs/apache-airflow/stable/concepts/connections.html">here</a>.</p><p>Next within the operator folder create an empty __init__.py file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*qau_RdGHwnljX1XBRuyfmg.png" /></figure><p>With this, we are ready to build our simple test operator.</p><h3>2. Details of the custom operator:</h3><p>The simple custom operator that we are going to build will be extending the functionality of the <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/operator/python.html">PythonOperator</a>. We will be extending the functionality of the PythonOperator which is a native airflow operator and enable it to report the time taken to complete its execution. To learn about some other details on building a custom operator and get familiar with some in-depth things you can visit the official docs <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/custom-operator.html">here</a>.</p><p>One potential use case of such an operator could be to time a long-running function for example a training loop or some computation python function.</p><h3>3. Implementing the simple custom operator:</h3><p>To extend the functionality of the PythonOperator as discussed in the previous section we will be subclassing the PythonOperator. In the operator&#39;s folder, we will create a python file named <strong>timed_python_operator.py</strong>. This python file will contain the required code for our custom operator.</p><p>The code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d63425ddd95ba82f40f5235e4aa53c8e/href">https://medium.com/media/d63425ddd95ba82f40f5235e4aa53c8e/href</a></iframe><p>We subclass the PythonOperator and create our new operator and name it as “<strong>TimedPythonOperator</strong>”. For this simple operator, we don’t implement any additional parameters hence our __init__ function will just have a call to the superclass. We implement our logic of timing the operator in the execute function. We import the time module and start tracking the time, we make a call to the execute function of PythonOperator through “<strong>super().execute(context)</strong>” and we sure pass the context to this call. In the end, our custom <strong>TimedPythonOperator </strong>will report the elapsed time which can be retrieved from the logs. If you need the elapsed time can be pushed to some database or other place for further analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVydp0EiTjKKZEJJzUC9nA.png" /><figcaption>image showing the <strong>timed_python_operator.py </strong>file</figcaption></figure><h3>4. Testing our custom operator in an Airflow Dag:</h3><p>We will test our, <strong>TimedPythonOperator </strong>with an airflow dag. For this, I created a dag under the dags folder named <strong>custom_op_test_dag.py.</strong> The following is the code present in the DAG.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5263c013b409c177773e2478bc198ce/href">https://medium.com/media/f5263c013b409c177773e2478bc198ce/href</a></iframe><p>In the above DAG, we are running a python function that prints “<em>I running using TimedPythonOperator custom operator</em>” 10 times. Since it is run using the TimedPythonOperator, at the end of the run it will log the time taken for the say_hello() function to execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evv8B0KQWCMGrk79dlcNzg.png" /></figure><p>Once I triggered the dag, I was able to see the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmpYdwcdatIeMiwzeS968Q.png" /><figcaption>logs after using <strong>TimedPythonOperator</strong></figcaption></figure><h3>5. Packaging the operator:</h3><p>Once you are done testing your operator on your local setup then you are ready to package up your airflow operator. Poetry already has given us the folder <strong>airflow_custom_operator </strong>along with the __init__.py. Now its time to copy over our <strong>operators</strong> folder from dev/operators to airflow_custom_operator/operators</p><ol><li>First, before we make the copy we would want to delete the __pycache__ folder. You can do this manually if you chose to but I have a makefile that clears such folders for me. Before I delete the __pycache__ folder I will stop my local airflow instance to make sure that the folder doesn’t get recreated.</li><li>Second, we copy-paste the dev/operators folder to airflow_custom_operator/operators.</li></ol><p>This is how my setup looks after completing the above-mentioned steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAQAx8ZCFBNl2tXrmJ1YLA.png" /><figcaption>cleaning and copying the operator&#39;s folder</figcaption></figure><p>3. Now before we build our package using poetry we want to make sure that the package once built should be capable of being registered by airflow as an operator. To ensure that airflow registers our package as an airflow operator we need to modify the airflow_custom_operator/__init__.py.</p><p>Note: <br><strong>airflow_custom_operator/__init__.py</strong> is not the same as <strong><em>airflow_custom_operator/operators/__init__.py</em></strong></p><p>We update the airflow_custom_operator/__init__.py with a function called get_provider_info() and it is just filled with metadata of our operator.</p><p>The following image shows what has been updated in the airflow_custom_operator/__init__.py file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E96GRJZDyc9SsRPF4lD-Rw.png" /></figure><p>These conclude the 3 important steps before we can build our package. Here next we have an optional 4th step.</p><p>4. Before I actually package the operator I want to make sure I have the right formatting of the python files. For that, I will use the black formatter. You can learn more about this formatter <a href="https://black.readthedocs.io/en/stable/">here</a>.</p><p>I will add the black package to our project through the following code :</p><pre>&gt;poetry add black</pre><p>Then I will run the following command to format all our python files:</p><pre>&gt; poetry run black airflow_custom_operator dev tests</pre><p>Here are the results from the above command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqe7b_kqAG9wUAL5PSpDig.png" /></figure><p>Now we are finally ready to build our package. To build your package you can run the following from the airflow-custom-operator folder</p><pre>airflow-custom-operator&gt;poetry build</pre><p>It took less than 2 seconds for the package to be built:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCOPCARTIgiCiX_gswMDaQ.png" /></figure><p>You can install the package locally using</p><pre>&gt;poetry install</pre><p>If you are looking to publish it to PyPi using poetry you can follow this <a href="https://towardsdatascience.com/how-to-publish-a-python-package-to-pypi-using-poetry-aa804533fc6f">tutorial</a>. You should be ready to ship your package in no time.</p><p>We didn’t write any unit tests for our custom operator as it was a simple operator that we developed and didn’t really need a whole lot of test cases. But there are a lot of articles out there that will teach you how to develop test cases for airflow operators. If you guys need me to also write about developing tests for airflow operators please let me know in the comments below.</p><p>Thank you everyone for reading, that is all for this series on airflow. In this 2 part series on building airflow custom operator, we looked at how to set up our environment to develop a custom airflow operator, test it with DAGS and finally package it up using poetry. I will continue to write about Airflow in the future and also other Machine Learning and MLOps-related topics all included with detailed code and screenshots for you guys to follow along.</p><p>Next I will be writing an article on <a href="https://www.comet.com/site/">cometML </a>, its features (with code and demonstration) and also how it is benifical for Data Scientists and MLOps team. Until next time, take care.</p><p>More content to follow. Please clap if the article was helpful and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html">https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html</a></li><li><a href="https://airflow.apache.org/docs/">https://airflow.apache.org/docs/</a></li><li><a href="https://python-poetry.org/docs/">https://python-poetry.org/docs/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f4603899ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow, writing custom operators and publishing them as a package: Part 1.]]></title>
            <link>https://kvirajdatt.medium.com/airflow-writing-custom-operators-and-publishing-them-as-a-package-part-1-177031b40c01?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/177031b40c01</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 21:20:53 GMT</pubDate>
            <atom:updated>2022-08-19T21:20:53.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1nwA3fR9VVheYQJ3.png" /></figure><p>Welcom to this part 1 of the tutorial series on writing airflow custom operators and publishing them as a package. In this part of the series we will setup our local environment before we can start developing our custom airflow operator. Airflow has many providers and there are a lot of operators already in the ecosystem but at times you may need to build your own operator to talk to external systems that there is no airflow operator built already. Maybe you don’t want to exactly write a whole new operator but extend the functionality of an existing operator and publish it. This article is here to help you in that journey. During my summer internship (2022 at Shipt), I took up the task of creating an operator that could talk to Kafka and Snowflake. This article is the born out from that work. Here I summarize my learnings on how I setup my local environment for the task at hand and ultimately published the operator as a package.</p><h3>Table of Contents</h3><ol><li>Poetry to intialize our project.</li><li>Installing airflow with docker-compose file.</li><li>Test the airflow instance.</li></ol><h3>1. Poetry to intialize our project:</h3><p>We will start with intializing our project. We will be using poetry to maintain and package our dependencies for this project. You can install poetry and learn more about the project from <a href="https://python-poetry.org/">docs</a>. We will be using <strong>python 3.9.13</strong> in the rest of the tutorial. We choose this version of python because we will work with airflow docker image <strong>airflow:2.2.5-python3.9</strong> which is built using python 3.9. I use VSCODE as my code editor you can choose any editor you prefer to follow along the rest of the tutorial.</p><p>Once you have poetry installed on your system you can intalize a new project using the following command.</p><pre>&gt;poetry new airflow-custom-operator</pre><p>The above command will create a python virtual environment, some folders and files for you. The dependcies we have will be managed by the file pyproject.toml.</p><p>Here is what you should see once you install poetry and run the above command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*MHMkENxOsZE4pt4nh-_NaQ.png" /></figure><p>Lets install apache-airflow package in our virtual environment. To do that change the directory to airflow-custom-operator and run the following:</p><pre>airflow-custom-operator&gt; poetry add apache-airflow@2.2.5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLox2lzO9i79OR9rcz1QsQ.png" /></figure><p>This will install apache airlfow to the virtual environment and will help you develop your code. Ensure in your code editor you set the virtual environment path you created through poetry as the interpter. This will help us a lot when we are developing our operator and help us avoid any syntax errors and give us the much needed tab completetion for productivity.</p><p>In vscode I was able to do update my interptre path to the virtual environment by running the following command.</p><pre>airflow-custom-operator&gt; poetry show -v</pre><p>The first line of output from the above command points me to the virtual environment path. I updated the same path in vscode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OODMkwqJe3qXCzljjXGqdw.png" /></figure><p>I found that having the above setup helped me in reducing syntax errors a lot during the time I was learning to work with the apache-airflow package.</p><h3>2. Installing airflow with docker-compose file:</h3><p>The poetry part is to help us setup our package for the custom operator. We set this thing upfront. Next we will need a working airflow instance to develop and test our custom airflow opertaor that we will build. To setup airflow instance we will use docker. We use docker since airflow has many services that is required for it to run and airflow provides a healthy docker-compose file to get started.</p><p>After we have settled on using docker to setup our local airflow environment. Create a folder named dev in your airflow-custom-operator folder that poetry created.</p><p>Here is what the folder looks like after the above step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*BwsoGlKhE7l95pSt0S5Etw.png" /></figure><p>To learn more about the docker-compose file you can follow the offical docs <a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html">here</a>. In this tutorial however we will use a slightly modified version of the docker-compose file. We won’t be running the flower and redis service as we won’t be using them and we also disable the example airflow jobs.</p><p>This is what our docker-compose file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32dd9ab7da2613033b71a8f9b5dd9226/href">https://medium.com/media/32dd9ab7da2613033b71a8f9b5dd9226/href</a></iframe><blockquote>You can install additional dependencies to the airflow containers by updating the line 36 in the docker-compose file mentioned above. The below line illustrates how you can <strong>install tensorflow and scikit-learn</strong> packages to your airflow <strong>containers on the fly</strong>. The best thing about this option is that you don’t have to update the airflow image</blockquote><pre>_PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:- scikit-learn tensorflow}</pre><p>We will mount the following volumes within the dev folder for easier development.</p><ul><li><strong>./dags:/opt/airflow/dags</strong> (This volume will hold our Airflow DAGS)</li><li><strong>./logs:/opt/airflow/logs </strong>(This volume will hold our Airflow Logs)</li><li><strong>./plugins:/opt/airflow/plugins</strong> (This volume will hold our Airflow plugins-hooks, operators-)</li></ul><h4>Note:</h4><ol><li>Before running the docker-compose file. Please ensure you have set <strong>docker desktop (or rancher desktop)</strong> <strong>atleast 4.5 GB of RAM</strong>. This required for the airflow UI to start. If you don’t allocate the required resources the airflow UI won’t load up. Following are the settings I have made to my setup. You don’t need to go overboard like me by allocating docker 6 GB RAM.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoWFskcZ67C8X6mEmXPDSw.png" /></figure><p>2. Create a file named <strong>.env</strong> in dev folder and include the following line</p><pre>AIRFLOW_UID=50000</pre><p>This is how things should look once you are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OZUJbuABFVQCL4gigbrXQ.png" /></figure><h3>3. Test the airflow instance</h3><p>Once you have completed the setup it is time to test things. Run the following command from dev directory.</p><pre>airflow-custom-operator/dev&gt; docker-compose up</pre><p>You should start seeing docker pull down the required images. It will take around 5–10 mins for the airflow instance to be up. The docker-compose will create a few folders in dev folders (dags, logs and plugins). Here is a view of what it will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*9s9oYowaEPWvEhwgpp1IiQ.png" /></figure><p>Once the airflow UI is up you can navigate to <a href="http://localhost:8080/">http://localhost:8080</a> and check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmbt9aEv-g6kdv5p0CEemg.png" /><figcaption>airflow UI up and running</figcaption></figure><p>To login into airflow the default username and password is airflow and airflow respectively.</p><p>username: airflow<br>password: airflow</p><p>Once you login you should be greeted with the following UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvbygEcbDkdK9Gvk4K53lw.png" /><figcaption>airflow UI</figcaption></figure><p>Next let us test our airflow setup by running a simple DAG. Create your dag under the <strong>airflow-custom-operator/dev/dags folder.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnxsNWK0mbxx5crqobqpoQ.png" /></figure><p>You can copy paste the following dag or write your own dag to test your setup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/489387b29a0a4e4a3f97ad72b978e754/href">https://medium.com/media/489387b29a0a4e4a3f97ad72b978e754/href</a></iframe><p>Your dag should show up in the UI in a minute or two. Once it does, unpause the dag and trigger it manually to compelte your test. The dag should run successfully and you should have a working airflow environment for development and testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITUTzvU56jkWIWbdTll7Sg.png" /><figcaption>airflow test dag trigged and working</figcaption></figure><p>Thank you all for reading, that’s it for this part of the series. We did quite a few things in this article to setup our local environment to start developing airflow custom operators. We started by installing poetry and created a package structure for our airflow custom operator. Then we setup our local airflow environment in docker. At last we tested our setup.</p><p>In the next part of the series we will be using this setup to develop a custom operator and test it within our airflow setup. We also will talk about linting our code, unit tests of airflow operator before we can publish the operator as a package.</p><p>More content to follow. Please clap if the article was helpful and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html">https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html</a></li><li><a href="https://airflow.apache.org/docs/">https://airflow.apache.org/docs/</a></li><li><a href="https://python-poetry.org/docs/">https://python-poetry.org/docs/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177031b40c01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Incremental Machine Learning for Streaming data with river: Part 3; Classification Algorithms…]]></title>
            <link>https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-3-classification-algorithms-315c145dcb92?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/315c145dcb92</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[incremental-learning]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 23:11:55 GMT</pubDate>
            <atom:updated>2022-07-24T23:11:55.498Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-2-classification-algorithms-525c0faaec6?source=your_stories_page-------------------------------------">Incremental Machine Learning for Streaming data with river: Part 3; Classification Algorithms</a> Ensemble Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cHZLNsNM9X5-AS_n" /><figcaption>Photo by <a href="https://unsplash.com/@knipszimmer?utm_source=medium&amp;utm_medium=referral">Marc Zimmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>Welcome back, this is the part 3 of “Incremental Machine Learning for Streaming data with river” series. In the <a href="https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-1-f0131459e85b">part1</a> of the series we have discussed the need for Incremental Leanring, some challeneges and terminolgoies, and also explored Model Drift. We also got our self familar to the River Python Package which focuses on providing user firendly machine learning library to work with streaming data and incremental/online learning. The <a href="https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-2-classification-algorithms-525c0faaec6">part2</a> of the series we discussed on how to simulate streaming data (for experimentation and research)and then we focused on few Tree Based algorithms to perform Incremental Learning.</p><p>In this part 3 of the series, we will be focusing on Ensemble Learning methods with Streaming Data. Ensemble learning mixes many models to increase prediction accuracy on unseen data. The most popular Ensemble learning methods are bagging (also known as bootstrap aggregation), and boosting.</p><p>In the remainder of this article, we will discuss the Adaptive Random Forests, Online Bagging methods, and Boosting methods for incremental ML. The bagging method, which Leo Breiman [2] first developed in 1996, selects a random sample of data from a training set with replacement, allowing for multiple selections of the individual data points. Following the generation of several data samples, these models are individually trained, and depending on the task (classification or regression ) the average or majority of those predictions result in a more accurate estimate.</p><h3>Table of Contents</h3><ol><li>Adaptive Random Forests for incremental ML and hands-on code example.</li><li>Online Bagging methods for incremental ML and hands-on code example.</li><li>Boosting methods for incremental ML and hands-on code example.</li><li>Summary of the series</li></ol><h3>1. Adaptive Random Forests for incremental ML:</h3><p>The random forest algorithm works by building multiple decision trees. The way Random Forest works in batch Machine Learning is that it makes multiple passes over the dataset. Hence a vanilla Random forest algorithm cannot be applied in Incremental ML for streaming data as it can’t handle the drift and also because it needs multiple passes over the dataset.</p><p>A variation on the random forest was introduced by Gomes and team [3] called the adaptive random forest (ARF) which works with streaming data. Online bagging is used in the ARF method to simulate resampling with replacement. ARF uses a ( lambda = 6) Poisson distribution in online bagging as opposed to the more common (lambda = 1) Poisson distribution.</p><p>The Hoeffding tree (discussed in <a href="https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-2-classification-algorithms-525c0faaec6">part2</a> of the series) serves as the foundation for ARF’s fundamental model, random forest tree training (RFTreeTrain), albeit there are a few modifications made. The RFTreeTrain differs in that it prohibits early tree cutting. Another distinction is that splits are restricted to only the features that are formed at random when a new node is created. In base trees, the ARF employs drift detectors that trigger resets anytime there is a drift. ARF enables training background trees, which, in the event of a drift, take the place of active trees.</p><p>The full algorithm for the adaptive random forest (ARF) is as follows:</p><p>The following algorithm is for the base model that ARF will use. (In batch random forest this usually is a decision tree.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*K6EVf3ZAN7wnPle8hFwycw.png" /><figcaption>Algo from Gomes, 2017 [3]</figcaption></figure><p>The following is the full algorithm of the ARF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*F8BD9ZK61l4kowiJLhpg3A.png" /><figcaption>Algo from Gomes, 2017 [3]</figcaption></figure><p>Further experiments and results of ARF can be studied by running through [3].</p><h3>1.2 Hands-on ARF with the river package:</h3><p>The river package has the AdaptiveRandomForestClassifier class which implements the ARF algorithm discussed above.</p><blockquote>The 3 most important aspects of Adaptive Random Forest 1 are:</blockquote><blockquote>inducing diversity through re-sampling</blockquote><blockquote>inducing diversity through randomly selecting subsets of features for node splits</blockquote><blockquote>drift detectors per base tree, which cause selective resets in response to drifts</blockquote><blockquote>It also allows training background trees, which start training if a warning is detected and replace the active tree if the warning escalates to a drift.</blockquote><p>Some important parameters in AdaptiveRandomForestClassifier are as follows:</p><p>a. <strong>n_models: </strong>Number of RFtrain trees in the ensemble.<br>b. <strong>max_features: </strong>Max number of attributes for each node split.<br>c. <strong>lambda_value: </strong>The lambda value for bagging it defaults to 6 (reasons discussed above).<br>d. <strong>max_depth: </strong>The maximum depth a tree can reach. By default it is infinte<br>e. <strong>split_criterion: </strong>It can be set to either(gini, information gain or hellinger distance )<br>f. <strong>leaf_prediction: </strong>Prediction mechanism used at leafs.<br>- ‘mc’ — Majority Class<br>- ‘nb’ — Naive Bayes<br>- ‘nba’ — Naive Bayes Adaptive</p><p>Following is the sample code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6e8dbbf9d7eb765d2d6f83af1990648/href">https://medium.com/media/c6e8dbbf9d7eb765d2d6f83af1990648/href</a></iframe><p>An example of how to use the ARF model to make a prediction on unseen data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dadede71251b00ae81eb9f39557c1a81/href">https://medium.com/media/dadede71251b00ae81eb9f39557c1a81/href</a></iframe><h3>2. Online Bagging methods for incremental ML:</h3><p>In batch Machine Learning Bootstrapping is the method of randomly creating samples of data out of a population with replacement to estimate a population parameter. On size N bootstrap sample sets, X base models are trained. The original training dataset is used to build the bootstrapped sample sets through sampling with replacement. Each base model’s training set includes the initial training instances K times, where P(K = k) has a binomial distribution. Additionally, K tends to have a Poisson(1) distribution when N tends to be infinite (i.e., K exp(-1)/k!).</p><p>In online bagging [4], the algorithm selects the training example K Poisson(1) times for each base model and modifies the base model as necessary. By completing majority voting of the X basic models, new instances are categorized. Both batch bagging and online bagging use the same step. Online bagging is thought to be an effective substitute for batch bagging.</p><p>The reference [4] goes into details about Online Bagging and Boosting and can be the next source to continue learning.</p><h3>2.2 Hands-On Online Bagging methods for incremental ML:</h3><p>The river package provides BaggingClassifier class for Online Bagging Classification and BaggingRegressor for Regression. In this series since we are looking at the classification methods, we will be exploring BaggingClassifier.</p><blockquote>Online bagging for classification.For each incoming observation, each model’s learn_one method is called k times where k is sampled from a Poisson distribution of parameter 1. k thus has a 36% chance of being equal to 0, a 36% chance of being equal to 1, an 18% chance of being equal to 2, a 6% chance of being equal to 3, a 1% chance of being equal to 4, etc.</blockquote><p>This class has only a few parameters.</p><ol><li><strong>model</strong>: The classifier to bag.</li><li><strong>n_models</strong>: The number of models in the ensemble.</li><li><strong>seed</strong>: Random number generator seed for reproducibility.</li></ol><p>In the example, we will use three logistic regressions bagged together. The performance is slightly better than when using a single logistic regression. We will be using the Phishing Dataset. This dataset contains features from web pages that are classified as phishing or not. For the data, we will be preprocessing it with StandardScaler.</p><p>Let us take a look at the dataset using the following code:</p><pre>from river import datasets</pre><pre>dataset = datasets.Phishing()</pre><pre># run following to get details of dataset<br>dataset</pre><pre># Taking a look at couple of the datapoints in dataset<br>list(dataset.take(2))<br></pre><p>The output will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8vjAgBJqog-TM0zCokc4JQ.png" /></figure><p>Here is the full example of building two models:</p><ol><li>A simple logistic regression (incremental model)</li><li>A bagging method with 5 base models. Each base model is logistic regression.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b230ed98fa3f13dfb07fdad358c07cd0/href">https://medium.com/media/b230ed98fa3f13dfb07fdad358c07cd0/href</a></iframe><p>Note: The pipe| character in the above code is for building a pipeline. It works similar to sklearn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">pipeline</a>.</p><h3>3. Boosting methods for incremental ML</h3><p>Boosting is a well-known ensemble learning method. The fundamental idea behind it is to successfully bring together a group of “weak learners” to produce a “strong learner.” One of the earliest boosting methods for batch data is called AdaBoost.</p><p>The online boosting classifier, which Wang devised [8], is the AdaBoost algorithm’s incremental form. Each new example in an online learning environment is trained K times using data from a binomial distribution. The binomial distribution tends to be a Poisson(lambda) distribution because there are many examples (tends to infinity), just like in a data stream. The value of is determined by keeping track of the weights of incorrectly and correctly classified samples. The ADWIN windowing approach is used by the online boosting algorithm to manage the data stream’s innate concept drift.</p><p>Following is the algorithm for Online AdaBoost Algorithm from [8].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*9suZPL4WYwt0Wzor9K94Ng.png" /></figure><h3>3.2 Hands-On Adaboost for Incremental Learning with River:</h3><p>The river package provides the AdaBoostClassifier for Online boosting.</p><blockquote>Boosting for classification. For each incoming observation, each model’s learn_one method is called k times where k is sampled from a Poisson distribution of parameter lambda. The lambda parameter is updated when the weaks learners fit successively the same observation.</blockquote><p>The parameters here are the same as the ones used by BaggingClassifier.</p><p>Here we look at the code for classifying the phishing data using the AdaBoostClassifer (we just replace BaggingClassifier with AdaBoostClassifier from the previous code).</p><p>Following is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dc5dcbd280204eadb52b2e6df7ced11/href">https://medium.com/media/0dc5dcbd280204eadb52b2e6df7ced11/href</a></iframe><h3><strong>Summary of the series:</strong></h3><p>In this three-part series on the Incremental Learning with river package, we have learned quite a few things. We started with the question of why we need to analyze data in real-time and the need for Incremental learning. Then we learned about some challenges for incremental learning on streaming data. We then looked at model drift and its various types. then we learned about window methods to analyze and detect the Drift in data. We explored the river package to detect drift. We looked at various classification algorithms in the last 2 parts of the series and leveraged the river package to perform classification incrementally on streaming data.</p><h4>The code for this tutorial can be found at:</h4><ol><li>On <a href="https://colab.research.google.com/drive/1bAiRmhoa4nMrKaRz0nz1UhV_Qiqs8Tbo#scrollTo=xwhUOMMigAaH">google colab</a></li><li>On <a href="https://github.com/Virajdatt/for-my-medium/blob/main/incremental_learning_intro/river_ensemble.ipynb">github</a></li></ol><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions. If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://www.amazon.com/Practical-Machine-Learning-Streaming-Python/dp/1484268660">https://www.amazon.com/Practical-Machine-Learning-Streaming-Python/dp/1484268660</a></li><li><a href="https://link.springer.com/content/pdf/10.1007/BF00058655.pdf">https://link.springer.com/content/pdf/10.1007/BF00058655.pdf</a></li><li>Gomes, H.M., Bifet, A., Read, J., Barddal, J.P., Enembreck, F., Pfahringer, B., Holmes, G., &amp; Abdessalem, T. (2017). Adaptive random forests for evolving data stream classification. <em>Machine Learning, 106</em>, 1469–1495.</li><li>Nikunj C. Oza and Stuart Russell. “Online Bagging and Boosting.” Artificial Intelligence and Statistics. January 2001, pp. 105–112. <a href="https://www.researchgate.net/publication/2453583_Online_Bagging_and_Boosting">https://www.researchgate.net/publication/2453583_Online_Bagging_and_Boosting</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html</a></li><li><a href="https://riverml.xyz/0.11.1/api/ensemble/BaggingClassifier/">https://riverml.xyz/0.11.1/api/ensemble/BaggingClassifier/</a></li><li><a href="https://riverml.xyz/dev/api/ensemble/AdaptiveRandomForestClassifier/">https://riverml.xyz/dev/api/ensemble/AdaptiveRandomForestClassifier/</a></li><li>B. Wang and J. Pineau, “Online Bagging and Boosting for Imbalanced Data Streams.” IEEE Transactions on Knowledge and Data Engineering. December 2016. pp. 3353–3366.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315c145dcb92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Incremental Machine Learning for Streaming data with river: Part 2, Classification Algorithms]]></title>
            <link>https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-2-classification-algorithms-525c0faaec6?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/525c0faaec6</guid>
            <category><![CDATA[incremental-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 20:00:10 GMT</pubDate>
            <atom:updated>2022-06-05T20:00:10.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mXZ_m3yIVojGy_yE" /><figcaption>Photo by <a href="https://unsplash.com/@jonflobrant?utm_source=medium&amp;utm_medium=referral">Jon Flobrant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back, this is part 2 of the “Incremental Machine Learning for Streaming data with river” series. In this present article, we will be going over some Supervised Classification Algorithms. We will first look at the key theoretical underpinnings of the algorithms and then look at the implementation in the package river. In the previous part, we have seen: why we need incremental learning, challenges with incremental learning (like concept drift), river package and finally we calculated concept drift using the river package. If you haven’t read the previous part you can check it out here at this <a href="https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-1-f0131459e85b">link</a>.</p><p>In this part, we will look at a few tree-based classification algorithms available for incremental and online learning. Before we actually start looking at the classification algorithms we will quickly look at two interesting topics required for incremental learning. First, we will look at how to simulate streaming data, this will be essential in aiding us to carry out experiments and check the performance of algorithms. Next, we will move on to discuss the evaluation strategy for incremental algorithms. With incremental learning, we cannot use the traditional machine learning evaluation methods like holding out a specific test-set to evaluate the model performance, so we check out evaluation startergies we can use for incremental learning. Finally, we look at 2 classification algorithms for streaming data:</p><p>1. Hoeffding Tree Classifier and <br>2. Extremely Fast Decision Tree Classifier:</p><h3>Table of Contents:</h3><ol><li>Simulating Streaming data</li><li>Evaluation strategy for incremental algorithms</li><li>Hoeffding Tree Classifier</li><li>HANDS-ON with the river for Hoeffding Tree Classifier</li><li>Extremely Fast Decision Tree Classifier</li><li>HANDS-ON with the river for Extremely Fast Decision Tree Classifier</li></ol><h3>1. Simulating Streaming data:</h3><p>In this article, we will use streaming data which is generated using data generators. This will help us understand and learn the implementation of the classification algorithms easily. Once we are familiar with the workings of the algorithms in the future parts, we will use real-world data and build models. Following are some of the data generators that generate streaming data:</p><ol><li><strong>Hyperplane Generator</strong>: Since we can modify the orientation and position of the hyperplane in a smooth manner by adjusting the relative sizes of the weights, hyperplanes are ideal for replicating time-changing notions. This generator introduces a change to this dataset by adding drift to each weighted feature, it is the probability that the direction of change is reversed and is the change applied to each example.<br>Following is how we can generate data using the river:</li></ol><pre>from river import synth</pre><pre>dataset = synth.Hyperplane(seed=42, n_features=2)</pre><pre>for x, y in dataset.take(5):<br>  print(x, y) </pre><pre># OUTPUT<br>#{0: 0.7319, 1: 0.5986} 1 <br>#{0: 0.8661, 1: 0.6011} 1 <br>#{0: 0.8324, 1: 0.2123} 0 <br>#{0: 0.5247, 1: 0.4319} 0 <br>#{0: 0.2921, 1: 0.3663} 0</pre><p>2. <strong>Agarwal generator</strong>: One of the first data sources for training decision tree learners was the Agarwal stream generator. The dataset contains nine distinct features. The target variable indicates whether or not a loan should be approved. Age, salary, education level, loan amount, house value, zip code, commission, the carmaker, and the number of years the house has been owned are some of the features or predictor variables in this dataset. There are 10 functions defined for generating binary class labels from the features. Presumably, these determine whether the loan should be approved.</p><pre>from river import synth</pre><pre># classification_function accepts values between 0-9<br>dataset = synth.Agrawal(classification_function=0, seed=42)</pre><pre>for x, y in dataset.take(5):<br>   print(list(x.values()), y) </pre><pre># Output<br>[68690.2154, 81303.5729, 62, 4, 6, 2, 419982.4410, 11, 433088.0728]1 <br>[98144.9515, 0, 43, 2, 1, 7, 266488.5281, 6, 389.3829] 0 [148987.502, 0, 52, 3, 11, 8, 79122.9140, 27, 199930.4858] 0 [26066.5362, 83031.6639, 34, 2, 11, 6, 444969.2657, 25, 23225.2063]1 <br>[98980.8307, 0, 40, 0, 6, 1, 1159108.4298, 28, 281644.1089] 0</pre><p>Following is a better view of the data generated using the <strong>Agarwal generator:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*EocWZU_snnpU851oe1GVhA.png" /><figcaption>source: Practical Machine Learning for Streaming Data with Python, book</figcaption></figure><p>There are many such other data generators like LED stream generator(with concept drift), Mixed data stream generator, STAGGER concepts stream generator, etc.</p><h3>2. Evaluation strategy for incremental algorithms:</h3><p>The Evaluation of the Algorithms for Incremental Machine Learning is slightly different from the traditional Machine Learning Methods. Typically in Machine Learning, we use a holdout test set that the ML algorithm has never seen before and we test the performance of our model on this dataset. But with incremental learning on streaming data the properties of data that could evolve over time need some novel ways of evaluation.Training/Testing: There are multiple ways to evaluate incremental learning models and the most frequently used one’s are as follows:</p><p>1. <strong>Holdout</strong>: Use earlier data for training and later data for testing. Meaning when you have the incoming data from a stream. Use part of it to</p><p>2. <strong>Prequential evaluation</strong> (or interleaved test-then-train): In this evaluation, the incoming stream of data is first used for testing the model performance, and then as subsequent data streams arrive the data points are used in training then. <br>3. <strong>Data chunk Evaluation</strong>: uses data chunks of a certain size instead of single instances to apply Prequential evaluation. It is a good mix of holdout and Prequential evaluation.</p><p>4. <strong>Progressive Validation</strong>: Assume you have an mtrain-sized training set and an mpv-sized test set. Progressive validation begins with the training set learning a model and then testing it on the first example of the test set. Then we test on the second example of the test set and train on the training set plus the first example of the test set. The operation is repeated for mtest iterations.</p><p>The river package contains an implementation of <strong>Progressive Validation.</strong></p><p><strong>NOTE</strong>: Evaluation strategy is different from metrics</p><h3>3. Hoeffding Tree Classifier:</h3><p>The biggest challenge with developing an incremental decision tree-based algorithm is that we don’t have access to all the data at once. With streaming data, the cost of storing the data and then later loading them in memory to train an algorithm will be really high. We get only one pass through the data as we discussed in the challenges of incremental learning in part 1 of the series. This inability to not pass through the data more than once leads to the challenge of deciding the best split attribute. In batch learning decision trees (like ), we get to choose the best split after the splits are done on various attributes and the best one is chosen based on the criteria selected (Gini-index, etc.). To address this challenge Hoffeding Tree or the Very Fast Decision Tree (VFDT) algorithm was introduced in the paper <a href="https://homes.cs.washington.edu/~pedrod/papers/kdd00.pdf">Mining High-Speed Data Streams</a>, in which instead of using previously used instances, the algorithm waits for fresh ones to arrive. The basic assumption about the data that the VFDT makes is that data is not changing over time and this helps in building the Hoeffding tree. The algorithm has the notion that small sample size is typically sufficient for determining the best splitting attribute. The statistical result known as the Hoeffding bound backs up this theory. While converting a tree leaf to a tree node, VFDT uses the Hoeffding bound to accumulate adequate statistics of new incoming observations in a data stream.</p><p>The Hoeffding bound states (with a probability of 1–£) that after n independent observations of a real-valued random variable, x, with range R, the true mean of x is at least μ − € where μ is the observed mean of the random variable x and €. Where the € has the following value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*lvmf4IaiQrD1Ekuv.png" /></figure><p>The algorithm for Hoeffding Tree Classifier is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*fQQV4ku-qFIlYq6i.png" /><figcaption>Hoeffding Tree Algorithm</figcaption></figure><h3>4. HANDS-ON with the river for Hoeffding Tree Classifier:</h3><p>Now let us see the implementation of the Hoeffding Tree Classifier in the river. We will use the Agarwal Data generator to generate our dataset. <strong>HoeffdingTreeClassifier</strong> class has the implementation which is part of the tree module. Following are some of the important parameters we pass to the HoeffdingTreeClassifier while instantiating the class.</p><p><strong>a. grace_period</strong>: Number of instances a leaf should observe between split attempts.<br><strong>b. nominal_attributes: </strong>List of Nominal attributes identifiers. If empty, then assume that all numeric attributes should be treated as continuous.<br><strong>c. split_confidence: </strong>Allowed error in a split decision, a value closer to 0 takes longer to decide.</p><pre>from river import synth<br>from river import evaluate<br>from river import metrics<br>from river import tree</pre><pre>gen = synth.Agrawal(classification_function=0, seed=42)<br># Take 1000 instances from the infinite data generator<br># The dataset object will have the data in form of streaming data</pre><pre>dataset = iter(gen.take(1000))</pre><pre>model = tree.HoeffdingTreeClassifier(grace_period=100,<br>split_confidence=1e-5,<br>nominal_attributes=[&#39;elevel&#39;, &#39;car&#39;, &#39;zipcode&#39;]<br>)</pre><pre># We will use the accuracy metric to check  </pre><pre>metric = metrics.Accuracy()</pre><pre># We evaluate our model using the <strong>Progressive Validation </strong>method</pre><pre>evaluate.progressive_val_score(dataset, model, metric)</pre><pre># OUTPUT<br># Accuracy: 83.78%</pre><h3><strong>5. Extremely Fast Decision Tree Classifier:</strong></h3><p>The extremely Fast Decision Tree classifier is also referred to as Hoeffding AnyTime Tree (HATT) classifier. EFDT works in a similar fashion to a Hoeffding tree, however, the distinction is in how they divide at nodes. The Hoeffding tree defers splitting at a node until it finds the best split and then makes no further decisions. The Hoeffding Anytime Tree splits at a node as soon as it appears to be a worthwhile split and returns to it if a better split becomes available. The Hoeffding Anytime Tree is not as fast as the Hoeffding tree in terms of processing, but it is faster in terms of statistics. Following is the pseudocode for Extremely Fast Decision Tree Classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*hLhH1aaf1r9j4ZNyPRQToA.png" /><figcaption>source: Extremely Fast Decision Tree; <a href="https://arxiv.org/pdf/1802.08780.pdf">https://arxiv.org/pdf/1802.08780.pdf</a></figcaption></figure><h3>6. HANDS-ON with the river for Extremely Fast Decision Tree Classifier:</h3><p>Following is the code for EFDT implemented with the river. We have everything the same as the previous example Hoeffding Tree Classifier (dataset, metrics, and evaluation strategy) but instead of Hoeffding Tree Classifier, we use the Extremely Fast Decision Tree Classifier.</p><pre>from river import synth<br>from river import evaluate<br>from river import metrics<br>from river import tree</pre><pre>gen = synth.Agrawal(classification_function=0, seed=42)<br># Take 1000 instances from the infinite data generator<br>dataset = iter(gen.take(1000))</pre><pre>model = tree.ExtremelyFastDecisionTreeClassifier(grace_period=100, split_confidence=1e-5, nominal_attributes=[&#39;elevel&#39;, &#39;car&#39;, &#39;zipcode&#39;], min_samples_reevaluate=100)</pre><pre>metric = metrics.Accuracy()</pre><pre>evaluate.progressive_val_score(dataset, model, metric)<br>Accuracy: 87.89%</pre><p>In conclusion, we can see that the Extremely Fast Decision Tree Classifier gives relatively better results than the Hoffedding Trees.</p><p>That’s all for this part, to quickly summarize in this part of the incremental learning series we learned about the various ways to generate synthetic data for stream data. Then we looked at the implementation of the Agarwal data generator in the river package. We learned why incremental learning has different evaluation methods compared to machine learning and we also looked at 4 types of evaluation methods. In the end, we saw two tree-based classifiers for incremental learning on streaming data.</p><p>In the next part, we will look at a few more algorithms for streaming data. We will focus mainly on Ensemble learning algorithms like Adaptive Random Forests, Online Bagging, and Boosting methods. Please stay tuned.</p><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions.If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://www.cms.waikato.ac.nz/~abifet/book/chapter_6.html">https://www.cms.waikato.ac.nz/~abifet/book/chapter_6.html</a></li><li><a href="https://riverml.xyz/dev/api/tree/HoeffdingTreeClassifier/">https://riverml.xyz/dev/api/tree/HoeffdingTreeClassifier/</a></li><li><a href="https://riverml.xyz/dev/api/synth/Hyperplane/">https://riverml.xyz/dev/api/synth/Hyperplane/</a></li><li><a href="https://riverml.xyz/dev/api/synth/Agrawal/#fnref2:1">https://riverml.xyz/dev/api/synth/Agrawal/#fnref2:1</a></li><li><a href="https://hunch.net/~jl/projects/prediction_bounds/thesis/mathml/thesisse44.xml">https://hunch.net/~jl/projects/prediction_bounds/thesis/mathml/thesisse44.xml</a></li><li><a href="https://riverml.xyz/0.11.0/api/evaluate/progressive-val-score/#examples">https://riverml.xyz/0.11.0/api/evaluate/progressive-val-score/#examples</a></li><li><a href="https://riverml.xyz/dev/api/tree/ExtremelyFastDecisionTreeClassifier/">https://riverml.xyz/dev/api/tree/ExtremelyFastDecisionTreeClassifier/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525c0faaec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Incremental Machine Learning for Streaming data with River: Part 1]]></title>
            <link>https://kvirajdatt.medium.com/incremental-machine-learning-for-streaming-data-with-river-part-1-f0131459e85b?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0131459e85b</guid>
            <category><![CDATA[incremental-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Fri, 27 May 2022 12:40:28 GMT</pubDate>
            <atom:updated>2022-05-27T13:06:58.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Leooc_mvvhLwnyIb" /><figcaption>Photo by <a href="https://unsplash.com/@kazuend?utm_source=medium&amp;utm_medium=referral">kazuend</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The amount of data generated, processed and analyzed every day is increasing at a tremendous pace. Modern smart devices(ex: cell phones, ipads), IoT devices, and social media (tweets shared, Snapchat photos sent) are some of the key contributing factors to this increased generation and analysis of data. Bernard Marr in his article <a href="https://bernardmarr.com/how-much-data-do-we-create-every-day-the-mind-blowing-stats-everyone-should-read/">How Much Data Do We Create Every Day?</a> explains in detail how social media, IoT, photos, cloud services, etc are responsible for the current explosion in data. Researchers and Industry giants have leveraged Machine Learning and Deep Learning technologies to process the tremendous volume of data to identify key patterns to aid in better decision making, and forecasting. Although the data is generated in real-time we see that most the Machine Learning Algorithms and projects do something called batch processing as opposed to real-time processing. Batch-Processing loosely can be defined as processing data collected over a period of time. Real-time processing is the processing of data almost as soon as it is generated.</p><p>In the rest of the article (and series), we will see how we can perform machine learning with real-time data. We will look at the various considerations, challenges, algorithms, tools, and libraries (mostly in python) that will aid us in our journey.</p><h3>Table of Contents:</h3><ol><li>Motivation (why do we even need to analyze data in real-time?)</li><li>Some Challenges for incremental learning on streaming data.</li><li>Some Terminologies.</li><li>Details about Model Drift.</li><li>Details on Windowing Methods.</li><li>Intro to River Package.</li><li>Hands-On Drift Detection with River.</li><li>Quick peek at the next part of the series.</li></ol><h3>1. Motivation: (so why do we even need to analyze data in real-time?)</h3><p>Real-time data analytics and insights will enable decision-makers in a business to make timely, value-added decisions. If you look at the various algorithm and machine learning projects [], almost all of them collect historic data, clean it, process it, and build predictive models. By the time all these steps in Machine Learning pipelines are complete, there is a good chance that new data is generated.</p><p>Now, what happens when new data is generated? Usually, in the traditional Machine Learning approach, the new data will be appended to the existing data and the whole ML pipeline is kicked-off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPWVxgj0hbacDf3UJ-70Sg.png" /><figcaption>Traditional ML Pipeline</figcaption></figure><p>If there were 100 data points in the first dataset on which the first ML model was trained and then we saw additional 10 data points generated (we will call this delta data). The second model will be built by training the algorithm on 100 + 10 = 110 data points. If instead of the original dataset being of 100 data points imagine it is 10 Million data points and the newly generated delta has 2 million data points. Now you can see how it is hard to scale, also it is not a time and computationally efficient method?</p><p>This is where real-time analysis and machine learning come in handy. The machine learning algorithms for real-time stream data learn from the incoming delta data. Here the model continues to learn from new data points and optimizes its objective function.</p><p>Following is an illustration that captures important aspects of real-time stream data Machine Learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIKhRxubdDzd17-Q055SOA.png" /></figure><p>Real-time analysis of data improves the <strong>Applications</strong> like:</p><ol><li>Fraud detection in real-time.</li><li>Real-time recommendations: Based on your current interaction on a website the recommendations suitable for you are “learned on the fly”.</li><li>Algorithmic trading using stock tick data. Monitoring stock trends in real-time helps trading-related decision-making.</li></ol><p>And many more are possible through the analysis of real-time data. Given its tremendous potential, numerous academic and industrial researchers are developing novel real-time analytics methods. Because real-time data presents a unique set of issues, traditional machine learning techniques do not work.</p><h3>2. Some Challenges for incremental learning on streaming data:</h3><ol><li><strong>Model or Data Drift</strong>: Data drift usually leads to instability of models at which point it won’t be useful anymore. We will explore more about this in the next section.</li><li>Usually, with streaming data, the data is not saved for a longer time. Hence the learning algorithms cannot get multiple passes through the data. Data must be processed in a single step.</li><li>Higher memory and processing requirements.</li><li>For a classification task, all the classes for the target variable may not be available right up front as usually is the case in Traditional Batch Processing Machine Learning. Ex: Consider your target variable is predicting the color of the car the customer selects. With stream data, you exactly don’t know how many classes of color you will end up with. At extreme it can be just one or more than 25.</li></ol><h3>3. Some Terminologies</h3><ol><li><strong>Stream-Data</strong>: Streaming data, often known as data streams, is an endless and continuous flow of data from a source arriving at a rapid rate. As a result, streaming data is a subset of big data that focuses on the velocity of the data. <br>Example for stream data: Tweets online, online credit card transactions.</li><li><strong>Model Drift</strong>: Model drift or model decay is the degradation of the ML model’s predictive ability due to alterations in the digital environment and subsequent changes in variables like data and concepts.</li><li><strong>Windowing</strong>: A window is a snapshot of data that can be counted by observation or measured in time. This is a particularly helpful strategy in the context of streaming data because you never have access to the “whole data” at any given time. Because new data points are given more weight, a window can successfully handle drift. Older data points are periodically removed.</li><li><strong>Incremental and Online Learning:<br>Incremental Learning</strong> When a new batch/mini-batch of data comes, incremental learning algorithms work with limited resources and constantly change model parameters.<br><strong>Online Learning</strong>: In contrast to incremental learning algorithms, online learning algorithms update the model parameters whenever a new observation is received. To update the model parameters with online learning algorithms, you don’t have to wait for a mini-batch of data to arrive.</li></ol><h3>4. Details about Model Drift:</h3><p><strong>Why is detecting Model Drift Important?</strong></p><ol><li>Important to keep the model relevant in production.</li><li>Detect the right kind of drift for corrective measures (retraining the model, training with weighted data, online learning, feature dropping or replacing the model with a new one, etc)</li></ol><p>There are 2 types of Model Drift:</p><ol><li><strong>Concept Drift</strong>: A type of model drift where the properties of target variables change over time.<br><strong>Example:</strong> A personalized recommender system profiles user shopping patterns based on past behavior. But significant changes such as customer relocation to a different geography or a global pandemic like COVID-19 drastically affect the shopping behavior making current recommender systems irrelevant.</li></ol><p><strong>Types of Concept Drifts:</strong></p><ul><li><strong>Sudden Drift</strong>: Drift occurred as a result of drastic external changes. It can be a sudden/abrupt change such as traveling patterns affected by the COVID-19 outbreak.</li><li><strong>Incremental Drift</strong>: Drift occurred due to small changes and was noticed only after a long period. For example, changes in the loan default pattern over some months require retraining of a credit scoring model.</li><li><strong>Recurrent Drift</strong>: This drift happens periodically, maybe during a specific event or time of the year. For example, the Black Friday event significantly affects consumer buying patterns. Therefore, training a different model on Black Friday data makes sense.</li></ul><p><strong>2. Data Drift</strong>: A shift observed due to changes in the statistical properties of the independent variables, such as feature distributions.</p><p><strong>Why is Data Drift Monitoring Important?</strong></p><p>Flagging data drifts and automating model retraining jobs with new data help ensure that the model is relevant in production and offers fair predictions over time. Timely insights on data drift detection help avoid model decay with best industry practices such as:</p><ol><li>Incremental learning with retraining model as new data arrives</li><li>Training with weighted data</li><li>Periodic retraining and updating models</li></ol><h3>5. Details on Windowing:</h3><p>Windowing methods are used to evaluate the data in chunks of windows to detect drift. By now we have seen what drift is and also seen what windowing is. Knowing about Windowing methods is useful to understand <strong>drift detection algorithms</strong>. There are various types of windowing techniques we will focus on the following 3:</p><p><strong><em>1] Landmark window model</em></strong>. Older data points are not discarded. All data points are accumulated in the window. Figure this model. The rectangle represents the window, and the blue circles are the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*6FOLZ0ncIxw-5GYDVekTcw.png" /></figure><p>The figure above shows that a landmark window accumulates data points over time. The window size increases as more data points arrive. This windowing technique requires large memory resources, especially when dealing with large data streams.</p><p><strong><em>2] Sliding window model</em></strong>. This is a popular way to discard older data points and consider only the recent data points for analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*aq4D452eKRqGc9dqyriBnw.png" /></figure><p>In a sliding window model, as shown in Figure “time” is the x-axis, and the observations arrive sequentially from left to right. The leftmost observation is the oldest data, and the most recent observations are on the right.</p><p><strong>3] damped window model</strong> associates weights with the data in the stream, and gives higher weights to recent data than those in the past. The data points are weighted. Higher weight is given to recent data points. An <em>exponential fading strategy </em>is used to discard old data.</p><p><strong>A comparison of the 3 windowing techniques</strong>. The <a href="https://link.springer.com/article/10.1007/s10462-020-09874-x"><em>paper</em></a><em> </em>covers the comparison in much detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*WgiJ5JbHuzvs_c_C.png" /><figcaption>Comparision from [4]</figcaption></figure><h3>6. Intro to River Package:</h3><blockquote>River is a Python library for <a href="https://www.wikiwand.com/en/Online_machine_learning">online machine learning</a>. It aims to be the most user-friendly library for doing machine learning on streaming data. River is the result of a merger between <a href="https://github.com/MaxHalford/creme">creme</a> and <a href="https://github.com/scikit-multiflow/scikit-multiflow">scikit-multiflow</a>.</blockquote><p>Some interesting facts about the river package are that it has similar API’s like sklearn and it has the potential to democratize real-time stream data machine learning in the same way as sklearn has done with traditional machine learning.</p><h3>Features of River as listed by the team (all below for Online Learning):</h3><ul><li>Linear models with a wide array of optimizers</li><li>Nearest neighbors, decision trees, naïve Bayes</li><li>Anomaly detection</li><li>Drift detection</li><li>Recommender systems</li><li>Time series forecasting</li><li>Imbalanced learning</li><li>Clustering</li><li>Feature extraction and selection</li><li>Online statistics and metrics</li><li>Built-in datasets</li><li>Progressive model validation</li><li>Model pipelines as a first-class citizen</li><li>Check out <a href="https://riverml.xyz/latest/api/overview/">the API</a> for a comprehensive overview</li></ul><p>In my experience, the documentation for river can be a little more improved in the organization so it is easier to navigate for absolute beginners who are interested in streaming data and real-time data analytics. But you need not worry we will pass through it</p><p>Installation of River:</p><pre>pip install river</pre><h3>7. Hands-On with River to Detect Drift:</h3><p>With the basic idea about streaming data, and also now equipped with the knowledge of windowing, data drift and the tool river we will now explore some advanced algorithms for drift detection. We will also explore how to use these algorithms with the river for hands-on expereince.</p><p><strong>Adaptive Windowing Method for Concept Drift Detection: </strong>In this approach, a sliding window of dynamic size is employed in the adaptive windowing approach for concept drift detection (ADWIN); that is, the window’s size is not set but is estimated online based on the rate of change detected from the data in the window.</p><p>To illustrate drift detection using ADWIN with the river we follow a few simple steps:</p><ol><li>First, create a 1000 datapoints with Standard Normal distribution (values will be between -1 to 1)</li><li>Data concepts are changed from index 599 to 999 (we change the data points here these will have a value between 5–9 now)</li><li>We try to detect Drift using ADWIN</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1-SCCz2HoHRYhrg31HNjA.png" /><figcaption>ADWIN Data Drift</figcaption></figure><p><strong>Conclusion</strong>: We see that the algorithm detected drift at the index 639 that is after seeing additional 40 odd points</p><p>Next method:</p><p><strong>Early Drift Detection Method: </strong>The Early Drift Detection Approach (EDDM) is an enhancement to the DDM method, which is particularly useful for identifying slow, progressive changes in a data stream. The idea behind the DDM approach, which we described before, was to keep track of the number of errors in the learning algorithms, but the EDDM method tracks the mean distance between two errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Szytp1u8GWSc3SbPKpxwAw.png" /></figure><p>That’s all for this article. There are other various methodologies and algorithms to detect drift. There are more python packages and other tools to do real-time machine learning we will see them in the future part of the series. In the next part, we will learn about <strong><em>Supervised Learning Algorithms for real-time streaming data</em></strong>.</p><p>The code can be accessed on :</p><ol><li><a href="https://colab.research.google.com/drive/1cRnsNf28jmIhhomIYIpZxrag634wDJpq?usp=sharing">Google-Colab</a></li><li><a href="https://github.com/Virajdatt/for-my-medium/blob/main/incremental_learning_intro/river_drift_detection.ipynb">Git-Hub</a></li></ol><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions.</p><p>If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><h3>References:</h3><ol><li><a href="https://bernardmarr.com/how-much-data-do-we-create-every-day-the-mind-blowing-stats-everyone-should-read/">https://bernardmarr.com/how-much-data-do-we-create-every-day-the-mind-blowing-stats-everyone-should-read/</a></li><li><a href="https://streamsets.com/why-dataops/what-is-data-drift/">https://streamsets.com/why-dataops/what-is-data-drift/</a></li><li><a href="https://riverml.xyz/latest/">https://riverml.xyz/latest/</a></li><li><a href="https://link.springer.com/article/10.1007/s10462-020-09874-x">https://link.springer.com/article/10.1007/s10462-020-09874-x</a></li><li><a href="https://github.com/online-ml/river">https://github.com/online-ml/river</a></li><li><a href="https://censius.ai/wiki/data-drift">https://censius.ai/wiki/data-drift</a></li><li><a href="https://www.amazon.in/Practical-Machine-Learning-Streaming-Python-ebook/dp/B0923T8ZY1">https://www.amazon.in/Practical-Machine-Learning-Streaming-Python-ebook/dp/B0923T8ZY1</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0131459e85b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Essentials:Dealing with categorical variables using the value_counts method]]></title>
            <link>https://kvirajdatt.medium.com/pandas-essentials-dealing-with-categorical-variables-using-the-value-counts-method-4f4be8d38470?source=rss-4fa440f949cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4be8d38470</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Virajdatt Kohir]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 02:10:40 GMT</pubDate>
            <atom:updated>2022-04-03T02:10:40.700Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas Essentials: Dealing with categorical variables using the value_counts method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCvH3ZV4ur1SEbx1" /><figcaption>Photo by <a href="https://unsplash.com/@bash__profile?utm_source=medium&amp;utm_medium=referral">Nicholas Cappello</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pandas is an amazing data manipulation and data wrangling library which makes an aspiring data scientist feel like a superhuman. I still remember my early days with python and pandas, it is the attractive nature of pandas along with sklearn that lead me to take up python over R (which I was working with before).</p><p>Even now after 5 years of using pandas, there are methods and tricks with pandas that still surprise me to this day. These tips and tricks I have learned over the years have increased my efficiency immensely and have given additional dimensions to my data analysis and model-building skills.</p><p>Now in this short article, I want to compile and talk about a five tricks with the value_counts method of pandas that I have learned over the past few months and have been using extensively when dealing with categorical variables.</p><p>So what is value_counts() in pandas?: In short, it lets you list the most frequently occurring elements in decreasing order in a pandas column (more specifically ). If you want to learn more about the value_counts method of pandas you can read about it <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html">here</a>. Following are the tricks :</p><h3>1. Get the rows/data points for which the frequency of a certain category is greater than the given threshold:</h3><p>Imagine that there is a categorical data column that has more than 100 or more categories/types i.e a lot of categories. Now to find the frequency of each category from this column you use value_counts.</p><p>Then use the following code to select the rows which have the frequency of a certain category greater than the threshold you want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c13887a8393524db3e62eda40298be/href">https://medium.com/media/c1c13887a8393524db3e62eda40298be/href</a></iframe><h3>2. Capture just the categories of a categorical column in decreasing order of frequency with value_counts</h3><p>If you want to retrieve only the categories of your categorical column and also want to preserve the order (decreasing in this case) you can use the following code:</p><pre>color_decreasing_frequency=df[&#39;color&#39;].value_counts().index.to_list()</pre><h3>3. Make <strong>value_counts</strong> show the count of nan in your report:</h3><p>This was a great time-saver, value_counts by default don’t count the NAN in your column but if you need to find out them for your analysis you can do it by passing dropna=<strong>False </strong>to the value_counts method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dedfdffd657581ae82b6ceeab5f6248/href">https://medium.com/media/7dedfdffd657581ae82b6ceeab5f6248/href</a></iframe><h3>4. Value_counts with the entire data frame:</h3><p>Interesting results are obtained when you run the value_counts on a data frame instead of a series (meaning when you operate not on one single column but more). This results in returning counts of frequency of the combination of values from 2 columns. Please look at the example below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed6754b1fc23bd8dbb4fa3e117f61957/href">https://medium.com/media/ed6754b1fc23bd8dbb4fa3e117f61957/href</a></iframe><p>This method has saved me immense time when I wanted to inspect the frequency of values across 2 columns. There was a time when I had developed a loop to have this functionality. Now that I know this method it has increased my productivity.</p><h3>5. Make a data frame of your value_counts results :</h3><p>Finally, this has been an absolute favorite find and I only discovered this very recently. We can convert the results of value_counts into a data frame. This is useful when you want to further manipulate the data after retrieving the frequency. Following is an example of how to do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*GkPENhmYZxrrnbVQE0ea0w.png" /></figure><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><p>Thank you for reading, that’s all for this article. More content to follow. Please clap if the article was helpful to you and comment if you have any questions.</p><p>Also, I am developing and publishing content here on medium based on my experience and learnings regularly. I write about various things in the field of Data Science, Machine Learning, and Deep Learning. Please do follow me here on medium if these areas interest you, lets&#39;s learn together.</p><p>If you want to connect with me, learn and grow with me or collaborate you can reach me at any of the following:</p><p>Linkedin:- <a href="https://www.linkedin.com/in/virajdatt-kohir/">https://www.linkedin.com/in/virajdatt-kohir/</a><br>Twitter:- <a href="https://twitter.com/kvirajdatt">https://twitter.com/kvirajdatt</a><br>GitHub:- <a href="https://github.com/Virajdatt">https://github.com/Virajdatt</a><br>GoodReads:- <a href="https://www.goodreads.com/user/show/114768501-virajdatt-kohir">https://www.goodreads.com/user/show/114768501-virajdatt-kohir</a></p><p>:) :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4be8d38470" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>