<?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 Ajit Samudrala on Medium]]></title>
        <description><![CDATA[Stories by Ajit Samudrala on Medium]]></description>
        <link>https://medium.com/@samudralaajit?source=rss-91e6297941a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6YeFL8w9Tteh2kBILhCQaA.jpeg</url>
            <title>Stories by Ajit Samudrala on Medium</title>
            <link>https://medium.com/@samudralaajit?source=rss-91e6297941a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:31:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samudralaajit/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[Density Estimation: MLE, MAP, MOM, KDE, ECDF, Q-Q Plot, GAN]]></title>
            <link>https://medium.com/analytics-vidhya/density-estimation-mle-map-mom-kde-ecdf-q-q-plot-gan-5161f84d28d7?source=rss-91e6297941a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5161f84d28d7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ajit Samudrala]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 16:59:44 GMT</pubDate>
            <atom:updated>2019-11-18T18:18:49.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*kvzAQU3wJ3Zxjf4O_UEj4g.png" /></figure><p>Statistics revolve around making estimations about the population from a sample. Density estimation is estimating the probability density function of the population from the sample.</p><h3>Terminology</h3><p><strong>Estimator: </strong>Function of data that approximates a parameter of interest. An estimator is a random variable as it is a function of a random sample.</p><p><strong>Consistent Estimator</strong>: Any estimator that converges to the true parameter of interest as the sample size tends to infinity is called a consistent estimator. The sample mean is a consistent estimator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*lHOr6e666G81D-O3qVjLsw.png" /></figure><p><strong>Unbiased Estimator:</strong> Any estimator whose expected value is equal to the true parameter of interest is called an unbiased estimator. The sample mean is an unbiased estimator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*2a74zBR8AuCq2ZrlS-sYkA.png" /></figure><p><strong>Parametric Methods</strong>: We assume the population follows a certain distribution and try to estimate its parameters from the available data.</p><p><strong>Non-parametric Methods</strong>: No assumptions are made on the population distribution. While parametric methods only involve estimating few parameters, non-parametric methods try to estimate density on the entire sample space.</p><p><strong>Explicit Density Estimation: </strong>Estimates the true pdf or cdf over the sample space.</p><p><strong>Implicit Density Estimation: </strong>Doesn’t produce explicit densities but generates a function that can draw samples from the true distribution.</p><h3>Explicit Density Estimation</h3><h4>Maximum Likelihood Estimation (MLE)</h4><p>MLE is a parametric method that maximizes the likelihood or log-likelihood function, which is a function of parameters. MLE is a random variable as it is calculated on a random sample. MLE is a consistent estimator and under certain conditions, it asymptotically converges to a normal distribution with true parameter as mean and variance equal to the inverse of the Fisher information matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*hvR_G_JmH6ppTuSFlUvSXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*PrJ3iwFuoOgOrHpo7jMfSg.png" /></figure><p>For example, if we assume our population follows a normal distribution, which is parametrized by mean and variance, the MLE is the sample mean and rescaled sample variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*HHGA4ewJH05hjOuPRGfBQQ.png" /></figure><p><strong>Consistency of MLE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*RGyGQ5k_eUafTTJwMVd7Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*PELLG5ZoHoILmwNSB5sc4A.png" /></figure><p>As aforementioned MLE is a consistent estimator i.e., as the sample size increases the MLE approaches true parameter, which is demonstrated in the above figure.</p><h4>Maximum-a-Posteriori Estimation (MAP)</h4><p>MAP takes our prior belief on true parameter into account, while calculating its posterior likelihood. If our prior belief is uniform on the parameter space, MLE is equal to MAP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*y7osFNx_XCxarTB0Q_Zt-w.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*8hZU6ERphXS91Z3ydj1Z2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*R1s5DC6Q9B1whLQZoXUgVQ.gif" /></figure><h3>Method of Moments (MOM)</h3><p>According to the Law of Large Numbers (LLN), the average converges to the expectation as the sample size tends to infinity. Using this law, the population moments which are a function of parameters are set equal to sample moments to solve for the parameters. For a normal distribution, both MLE and MOM produce sample mean as an estimate to the population mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*7lNqqVkziIevVw1HqtDE0g.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*XQG1fZYDAvpyeAPMDPjpcw.gif" /></figure><h4>Empirical Cumulative Distribution Function (ECDF)</h4><p>Another way to characterize data generating distribution a.k.a population distribution is estimating its cdf instead of pdf. ECDF is a consistent estimator, unbiased estimator and non-parametric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ZK80pf8uXzH8vYxaZNb8XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*yNXtdQoawqPPLEhpdv7L9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*UY_8IfxkBZNd8e3ZWrbXpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*41dy8JUMD4builw6eQCEmg.png" /></figure><p>As the sample size increases, the ecdf becomes close to the true cdf.</p><h4>Kernel Density Estimation (KDE)</h4><p>KDE is a non-parametric method to estimate pdf of data generating distribution. KDE allocates high density to certain x if sample data has many datapoints around it. A datapoint’s contribution to certain x depends on its distance to x and bandwidth. As the sample size increases, KDE approximation under certain conditions approaches true pdf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*hlWEI-mDmuNWSSUDeOjG4A.png" /></figure><p>Kernel function should always produce a value greater than or equal to zero and it should integrate to 1 over the sample space. Some popular kernels are uniform, gaussian, biweight, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Vbeyh2cpNgC0uuAWYKawsg.png" /><figcaption>bandwidth: Scott, Kernel: Gaussian</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*AoUvaZr848PxLMt4EqdUEA.png" /><figcaption>effect of bandwidth</figcaption></figure><p>As large bandwidths, it overestimates the density at points with fewer data points around them thus over smoothening the curve. On the other hand, if the bandwidth is very small it produces spurious fluctuations and overfits to the data.</p><h3>Q-Q Plot</h3><p>Plots the quantiles of two distributions against each other, typically against a theoretical distribution with know parameters like a standard normal distribution. If the sample is generated from a data distribution that is identical to a theoretical distribution, the q-q plot looks like a straight line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*vFp0ddzwwkZCDyzyDhRx-A.png" /></figure><p>Though Q-Q plot doesn’t estimate true pdf, it is a quick and easy way to check our assumptions about true pdf.</p><h3>Implicit Density Estimation</h3><h4>GAN</h4><p>A GAN takes a random sample from a latent distribution as input and maps it to the data space. The task of training is to learn a deterministic function that can efficiently capture the dependencies and patterns in the data so that the mapped point resembles a sample generated from the data distribution. Below I have generated 300 random samples from Isortropic Bivariate Gaussian distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcaPAgElCItnp0oCiVS_yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*R88gzkQao_dhm5lzlvKgIQ.gif" /></figure><p>When passed through the above function, the samples form a ring. In GAN, this function is essentially the generator network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuyeLSsEpObu8IskXPbc3w.png" /></figure><p>The above example demonstrates that there could be a high capacity function that may be able to model data distribution of high dimensional data like images. Neural networks are out best bet as they are universal functional approximators. Hence, deep neural networks are used while modeling data distribution of images.</p><p>I have just introduced the topics in the article. Read more about them to strengthen your understanding of them. Find the complete notebook <a href="https://github.com/ajitsamudrala/Density-Estimation-Medium">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5161f84d28d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/density-estimation-mle-map-mom-kde-ecdf-q-q-plot-gan-5161f84d28d7">Density Estimation: MLE, MAP, MOM, KDE, ECDF, Q-Q Plot, GAN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AsyncIO, Threading, and Multiprocessing in Python]]></title>
            <link>https://medium.com/analytics-vidhya/asyncio-threading-and-multiprocessing-in-python-4f5ff6ca75e8?source=rss-91e6297941a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5ff6ca75e8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ajit Samudrala]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 04:44:57 GMT</pubDate>
            <atom:updated>2021-07-13T06:16:58.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNvid2sPn5qCiR6X6QZbXQ.jpeg" /><figcaption>image taken from another medium post on java threading</figcaption></figure><p>AsyncIO is a relatively new framework to achieve concurrency in python. In this article, I will compare it with traditional methods like multithreading and multiprocessing. Before jumping into examples, I will add a few refreshers about concurrency in python.</p><ul><li>CPython enforces GIL (Global Interpreter Lock) which prevents taking full advantage of multithreading. Each thread needs to acquire this mutually exclusive lock before running any bytecode</li><li>Multithreading is usually preferred for network I/O or disk I/O as threads need not compete hard among themselves for acquiring GIL.</li><li>Multiprocessing is usually preferred for CPU intensive tasks. Multiprocessing doesn’t need GIL as each process has its state, however, creating and destroying processes is not trivial.</li><li>Multithreading with threading module is preemptive, which entails voluntary and involuntary swapping of threads.</li><li>AsyncIO is a single thread single process cooperative multitasking. An asyncio task has exclusive use of CPU until it wishes to give it up to the coordinator or event loop. (Will cover the terminology later)</li></ul><h3>Hands-on Examples</h3><h4>Delay Messages</h4><p>The program delays printing message. While the MainThread is sleeping, the CPU is idle, which is a bad use of resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c86f44f7af9f16eb9f7999f807392a1/href">https://medium.com/media/5c86f44f7af9f16eb9f7999f807392a1/href</a></iframe><pre>12:39:00:MainThread:Main started<br>12:39:00:MainThread:TWO received<br>12:39:02:MainThread:Printing TWO<br>12:39:02:MainThread:THREE received<br>12:39:05:MainThread:Printing THREE<br>12:39:05:MainThread:Main Ended</pre><h4>Concurrency with Threading</h4><p>Using python’s threading module to run multiple invocations of <em>delay_message </em>on separate non-daemon threads<em>. </em>Unsurprisingly, the program executes faster than the above synchronous version by two seconds. OS swaps threads when a thread is idle (sleeping). You can relate sleeping to making a system call to communicate with an external environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ecaf7664522f0ea430822e64902d174/href">https://medium.com/media/4ecaf7664522f0ea430822e64902d174/href</a></iframe><pre>12:39:05:MainThread:Main started<br>12:39:05:Thread-4:TWO received<br>12:39:05:Thread-5:THREE received<br>12:39:07:Thread-4:Printing TWO<br>12:39:08:Thread-5:Printing THREE<br>12:39:08:MainThread:Main Ended</pre><h4>Thread pool</h4><p>Though threads are lightweight, creating and destroying a large number of threads is expensive. concurrent.futures is built on top of the threading module and provides a neat interface to create ThreadPool and ProcessPool. Instead of creating a new thread for a function call, it reuses an existing thread in the pool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc46d61cb1ac63453b1444969567951/href">https://medium.com/media/3fc46d61cb1ac63453b1444969567951/href</a></iframe><pre>10:42:36:ThreadPoolExecutor-0_0:TWO received<br>10:42:36:ThreadPoolExecutor-0_1:THREE received<br>10:42:38:ThreadPoolExecutor-0_0:Printing TWO<br>10:42:38:MainThread:TWO Done<br>10:42:39:ThreadPoolExecutor-0_1:Printing THREE<br>10:42:39:MainThread:THREE Done</pre><h4>Concurrency with AsyncIO</h4><ol><li><strong>Coroutine:</strong> Unlike a conventional function with a single point of exit, a coroutine can pause and resume its execution. Creation of coroutine is as simple as using async keyword before declaring a function.</li><li><strong>Event Loop Or Coordinator:</strong> Coroutine that manages other coroutines. You can think of it as a scheduler or master.</li><li><strong>Awaitable object</strong> Coroutine, Tasks, and Future are awaitable objects. A coroutine can await on awaitable objects. While a coroutine is awaiting on an awaitable object, its execution is temporarily suspended and resumed after Future is done.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4c2252f60adb4ce2113c31e473d700/href">https://medium.com/media/1a4c2252f60adb4ce2113c31e473d700/href</a></iframe><pre>07:35:32:MainThread:Main started<br>07:35:32:MainThread:Current registered tasks: 1<br>07:35:32:MainThread:Creating tasks<br>07:35:32:MainThread:Current registered tasks: 3<br>07:35:32:MainThread:TWO received<br>07:35:32:MainThread:THREE received<br>07:35:34:MainThread:Printing TWO<br>07:35:35:MainThread:Printing THREE<br>07:35:35:MainThread:Main Ended</pre><p>Though the program is running on a single thread, it can achieve the same level of performance as the multithreaded code by cooperative multitasking.</p><h4>A better way to create AsyncIO tasks</h4><p>Using asyncio.gather to create multiple tasks in one shot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1020bbb60fff4637032b17fb4f50eb1/href">https://medium.com/media/d1020bbb60fff4637032b17fb4f50eb1/href</a></iframe><pre>08:09:20:MainThread:Main started<br>08:09:20:MainThread:ONE received<br>08:09:20:MainThread:TWO received<br>08:09:20:MainThread:THREE received<br>08:09:20:MainThread:FOUR received<br>08:09:20:MainThread:FIVE received<br>08:09:21:MainThread:Printing ONE<br>08:09:22:MainThread:Printing TWO<br>08:09:23:MainThread:Printing THREE<br>08:09:24:MainThread:Printing FOUR<br>08:09:25:MainThread:Printing FIVE<br>08:09:25:MainThread:Main Ended</pre><h4>Caution about Blocking Calls in AsyncIO Tasks</h4><p>As I told earlier, an asyncio task has an exclusive right to use CPU until it volunteers to give up. If by mistake a blocking call sneaks into your task, it is going to stall the progress of the program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9da40af5a703f1742d837e72150a4c4b/href">https://medium.com/media/9da40af5a703f1742d837e72150a4c4b/href</a></iframe><pre>11:07:31:MainThread:Main started<br>11:07:31:MainThread:Creating multiple tasks with asyncio.gather<br>11:07:31:MainThread:ONE received<br>11:07:31:MainThread:TWO received<br>11:07:31:MainThread:THREE received<br>11:07:34:MainThread:Printing THREE<br>11:07:34:MainThread:FOUR received<br>11:07:34:MainThread:FIVE received<br>11:07:34:MainThread:Printing ONE<br>11:07:34:MainThread:Printing TWO<br>11:07:38:MainThread:Printing FOUR<br>11:07:39:MainThread:Printing FIVE<br>11:07:39:MainThread:Main Ended</pre><p>When the delay_message receives message THREE, it makes a blocking call and doesn’t give up control to the event loop until it completes the task, thus stalling the progress of execution. Hence, it takes <em>three seconds</em> more than the previous run. Though this example seems to be tailored, it can happen if you are not careful. On the other hand, threading is preemptive, where OS preemptively switches thread if it is waiting on a blocking call.</p><h4>Race Conditions</h4><p>A multithreaded code can quickly fall apart if it doesn’t account for race conditions. It especially becomes tricky when using external libraries, as we need to verify if they support multithreaded code. For example, the session object of popular requests module is not thread-safe. Hence, trying to parallelize network requests using a session object can produce unintended results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4e53652871cc84a21b81a6792f896b4/href">https://medium.com/media/b4e53652871cc84a21b81a6792f896b4/href</a></iframe><pre>20:28:15:ThreadPoolExecutor-0_0:Update Started<br>20:28:15:ThreadPoolExecutor-0_0:Sleeping<br>20:28:15:ThreadPoolExecutor-0_1:Update Started<br>20:28:15:ThreadPoolExecutor-0_1:Sleeping<br>20:28:17:ThreadPoolExecutor-0_0:Reading Value From Db<br>20:28:17:ThreadPoolExecutor-0_1:Reading Value From Db<br>20:28:17:ThreadPoolExecutor-0_0:Updating Value<br>20:28:17:ThreadPoolExecutor-0_1:Updating Value<br>20:28:17:ThreadPoolExecutor-0_1:Update Finished<br>20:28:17:ThreadPoolExecutor-0_0:Update Finished<br>20:28:17:MainThread:Final value is 1</pre><p>The final value should ideally be 2. However, due to preemptive swapping of threads, thread-0 got swapped before updating value, hence the updates were erroneous producing final value as 1. We have to use locks to prevent this from happening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13619d78e5b0d15c942db72e70dab6a9/href">https://medium.com/media/13619d78e5b0d15c942db72e70dab6a9/href</a></iframe><pre>21:02:45:ThreadPoolExecutor-0_0:Update Started<br>21:02:45:ThreadPoolExecutor-0_0:Sleeping<br>21:02:45:ThreadPoolExecutor-0_1:Update Started<br>21:02:45:ThreadPoolExecutor-0_1:Sleeping<br>21:02:47:ThreadPoolExecutor-0_0:Reading Value From Db<br>21:02:47:ThreadPoolExecutor-0_0:Updating Value<br>21:02:47:ThreadPoolExecutor-0_0:Update Finished<br>21:02:47:ThreadPoolExecutor-0_1:Reading Value From Db<br>21:02:47:ThreadPoolExecutor-0_1:Updating Value<br>21:02:47:ThreadPoolExecutor-0_1:Update Finished<br>21:02:47:MainThread:Final value is 2</pre><h4>Race Conditions are Rare with AsyncIO</h4><p>Since the task has complete control on when to suspend execution, race conditions are rare with asyncio.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2defd7c858c802ac41a739e6438812a/href">https://medium.com/media/b2defd7c858c802ac41a739e6438812a/href</a></iframe><pre>20:35:49:MainThread:Update Started<br>20:35:49:MainThread:Sleeping<br>20:35:49:MainThread:Update Started<br>20:35:49:MainThread:Sleeping<br>20:35:50:MainThread:Reading Value From Db<br>20:35:50:MainThread:Updating Value<br>20:35:50:MainThread:Update Finished<br>20:35:50:MainThread:Reading Value From Db<br>20:35:50:MainThread:Updating Value<br>20:35:50:MainThread:Update Finished<br>20:35:50:MainThread:Final value is 2</pre><p>As you can see, once the task got resumed after sleeping, it didn’t give up control until it completed the execution of coroutine. With threading, thread swapping in not very obvious, but with asyncio, we can control on when exactly the coroutine execution should be suspended. Nonetheless, it can go wrong when two coroutines enter a deadlock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ae75475677d266c89c418562df4028b/href">https://medium.com/media/7ae75475677d266c89c418562df4028b/href</a></iframe><h4>Multiprocessing</h4><p>As aforementioned, multiprocessing comes really handy when implementing CPU intensive programs. Below code executes merge sorting on 1000lists with 30000 elements. Bear with me if below implementation of merge sort is bit clumsy.</p><h4>Synchronous version</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e7ccc6a6bc780182fee8d4db0d4e207/href">https://medium.com/media/4e7ccc6a6bc780182fee8d4db0d4e207/href</a></iframe><pre>21:24:07:MainThread:Starting Sorting<br>21:26:10:MainThread:Sorting Completed</pre><h4>Asynchronous version</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a177592a662aafcd4b2fff5b003f4509/href">https://medium.com/media/a177592a662aafcd4b2fff5b003f4509/href</a></iframe><pre>21:29:33:MainThread:Starting Sorting<br>21:30:03:MainThread:Sorting Completed</pre><p>By default, the number of processes is equal to the number of processors on the machine. You can observe a considerable improvement in execution time between two versions.</p><p>I will be writing PART 2 of this article about making asynchronous network requests and file reads. If you find any errors in the code, please feel free to comment or reach out to me on <a href="https://www.linkedin.com/in/ajitsamudrala/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5ff6ca75e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/asyncio-threading-and-multiprocessing-in-python-4f5ff6ca75e8">AsyncIO, Threading, and Multiprocessing in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Mathematics behind XGBoost]]></title>
            <link>https://medium.com/@samudralaajit/unveiling-mathematics-behind-xgboost-c7f1b8201e2a?source=rss-91e6297941a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f1b8201e2a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Ajit Samudrala]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 15:04:57 GMT</pubDate>
            <atom:updated>2019-09-09T08:54:08.541Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is targeted at people who found it difficult to grasp the original paper. Follow me till the end, and I assure you will atleast get a sense of what is happening underneath the revolutionary machine learning model. Let&#39;s get started.</p><h4>Curious case of John and Emily</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*mWtNfyZwXju3-tZfRFYcng.jpeg" /></figure><p>John and Emily embarked on an adventure to pluck apples from the tree located at the lowest point of the mountain. While Emily is a smart and adventurous girl, John is a bit cautious and sluggish. However, only John can climb tree and pluck apples. We will see how they achieve their goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LA8TV-PCjh1on6MQ1LxOVw.jpeg" /></figure><p>John and Emily start at point ‘a’ on the mountain and tree is located at point ‘g’. There are two ways they can reach point ‘g’:</p><ol><li>) Emily calculates the slope of the tangent at point ‘a’; if the slope is positive, they move in the opposite direction or else in the same direction. However, slope gives direction but doesn’t tell how much they need to move in that direction. Therefore, Emily decides to take a small step and repeat the process, so they don’t end up at the wrong point. While the direction of the step is controlled by the negative gradient, the magnitude of the step is controlled by the learning rate. If the magnitude is either too high or too low, they may end up at a wrong point or take way too long to reach to point ‘g’.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*wQXYeg4Jrvb-4a3Nz4SP7w.jpeg" /></figure><p>John is skeptical about this approach and doesn’t want to walk more if by chance they end up at the wrong point. So Emily comes up with a new approach:</p><p>2. ) Emily suggests that she will first go to the next potential points and calculate the value of the loss function at those points. She keeps a note of the value of the function at all those points, and she will signal John to come to that point where the value is least. John loved this approach as he will never end up at a wrong point. However, poor Emily needs to explore all points in her neighborhood and calculate the value of the function at all those points. The beauty of XGBoost is it intelligently tackles both these problems.</p><p>Please be advised I may use function/base learner/tree interchangeably.</p><h4>Gradient Boosting</h4><p>Many implementations of Graident Boosting follow approach 1 to minimize the objective function. At every iteration, we fit a base learner to the negative gradient of the loss function and multiply our prediction with a constant and add it to the value from the previous iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*Ghv8bGUk0zzYfUouEJYuyw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Gradient_boosting">Source: Wikipedia</a></figcaption></figure><p>The intuition is by fitting a base learner to the negative gradient at each iteration is essentially performing gradient descent on the loss function. The negative gradients are often called as pseudo residuals, as they indirectly help us to minimize the objective function.</p><h4>XGBoost</h4><p>It was a result of research by Tianqi Chen, a Ph.D. student at the University of Washington. XGBoost is an ensemble additive model that is composed of several base learners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*hyVH1RhJaDkDksy7_f4Ocw.jpeg" /></figure><p>How should we choose a function at each iteration? we chose a function that minimizes the overall loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*pzR03dxcSOhn2tnKtAXo3A.jpeg" /></figure><p>In the gradient boosting algorithm stated above, we obtained ft(xi) at each iteration by fitting a base learner to the negative gradient of the loss function with respect to previous iteration’s value. In XGBoost, we explore several base learners or functions and pick a function that minimizes the loss (Emily’s second approach). As I stated above, there are two problems with this approach: 1.) exploring different base learners 2.) calculating the value of the loss function for all those base learners.</p><p>XGBoost uses Taylor series to approximate the value of the loss function for a base learner ft(xi), thus, reducing the load on Emily to calculate the exact loss for different possible base learners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZDFiZ8EaBUbv8POwgAwcQ.jpeg" /></figure><p>It only uses expansion upto second order derivative assuming this level of approximation would suffice. The first term ‘C’ is constant irrespective of any ft(xi) we pick. ‘gi’ is the first order derivative of loss at the previous iteration with respect predictions at previous iteration. ‘hi’ is the second order derivative of loss at previous iteration with respect to predictions at previous iteration. Therefore, Emily can calculate ‘gi’ and ‘fi’ before starting exploring different base learners, as it will be just a matter of multiplications thereafter. Plug and play, isn’t it?</p><p>So XGBoost has reduced one of the burdens on Emily. Still, we have a problem of exploring different base learners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sku1s6Y2NYyh71scMy8fSA.jpeg" /></figure><p>Assume Emily fixed a base learner ft that has ‘K’ leaf nodes. Let Ij be the set of instances belonging to node ‘j’ and ‘wj’ be the prediction for that node. So for an instance ‘i’ belonging to Ij, ft(xi)=wj. Therefore, we obtained equation 3 from equation 2 by substituting ft(xi) with respective predictions. After substituting the predictions, we can take the derivative of the loss function with respect to each leaf node’s weight, to get optimal weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*-tt8E0OzV2O2pKH6v5wMuQ.jpeg" /></figure><p>Substituting the optimal weights back into equation 3 gives equation 4. However, this is the optimal loss for a fixed tree structure. There will be several hundreds of possible trees.</p><p>Let&#39;s formulate the current position of Emily. She now knows how to ease the burden of computing loss using Taylor expansion. She knows for a fixed tree structure what should be the optimal weights in the leaf node. The only thing that is still a concern is how to explore all different possible tree structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*De1hXISG0y_7iL6OhxrJIw.jpeg" /></figure><p>Instead of exploring all possible tree structures, XGBoost greedily builds a tree. The split that results in maximum loss reduction is chosen. In the above picture, the tree starts at Node ‘I’. Based on some split criteria, the node is divided into left and right branches. So some instances fall in the left node and other instances fall in right leaf node. Now, we can calculate the reduction in loss and pick the split that causes the best reduction in loss.</p><p>But still, Emily has one more problem. How to chose the split criteria? XGBoost uses different tricks to come up with different split points like histogram, exact, etc. I will not be dealing with that part, as this article has already grown in size.</p><h4>Bullet Points to Remember</h4><ol><li>) While Gradient Boosting follows negative gradients to optimize the loss function, XGBoost uses Taylor expansion to calculate the value of the loss function for different base learners. Here is the best video on the internet that explains <a href="https://www.youtube.com/watch?v=3d6DsjIBzJ4&amp;t=447s">Taylor expansion</a>.</li><li>) XGBoost doesn’t explore all possible tree structures but builds a tree greedily.</li><li>) XGBoost’s regularization term penalizes building complex tree with several leaf nodes.</li><li>) XGBoost has several other tricks under its sleeve like Column subsampling, shrinkage, splitting criteria, etc. I highly recommend continuing reading the original paper <a href="https://arxiv.org/pdf/1603.02754.pdf">here</a>.</li></ol><p>You can view the complete derivation <a href="https://drive.google.com/open?id=1CmNhi-7pZFnCEOJ9g7LQXwuIwom0ZN_D">here</a>.</p><p>Read my other article on PCA <a href="https://www.linkedin.com/pulse/eigendecomposition-singular-value-decomposition-ajit-samudrala/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f1b8201e2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>