<?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 Abhishek on Medium]]></title>
        <description><![CDATA[Stories by Abhishek on Medium]]></description>
        <link>https://medium.com/@abhic159?source=rss-9a0d4f01560c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KhPQV4Y8DX86eNp6c4tIPQ.jpeg</url>
            <title>Stories by Abhishek on Medium</title>
            <link>https://medium.com/@abhic159?source=rss-9a0d4f01560c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:04:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhic159/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[Part 1: The Foundations of Machine Learning and Statistics]]></title>
            <link>https://abhic159.medium.com/part-1-the-foundations-of-machine-learning-and-statistics-89baf6167e43?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89baf6167e43</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 15:44:12 GMT</pubDate>
            <atom:updated>2026-06-13T15:44:12.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Every dataset has a story to tell, but it rarely speaks in plain English. Whether you’re forecasting sales trends for a retail storefront, breaking down years of Economics exam papers to spot historical patterns, or fine-tuning an object detection model to map out a physical space, you are essentially trying to translate raw, messy data into a clean, predictive narrative.</h3><p>But before we can build complex machine learning architectures or deep neural networks, we have to understand the mathematical heartbeat beneath them all.</p><p>Welcome to <strong>Part 1</strong> of our new series: <em>The Foundations of Machine Learning and Statistics</em>.</p><p>In this series, we are going back to basics. We’re stripping away the jargon and looking at the math that makes prediction possible, chapter by chapter. Today, we kick things off with the granddaddy of all algorithms: <strong>Two-Variable Linear Regression</strong>.</p><p>If you want to understand how variables interact in the real world, this is where you start.</p><h3>1. The Hypothetical Setup: Finding the Signal</h3><p>To understand regression, we first have to understand the <strong>Population Regression Function (PRF)</strong>.</p><p>Let’s use a classic Econometrics example: the relationship between a family’s Weekly Income X and their Weekly Consumption Expenditure Y.</p><p>If you pick a specific income level say, families making exactly $200 a week you won’t find that they all spend the exact same amount. Instead, there is a <em>subpopulation</em> of expenditure values. Some families save more, some spend more. However, if we average out the spending of <em>only</em> those families making $200, we find the <strong>conditional mean</strong> or expected value.</p><p>Mathematically, we write this as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*MbwShlIIQ5f59t0sVYmt3w.png" /></figure><p>E(Y | Xi) = f(Xi)</p><p><em>(Read as: The expected value of Y, given a specific value of X, is a function of X).</em></p><p>If we plot these conditional means on a graph and connect the dots, we get the Population Regression Curve. Assuming this relationship is a straight line, we arrive at our first major formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*C-_m-ozPLkCxLgLmpsk7qA.png" /></figure><p><strong>Visualizing the Conditional Mean:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*aboOr4VfnzMJLlkugaCAsA.png" /></figure><h3>2. The “Linear” in Linear Regression (A Common Trap)</h3><p>Here is a concept that trips up a lot of people: What does “linear” actually mean?</p><p>It does <strong>not</strong> mean the variables themselves have to be linear. You can square X, take the logarithm of X, or raise X to the third power. As long as the <strong>parameters</strong> (betas) are linear, it is still a linear regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*fWtwxZebRuJSwdXvlWqJZA.png" /></figure><p>When data scientists and econometricians talk about linear regression, we are exclusively talking about linearity in the parameters.</p><h3>3. Embracing the Noise: The Stochastic Error Term</h3><p>The formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*D6hJYAIV3H9Og2aHKuC4UQ.png" /></figure><p>is clean and perfect. But the real world is neither.</p><p>If we look at an individual family, their actual spending Yi will almost certainly deviate from the expected mean. To account for this reality, we introduce the ghost in the machine: the <strong>stochastic error term</strong> ui.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*iiBopwDHbqEkTN9hCnRBcA.png" /></figure><p><strong>Visualizing the Error Term:</strong></p><p>Plaintext</p><pre>Y<br>       |<br>       |       * (Yi - Actual observed data point)<br>       |       | <br>       |       | ui (The Stochastic Error Term)<br>       |       v<br>       |-------+------- Expected Value Line: E(Y|Xi) = β1 + β2Xi<br>       |<br>       |_______________________ X</pre><p><strong>Why does ui exist?</strong></p><p>Why can’t we just predict things perfectly?</p><ul><li><strong>Vagueness of theory:</strong> We know income affects consumption, but what about wealth, or age?</li><li><strong>Unavailability of data:</strong> We might not have the data for those other factors.</li><li><strong>Core vs. Peripheral variables:</strong> Some influences are simply too small to bother measuring.</li><li><strong>Intrinsic randomness:</strong> Human behavior isn’t entirely deterministic. People are unpredictable!</li><li><strong>Principle of parsimony:</strong> We want to keep our models as simple as possible.</li></ul><h3>4. Reality Bites: The Sample Regression Function (SRF)</h3><p>Here is the hardest truth in statistics: <strong>You will almost never have the population data.</strong> You will never know the true beta_1 or beta_2, and you will never see the true Population Regression Line. Instead, you get a sample. And from that sample, you must <em>estimate</em> the truth.</p><p>This gives us the <strong>Sample Regression Function (SRF)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*vihqak0n8PsLpzoInTpGFQ.png" /></figure><p>Because different samples yield different data points, every time you take a new sample, you will generate a slightly different sample regression line.</p><p><strong>Visualizing Population vs. Sample Lines:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*LArFLJ26LzipIEINhWoeww.png" /></figure><p>Our ultimate goal is to find the Sample Regression Function that sits as close to the invisible Population Regression Function as mathematically possible.</p><h3>What’s Next?</h3><p>Understanding these foundational ideas — the difference between the underlying population truth and our sample-based estimates, and why the error term exists — is the very first step in predictive modeling.</p><p>But it leaves us with a massive cliffhanger: <strong>If we only have our sample data, how do we actually calculate beta hats to draw that best-fit line?</strong></p><p>If this first chapter resonated with you, hit subscribe and stick around. In <strong>Part 2</strong> of the <em>Machine Learning &amp; Statistics Series</em>, we will dive into the elegant mechanics of <strong>Ordinary Least Squares (OLS)</strong> estimation. We’ll uncover how the math forces that line to balance perfectly through your data points.</p><p>You won’t want to miss it. Until then, keep looking for the story behind your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89baf6167e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploration vs Exploitation — Cracking the Science of Decision Making: Multi-Armed Bandits]]></title>
            <link>https://abhic159.medium.com/exploration-vs-exploitation-cracking-the-science-of-decision-making-multi-armed-bandits-86d87a0cb2f1?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d87a0cb2f1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 05:12:55 GMT</pubDate>
            <atom:updated>2025-02-22T05:12:55.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l5hmINTYiFYdqKZB" /></figure><h3>Exploration vs Exploitation — Cracking the Science of Decision Making: Multi-Armed Bandits</h3><h3>Introduction</h3><p>In decision-making scenarios under uncertainty, the trade-off between exploring new options and exploiting known ones is a fundamental challenge. This balance is elegantly addressed by the <strong>Multi-Armed Bandit (MAB)</strong> problem, a classical framework in reinforcement learning, decision theory, and stochastic optimization. The MAB framework models a scenario where a decision-maker must balance the immediate gains from exploiting known options against the potential benefits of exploring new, possibly better, choices. This article dives deep into the world of Multi-Armed Bandits, exploring its core concepts, mathematical foundations, various algorithmic approaches, real-world applications, challenges, and hands-on implementation with code examples.</p><h3>Definition and Core Concepts</h3><h3>What is a Multi-Armed Bandit?</h3><p>A Multi-Armed Bandit is a problem scenario where a decision-maker must choose between multiple options (or “arms”), each with unknown reward distributions. The term originates from the analogy of a gambler facing several slot machines (bandits), each with different probabilities of payout. The objective is to maximize the total reward over a sequence of choices.</p><p>Formally, the MAB problem can be represented as a set of <em>k</em> arms, each associated with a probability distribution of rewards. At each timestep, the agent selects one arm and receives a reward drawn from that arm’s distribution. Over time, the agent learns about the reward distributions and improves its decision-making strategy.</p><h3>Exploration vs Exploitation</h3><ul><li><strong>Exploration</strong> involves trying out different arms to gather information about their reward distributions. This is crucial for understanding the environment and identifying potentially high-reward arms.</li><li><strong>Exploitation</strong> focuses on selecting the arm that currently seems to offer the highest reward based on past data. This maximizes immediate returns but can risk missing out on better options.</li></ul><p>The fundamental trade-off between exploration and exploitation is central to the MAB problem. Too much exploration can lead to suboptimal rewards, while excessive exploitation can cause the agent to miss out on better opportunities.</p><h3>Architecture of the Multi-Armed Bandit</h3><p>The MAB framework consists of:</p><ul><li><strong>Arms:</strong> Each arm represents an action with an unknown reward distribution. The arm’s behavior is often modeled using probability distributions like Bernoulli, Gaussian, or Poisson.</li><li><strong>Agent:</strong> Makes decisions on which arm to pull based on a specific algorithm or policy.</li><li><strong>Reward Mechanism:</strong> Provides feedback (reward) after each pull, which the agent uses to update its strategy.</li></ul><p><em>Visual Representation:</em></p><pre>+------------+       +----------+       +-----------+<br>|  Decision  |-----&gt; |  Select  |-----&gt; |  Reward   |<br>|   Policy   |       |   Arm    |       | Mechanism |<br>+------------+       +----------+       +-----------+<br>        ^                                    |<br>        |------------------------------------|</pre><p>This simple yet powerful architecture enables the modeling of complex decision-making processes in uncertain environments.</p><h3>Objective and Cost Function</h3><p>The primary objective in a MAB problem is to maximize the cumulative reward over time. This is often formalized by minimizing the <strong>regret</strong>, which quantifies the loss incurred by not always selecting the optimal arm.</p><p><em>Regret (Rₜ) = t * μ — Σₜ rₜ</em>*</p><p>Where:</p><ul><li><strong>μ</strong>* is the expected reward of the optimal arm.</li><li><strong>rₜ</strong> is the reward received at time <em>t</em>.</li></ul><p>Minimizing regret ensures that the agent’s performance approaches that of an oracle who always picks the best arm.</p><h3>How Does a Multi-Armed Bandit Work?</h3><p>The MAB algorithm operates in iterative cycles, where the agent selects an arm, observes the reward, and updates its decision-making policy based on this new information. Each iteration involves:</p><ol><li><strong>Arm Selection</strong> based on the current policy or algorithm.</li><li><strong>Reward Observation</strong> after pulling the arm.</li><li><strong>Policy Update</strong> using the observed reward to refine future decisions.</li></ol><h3>Modeling an Arm</h3><p>Each arm is modeled as a stochastic process with a specific reward distribution. Common choices include:</p><ul><li><strong>Bernoulli Distribution:</strong> For binary rewards (success/failure).</li><li><strong>Gaussian Distribution:</strong> For continuous rewards with noise.</li><li><strong>Poisson Distribution:</strong> For count-based rewards.</li></ul><p>The agent estimates these distributions over time using statistical methods, improving its selection strategy.</p><h3>Reward and Regret Distributions</h3><ul><li><strong>Reward Distribution:</strong> Reflects the probability of obtaining specific rewards from each arm.</li><li><strong>Regret Distribution:</strong> Evaluates the gap between the actual rewards obtained and the rewards from the optimal strategy.</li></ul><p>Understanding these distributions is crucial for designing effective bandit algorithms.</p><h3>Exploration vs Exploitation: Multi-Armed Bandits</h3><h3>Introduction</h3><p>In decision-making scenarios under uncertainty, the trade-off between exploring new options and exploiting known ones is a fundamental challenge. This balance is elegantly addressed by the <strong>Multi-Armed Bandit (MAB)</strong> problem, a classical framework in reinforcement learning, decision theory, and stochastic optimization. The MAB framework models a scenario where a decision-maker must balance the immediate gains from exploiting known options against the potential benefits of exploring new, possibly better, choices. This article dives deep into the world of Multi-Armed Bandits, exploring its core concepts, mathematical foundations, various algorithmic approaches, real-world applications, challenges, and hands-on implementation with code examples.</p><p>The MAB problem is not merely academic — it has practical applications in areas like online advertising, clinical trials, finance, and recommendation systems. Its ability to make sequential decisions with incomplete information makes it a cornerstone in modern data-driven decision-making strategies.</p><h3>Types of Approaches</h3><h3>1. Epsilon-Greedy</h3><p>The Epsilon-Greedy algorithm is one of the simplest methods to balance exploration and exploitation. It introduces randomness into the decision-making process to ensure that exploration occurs regularly.</p><p><strong>Math Behind Epsilon-Greedy:</strong></p><ul><li>With probability <strong>ε</strong> (epsilon), the agent explores by selecting a random arm.</li><li>With probability <strong>1 — ε</strong>, the agent exploits by selecting the arm with the highest estimated reward.</li></ul><p>The average reward for each arm is updated using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*bK5Plc_UX-bAGzN5JCi8CQ.png" /></figure><p><strong>Iteration Process:</strong></p><ol><li>Generate a random number between 0 and 1.</li><li>If this number &lt; ε, explore by choosing a random arm.</li><li>Otherwise, exploit by selecting the arm with the highest x̄i.</li><li>Pull the selected arm and observe the reward.</li><li>Update the average reward x̄i or the selected arm.</li></ol><p><strong>Exploration vs Exploitation Decision:</strong> The value of ε determines the exploration rate. A higher ε encourages more exploration, while a lower ε favors exploitation. Dynamic ε strategies, where ε decreases over time, are often used to shift focus from exploration to exploitation as the agent gathers more data.</p><h3>2. Upper Confidence Bound (UCB)</h3><p>The UCB algorithm selects arms based on both the estimated reward and the uncertainty of that estimate, promoting a balanced approach that favors arms with high potential.</p><p><strong>Math Behind UCB:</strong> The selection formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*CAWD0MKtCQdQfMvWgjrW3g.png" /></figure><p><strong>Interpretation:</strong></p><ul><li>The first term x̄i promotes exploitation by favoring high-reward arms.</li><li>The second term encourages exploration by adding a bonus for less frequently chosen arms.</li></ul><p><strong>Iteration Process:</strong></p><ol><li>Calculate UCBi for each arm.</li><li>Select the arm with the highest UCBi.</li><li>Pull the arm and observe the reward.</li><li>Update x̄ and ni for the selected arm.</li><li>Repeat, allowing the algorithm to dynamically balance exploration and exploitation.</li></ol><p><strong>Exploration vs Exploitation Decision:</strong> The logarithmic term ln⁡t\ln t ensures that as time progresses, even well-performing arms continue to be explored, albeit less frequently. The constant cc acts as a tuning parameter, determining the extent of exploration.</p><h3>3. Thompson Sampling</h3><p>Thompson Sampling, also known as Bayesian Bandits, is a probabilistic algorithm that selects arms based on their likelihood of being the best option. It is particularly effective in balancing exploration and exploitation without requiring explicit exploration parameters.</p><p><strong>Math Behind Thompson Sampling:</strong></p><ul><li>Each arm is modeled using a probability distribution (typically a Beta distribution for Bernoulli rewards).</li><li>The algorithm samples from these distributions to decide which arm to pull.</li></ul><p>The Beta distribution is updated using Bayes’ Theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ncG2yhmbHwLpSVXPvgpqA.png" /></figure><p><strong>Iteration Process:</strong></p><ol><li>For each arm, sample a value from its Beta distribution.</li><li>Select the arm with the highest sampled value.</li><li>Pull the selected arm and observe the reward.</li><li>Update the Beta distribution parameters based on the reward.</li><li>Repeat the process.</li></ol><p><strong>Exploration vs Exploitation Decision:</strong> Thompson Sampling naturally balances exploration and exploitation by sampling from distributions. Arms with uncertain or high expected rewards are more likely to be explored, ensuring a probabilistic approach to decision-making.</p><p>These detailed explanations of the Epsilon-Greedy, UCB, and Thompson Sampling approaches provide comprehensive insights into their mathematical foundations and operational dynamics, helping to understand how they handle the exploration-exploitation trade-off in Multi-Armed Bandits. This expanded view includes deeper theoretical underpinnings, practical implementation strategies, and nuanced decision-making processes, offering a robust guide for applying these methods in real-world scenarios.</p><p>In the next sections, we will explore real-world applications, challenges, limitations, and provide a complete hands-on implementation with code examples, demonstrating the power and versatility of Multi-Armed Bandit algorithms in data-driven decision-making.</p><h3>Comparison of Approaches</h3><ul><li><strong>Epsilon-Greedy</strong> is simple but less efficient.</li><li><strong>UCB</strong> dynamically balances exploration and exploitation.</li><li><strong>Thompson Sampling</strong> offers a probabilistic approach with strong empirical performance.</li></ul><h3>Hands-on Implementation</h3><p><strong>Use Case:</strong> Dynamic Pricing in E-commerce</p><pre># Multi-Armed Bandit Implementation: Epsilon-Greedy, UCB, and Thompson Sampling<br><br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>class BanditArm:<br>    def __init__(self, true_mean):<br>        self.true_mean = true_mean<br>        self.estimated_mean = 0<br>        self.n = 0<br><br>    def pull(self):<br>        return np.random.randn() + self.true_mean<br><br>    def update(self, reward):<br>        self.n += 1<br>        self.estimated_mean = ((self.n - 1) * self.estimated_mean + reward) / self.n<br><br>class EpsilonGreedy:<br>    def __init__(self, epsilon, n_arms):<br>        self.epsilon = epsilon<br>        self.arms = [BanditArm(np.random.rand() * 10) for _ in range(n_arms)]<br><br>    def select_arm(self):<br>        if np.random.rand() &lt; self.epsilon:<br>            return np.random.choice(len(self.arms))<br>        return np.argmax([arm.estimated_mean for arm in self.arms])<br><br>    def run(self, iterations):<br>        rewards = []<br>        for _ in range(iterations):<br>            chosen_arm = self.select_arm()<br>            reward = self.arms[chosen_arm].pull()<br>            self.arms[chosen_arm].update(reward)<br>            rewards.append(reward)<br>        return rewards<br><br>class UCB:<br>    def __init__(self, c, n_arms):<br>        self.c = c<br>        self.arms = [BanditArm(np.random.rand() * 10) for _ in range(n_arms)]<br>        self.total_pulls = 0<br><br>    def select_arm(self):<br>        self.total_pulls += 1<br>        ucb_values = [arm.estimated_mean + self.c * np.sqrt(np.log(self.total_pulls + 1) / (arm.n + 1e-5))<br>                      for arm in self.arms]<br>        return np.argmax(ucb_values)<br><br>    def run(self, iterations):<br>        rewards = []<br>        for _ in range(iterations):<br>            chosen_arm = self.select_arm()<br>            reward = self.arms[chosen_arm].pull()<br>            self.arms[chosen_arm].update(reward)<br>            rewards.append(reward)<br>        return rewards<br><br>class ThompsonSampling:<br>    def __init__(self, n_arms):<br>        self.alphas = [1] * n_arms<br>        self.betas = [1] * n_arms<br>        self.true_means = [np.random.rand() * 10 for _ in range(n_arms)]<br><br>    def pull(self, arm):<br>        return np.random.randn() + self.true_means[arm]<br><br>    def select_arm(self):<br>        samples = [np.random.beta(self.alphas[i], self.betas[i]) for i in range(len(self.alphas))]<br>        return np.argmax(samples)<br><br>    def update(self, arm, reward):<br>        if reward &gt; 0:<br>            self.alphas[arm] += 1<br>        else:<br>            self.betas[arm] += 1<br><br>    def run(self, iterations):<br>        rewards = []<br>        for _ in range(iterations):<br>            chosen_arm = self.select_arm()<br>            reward = self.pull(chosen_arm)<br>            self.update(chosen_arm, reward)<br>            rewards.append(reward)<br>        return rewards<br><br># Running the Algorithms<br>iterations = 1000<br>n_arms = 5<br><br>epsilon_greedy = EpsilonGreedy(epsilon=0.1, n_arms=n_arms)<br>ucb = UCB(c=2, n_arms=n_arms)<br>thompson = ThompsonSampling(n_arms=n_arms)<br><br>eg_rewards = epsilon_greedy.run(iterations)<br>ucb_rewards = ucb.run(iterations)<br>thompson_rewards = thompson.run(iterations)<br><br># Plotting Results<br>plt.figure(figsize=(12, 6))<br>plt.plot(np.cumsum(eg_rewards), label=&#39;Epsilon-Greedy&#39;)<br>plt.plot(np.cumsum(ucb_rewards), label=&#39;UCB&#39;)<br>plt.plot(np.cumsum(thompson_rewards), label=&#39;Thompson Sampling&#39;)<br>plt.xlabel(&#39;Iterations&#39;)<br>plt.ylabel(&#39;Cumulative Reward&#39;)<br>plt.title(&#39;Multi-Armed Bandit Algorithms Comparison&#39;)<br>plt.legend()<br>plt.show()</pre><h3>Explanation of Multi-Armed Bandit Code Implementation</h3><h3>Problem Statement</h3><p>The problem tackled by this code is the classic <strong>Multi-Armed Bandit (MAB)</strong> scenario, where the goal is to maximize cumulative rewards by selecting from multiple bandit arms, each with an unknown reward distribution. The decision-maker must balance <strong>exploration</strong> (trying new arms to gather more information) and <strong>exploitation</strong> (choosing arms that have previously yielded high rewards). This is done using three strategies: <strong>Epsilon-Greedy</strong>, <strong>Upper Confidence Bound (UCB)</strong>, and <strong>Thompson Sampling</strong>.</p><h3>Class Explanations</h3><h3>1. BanditArm Class</h3><p><strong>Purpose:</strong> Models an individual slot machine arm.</p><p><strong>Attributes:</strong></p><ul><li>true_mean: The actual average reward of the arm (unknown to the agent).</li><li>estimated_mean: The agent&#39;s running estimate of the arm’s average reward.</li><li>n: Counter for the number of times this arm has been pulled.</li></ul><p><strong>Methods:</strong></p><ul><li>pull(): Simulates pulling the arm, returning a reward drawn from a normal distribution centered at true_mean.</li><li>update(reward): Updates the estimated_mean after each pull using incremental averaging.</li></ul><p><strong>Iteration:</strong></p><ol><li>The arm is pulled, generating a reward.</li><li>The reward updates the running average.</li></ol><h3>2. EpsilonGreedy Class</h3><p><strong>Purpose:</strong> Implements the Epsilon-Greedy strategy, which explores randomly with a probability <strong>ε</strong> and exploits the best-known arm otherwise.</p><p><strong>Attributes:</strong></p><ul><li>epsilon: Probability of exploration.</li><li>arms: List of BanditArm instances.</li></ul><p><strong>Methods:</strong></p><ul><li>select_arm(): Chooses a random arm with probability ε, otherwise selects the arm with the highest estimated reward.</li><li>run(iterations): Repeats arm selection and reward collection over a specified number of iterations.</li></ul><p><strong>Iteration:</strong></p><ol><li>Generate a random number.</li><li>If below ε, pick a random arm (explore).</li><li>Else, pick the arm with the highest estimated reward (exploit).</li><li>Pull the arm, get the reward, and update the estimate.</li></ol><h3>3. UCB Class</h3><p><strong>Purpose:</strong> Uses the Upper Confidence Bound approach, which selects arms based on both their estimated rewards and the uncertainty around these estimates.</p><p><strong>Attributes:</strong></p><ul><li>c: Exploration parameter controlling how much to explore.</li><li>arms: List of BanditArm instances.</li><li>total_pulls: Total number of arm pulls across all arms.</li></ul><p><strong>Methods:</strong></p><ul><li>select_arm(): Computes UCB for each arm and selects the one with the highest score.</li><li>run(iterations): Iteratively selects arms and collects rewards.</li></ul><p><strong>Iteration:</strong></p><ol><li>Calculate UCB for each arm:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*BkNGVRKzmGw1XnxX5Lm1Pw.png" /></figure><ol><li>Select the arm with the highest UCB.</li><li>Pull the arm, get the reward, and update the estimate.</li></ol><h3>4. ThompsonSampling Class</h3><p><strong>Purpose:</strong> Uses Bayesian methods to select arms based on sampled probabilities.</p><p><strong>Attributes:</strong></p><ul><li>alphas: Success count for each arm.</li><li>betas: Failure count for each arm.</li><li>true_means: Actual mean rewards (hidden from the agent).</li></ul><p><strong>Methods:</strong></p><ul><li>select_arm(): Samples from a Beta distribution for each arm and picks the arm with the highest sample.</li><li>pull(arm): Simulates pulling the selected arm.</li><li>update(arm, reward): Updates the success/failure counts based on the observed reward.</li></ul><p><strong>Iteration:</strong></p><ol><li>Sample from the Beta distribution for each arm.</li><li>Select the arm with the highest sampled value.</li><li>Pull the arm and observe the reward.</li><li>Update the Beta distribution parameters.</li></ol><h3>How Each Strategy Models MAB</h3><ul><li><strong>Epsilon-Greedy:</strong> Directly balances exploration and exploitation through a fixed probability.</li><li><strong>UCB:</strong> Incorporates uncertainty into decision-making, preferring less-explored arms over time.</li><li><strong>Thompson Sampling:</strong> Uses a probabilistic approach to balance exploration and exploitation naturally.</li></ul><p>Each approach iteratively learns the reward distributions, improving arm selection as more data becomes available.</p><h3>Current Research and Breakthroughs</h3><p>Recent advances focus on:</p><ul><li><strong>Contextual Bandits:</strong> Incorporating additional contextual information (e.g., user demographics) into the arm selection process.</li><li><strong>Deep Multi-Armed Bandits:</strong> Leveraging deep learning models to approximate complex reward functions and scale to larger datasets.</li><li><strong>Multi-Agent Bandits:</strong> Studying scenarios where multiple agents interact, collaborate, or compete while solving MAB problems.</li><li><strong>Non-Stationary Bandits:</strong> Developing algorithms that adapt to changing reward distributions over time.</li></ul><h3>Real-World Applications</h3><ul><li><strong>Ad Placement Optimization:</strong> Selecting the best ads to display to users to maximize click-through rates.</li><li><strong>Dynamic Pricing Models:</strong> Adjusting prices in real-time based on market demand and user behavior.</li><li><strong>Clinical Trials for Drug Testing:</strong> Allocating patients to treatments while balancing the need for data and patient outcomes.</li><li><strong>Recommendation Systems:</strong> Personalizing content recommendations to maximize user engagement.</li></ul><h3>Case Study: Google Ads</h3><p>Google uses MAB algorithms to optimize ad placements, balancing exploration of new ads with exploiting high-performing ones. This approach has significantly improved click-through rates and ad revenue.</p><h3>Challenges and Limitations</h3><ul><li><strong>Scalability with Large Action Spaces:</strong> Traditional MAB algorithms struggle when the number of arms becomes very large.</li><li><strong>Non-Stationary Reward Distributions:</strong> Real-world environments often change over time, requiring adaptive algorithms.</li><li><strong>Delayed Feedback:</strong> In many applications (e.g., ad placements), rewards are not immediately observable.</li><li><strong>Ethical Considerations:</strong> Exploration in sensitive domains (like healthcare) must be carefully managed.</li></ul><h3>Future Directions and Open Research Questions</h3><ul><li><strong>Incorporating Deep Reinforcement Learning:</strong> Blending deep learning with MAB frameworks to tackle complex, high-dimensional problems.</li><li><strong>Adapting to Non-Stationary Environments:</strong> Designing algorithms that can detect and adapt to changes in reward distributions.</li><li><strong>Multi-Objective Bandits:</strong> Optimizing for multiple conflicting objectives simultaneously.</li><li><strong>Fairness and Ethics in Exploration:</strong> Ensuring that exploration strategies do not unintentionally harm specific user groups.</li></ul><h3>How MAB Outperforms Traditional Approaches</h3><p>Traditional decision-making approaches often rely on static strategies that fail to adapt to changing environments. In contrast, MAB frameworks continuously learn and adapt, offering dynamic solutions that improve long-term performance. By explicitly addressing the exploration-exploitation trade-off, MAB algorithms outperform many conventional heuristics in uncertain and evolving settings.</p><h3>Resources for Further Learning</h3><h3>Books:</h3><ul><li><em>Reinforcement Learning: An Introduction</em> by Sutton &amp; Barto</li><li><em>Bandit Algorithms</em> by Lattimore &amp; Szepesvári</li></ul><h3>Courses:</h3><ul><li>Coursera: <em>Reinforcement Learning Specialization</em></li><li>edX: <em>Practical Deep Learning for Coders</em></li></ul><h3>Papers:</h3><ul><li>“Finite-time Analysis of the Multiarmed Bandit Problem” — Auer et al.</li><li>“Thompson Sampling for Contextual Bandits” — Chapelle &amp; Li</li><li>“A Survey on Multi-Armed Bandits” — Bubeck &amp; Cesa-Bianchi</li></ul><h3>Online Resources:</h3><ul><li>OpenAI’s Reinforcement Learning Blog</li><li>DeepMind’s Research on Exploration Strategies</li></ul><p><em>This comprehensive guide equips you with both theoretical insights and practical skills to master Multi-Armed Bandits. Dive deeper, experiment, and harness the power of adaptive decision-making algorithms in real-world applications!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d87a0cb2f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Implicit Representations: The Future of Data Compression]]></title>
            <link>https://abhic159.medium.com/neural-implicit-representations-the-future-of-data-compression-9676be3b018f?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9676be3b018f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 14:59:29 GMT</pubDate>
            <atom:updated>2025-02-12T15:00:28.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BAwuk0PFdUXbbaVF" /></figure><h3>Introduction</h3><p>In an era where data generation is exploding, efficient compression methods are crucial for storage, transmission, and real-time processing. Traditional compression algorithms like JPEG, MP3, and H.264 rely on explicit signal transformations, often leading to artifacts and information loss. But what if we could encode data more intelligently — storing it as a continuous function rather than discrete bits? Enter <em>Neural Implicit Representations (NIR)</em>, an emerging paradigm that uses neural networks to represent data in a compact, continuous manner.</p><p>This article dives deep into the mathematics, breakthroughs, applications, challenges, and future directions of neural implicit representations. By the end, you’ll not only grasp why NIR is poised to revolutionize data compression but also gain hands-on insights into implementing these methods.</p><h3>What Are Neural Implicit Representations?</h3><p>Neural implicit representations store data as a function parameterized by a neural network, rather than explicit grid-based formats. This allows for continuous, high-resolution reconstructions with remarkable compression efficiency. A key advantage is that instead of storing pixel or voxel values, we store a neural network that maps spatial coordinates to signal intensities.</p><p>For example, in image compression, instead of storing pixel grids, we train a neural network to learn a mapping from spatial coordinates (x, y) to color values (r, g, b). At inference, the function can generate a high-resolution version of the original image, often outperforming traditional techniques.</p><h3>Core Concepts</h3><ul><li><strong>Coordinate-Based Representations:</strong> Data is stored as a function fθ(x) where x is a coordinate and θ represents neural network parameters.</li><li><strong>Compact Representation:</strong> Instead of storing explicit data points, we store a learned neural network capable of reconstructing the original signal.</li><li><strong>Implicit Nature:</strong> Unlike traditional explicit formats (bitmaps, meshes, etc.), the representation does not rely on a predefined structure but rather learns the best way to encode the data.</li></ul><h3>Mathematical Foundations and Key Equations</h3><p>At the heart of neural implicit representations lies a function approximation problem. Given a dataset D={(xi,yi)} the goal is to learn a neural network fθ that approximates the underlying function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*xr6SHPJe59Sg6Ux-FjeL6Q.png" /></figure><h3>Common Architectures</h3><ol><li><strong>Multilayer Perceptrons (MLPs):</strong> Standard choice, mapping coordinates to outputs via multiple non-linear transformations.</li><li><strong>Siren Networks:</strong> Use periodic activation functions (e.g., sine functions) for better high-frequency representation.</li><li><strong>Fourier Features:</strong> Introduce Fourier embeddings to help MLPs capture fine-grained details.</li></ol><h3>Optimization</h3><p>Training an implicit neural representation involves minimizing the reconstruction error, typically using an L2 loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*4tp3_UODFeJizcTlmoUiOA.png" /></figure><p>Optimization is performed via stochastic gradient descent (SGD) or Adam.</p><h3>Current Research and Breakthroughs</h3><p>Neural implicit representations have gained significant traction across multiple domains:</p><ol><li><strong>Neural Radiance Fields (NeRF):</strong> Revolutionizing 3D scene representation and novel view synthesis.</li><li><strong>DeepSDF:</strong> A method for shape representation using signed distance functions.</li><li><strong>Neural Compression for Images &amp; Videos:</strong> Methods like COIN and NeRV optimize video encoding with neural representations.</li><li><strong>Implicit Neural Audio Representations:</strong> Encoding high-fidelity audio signals efficiently.</li></ol><p>Recent research has demonstrated that implicit neural representations can outperform conventional methods in terms of both compression and quality.</p><h3>Real-World Applications and Case Studies</h3><h3>Image Compression</h3><ul><li>Researchers at Google have explored neural representations to replace JPEG and PNG.</li><li>Implicit networks achieve better compression rates while avoiding block artifacts.</li></ul><h3>3D Object Storage</h3><ul><li>CAD models and 3D scans can be stored as compact neural networks, reducing storage requirements while enabling high-fidelity reconstructions.</li></ul><h3>Video Compression</h3><ul><li>Instead of storing frames explicitly, a neural function maps time tt to frame content, drastically reducing data size.</li></ul><h3>Scientific Simulations</h3><ul><li>Neural implicit representations enable efficient storage of physics simulations, reducing terabytes of data into a small neural network.</li></ul><h3>Challenges and Limitations</h3><p>While promising, neural implicit representations come with challenges:</p><ol><li><strong>Training Time:</strong> Encoding data into a neural representation requires significant computation.</li><li><strong>Inference Speed:</strong> Decoding may be slower compared to traditional lookup-based methods.</li><li><strong>Generalization:</strong> Models trained on one dataset may not generalize well to unseen data.</li><li><strong>Hardware Constraints:</strong> High-quality reconstructions may demand powerful GPUs.</li></ol><h3>Future Directions and Open Research Questions</h3><ol><li><strong>Hybrid Approaches:</strong> Can we combine explicit and implicit representations for better efficiency?</li><li><strong>Faster Training Methods:</strong> How can we reduce training times while maintaining high-quality encoding?</li><li><strong>Hardware Acceleration:</strong> How can specialized chips (e.g., TPUs) speed up inference?</li><li><strong>Lossless Compression:</strong> Can we design lossless versions of neural representations?</li></ol><h3>Hands-on Implementation Example</h3><p>Here’s a simple Python snippet for representing an image with an MLP:</p><pre>import torch<br>import torch.nn as nn<br><br>class ImplicitImageMLP(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.mlp = nn.Sequential(<br>            nn.Linear(2, 256),<br>            nn.ReLU(),<br>            nn.Linear(256, 256),<br>            nn.ReLU(),<br>            nn.Linear(256, 3),<br>            nn.Sigmoid()<br>        )<br>    <br>    def forward(self, coords):<br>        return self.mlp(coords)<br># Generate a coordinate grid and train on an image</pre><p>This is just a starting point — you can explore more sophisticated architectures like SIREN or Fourier-feature MLPs.</p><h3>Resources for Further Learning</h3><h3>Research Papers</h3><ul><li><strong>NeRF:</strong> “NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis” (Mildenhall et al., 2020)</li><li><strong>DeepSDF:</strong> “DeepSDF: Learning Continuous Signed Distance Functions for Shape Representation” (Park et al., 2019)</li><li><strong>Neural Image Compression:</strong> “Learning-Based Image Compression with Implicit Representations” (Dupont et al., 2021)</li></ul><h3>Courses &amp; Tutorials</h3><ul><li>Stanford CS231N (Deep Learning for Computer Vision)</li><li>MIT 6.S191 (Introduction to Deep Learning)</li><li>FastAI’s Deep Learning Course</li></ul><h3>Conclusion</h3><p>Neural implicit representations are a paradigm shift in data compression, offering high-quality, compact, and continuous data representations. While challenges remain, ongoing research is pushing the boundaries of what’s possible. As hardware advances and training techniques improve, neural compression could become the standard for images, videos, 3D objects, and beyond.</p><p>Are we looking at the future of data storage? The answer seems to be a resounding <em>yes</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9676be3b018f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero-Shot Learning with Large Language Models: Pushing the Limits]]></title>
            <link>https://abhic159.medium.com/zero-shot-learning-with-large-language-models-pushing-the-limits-3371b1e54c10?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3371b1e54c10</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 15:24:21 GMT</pubDate>
            <atom:updated>2025-02-10T15:24:21.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o_Rih9T3M3_cUpHv" /></figure><h3>Introduction</h3><p>Imagine a model that can translate languages it has never seen, classify unseen images, or answer domain-specific questions without explicit training. Welcome to the world of <strong>Zero-Shot Learning (ZSL)</strong> — a paradigm that challenges the traditional supervised learning approach by enabling models to generalize beyond their training data. With the rise of <strong>Large Language Models (LLMs)</strong> like GPT-4, PaLM, and LLaMA, ZSL has reached unprecedented levels, redefining what machines can do with minimal human intervention.</p><p>In this deep dive, we will explore how ZSL works, the mathematical principles underpinning it, recent breakthroughs, real-world applications, and the challenges that still remain. By the end, you’ll have a comprehensive understanding of how LLMs push the limits of Zero-Shot Learning and how you can leverage them effectively.</p><h3>What is Zero-Shot Learning?</h3><p><strong>Zero-Shot Learning (ZSL)</strong> refers to a machine learning technique where a model is able to make accurate predictions for tasks it has never seen during training. Unlike traditional models that require labeled examples for every class, ZSL relies on knowledge transfer via high-dimensional embeddings, prompt engineering, and external knowledge sources.</p><h3>How LLMs Enable ZSL</h3><p>Large Language Models (LLMs) make ZSL possible by leveraging <strong>self-supervised pretraining on massive corpora</strong>. These models learn a dense representation of the world’s knowledge, allowing them to:</p><ul><li>Perform <strong>classification</strong> without explicit labels</li><li><strong>Translate</strong> between languages without paired data</li><li><strong>Answer domain-specific questions</strong> using only prompts</li><li>Generate code, poetry, or creative writing without prior examples</li></ul><p>The magic of ZSL in LLMs lies in their ability to <strong>generalize through contextual inference</strong>, treating prompts as implicit training data.</p><h3>Mathematical Foundations of Zero-Shot Learning</h3><p>At its core, ZSL relies on <strong>semantic embedding spaces</strong> and <strong>distributional representations</strong>. Let’s break down some key mathematical concepts:</p><h3>1. Embedding Space Representation</h3><p>Given a dataset of labeled examples X={x1,x2,…,xn} and their corresponding labels Y={y1,y2,…,yn}, ZSL models aim to learn a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*Hz5aEr0RZqyekMFCCZ0ZOw.png" /></figure><p>where EY is an embedding space capturing semantic relationships among labels. In the case of LLMs, this embedding space is often a <strong>pretrained transformer latent space</strong>.</p><h3>2. Cosine Similarity for Unseen Classes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JCVQgIgslfUjEZOZ4MrfA.png" /></figure><h3>3. Bayesian Inference in ZSL</h3><p>Some ZSL approaches leverage <strong>Bayesian inference</strong> to estimate the probability of a new label given an input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ctgiMlVu_DwUqpq3zUxVJw.png" /></figure><p>where P(y_new) is the prior probability of the unseen label, inferred from external knowledge sources.</p><h3>Cutting-Edge Research and Breakthroughs</h3><p>Several recent advancements have propelled ZSL with LLMs to new heights:</p><ul><li><strong>Prompt Engineering &amp; Few-Shot Learning (GPT-4, PaLM)</strong>: Carefully crafted prompts allow models to infer tasks without fine-tuning.</li><li><strong>Contrastive Learning (CLIP, ALIGN)</strong>: Aligns text and image embeddings for cross-modal generalization.</li><li><strong>Meta-Learning for ZSL</strong>: Adaptive methods that train models to generalize better across unseen tasks.</li><li><strong>Chain-of-Thought (CoT) Reasoning</strong>: Improves logical reasoning in zero-shot settings.</li></ul><h3>Real-World Applications</h3><ol><li><strong>Automated Customer Support</strong>: LLMs can answer queries without specific training in a domain.</li><li><strong>Medical Diagnosis</strong>: AI models provide preliminary diagnoses based on descriptions rather than explicit training on specific cases.</li><li><strong>Cross-Lingual NLP</strong>: Google Translate and DeepL use ZSL to support rare languages.</li><li><strong>Legal and Financial Document Analysis</strong>: Extracting insights without labeled datasets.</li><li><strong>Scientific Research</strong>: Assisting in hypothesis generation in unexplored fields.</li></ol><h3>Challenges and Limitations</h3><p>Despite its impressive capabilities, ZSL with LLMs faces several hurdles:</p><ul><li><strong>Bias and Hallucinations</strong>: LLMs can generate misleading or incorrect outputs.</li><li><strong>Lack of Explainability</strong>: Understanding how a model reaches a conclusion remains difficult.</li><li><strong>Domain Adaptation Issues</strong>: Performance drops significantly in highly specialized fields.</li><li><strong>Computational Costs</strong>: Running large models is expensive and resource-intensive.</li></ul><h3>Future Directions &amp; Open Research Questions</h3><ol><li><strong>Can we make ZSL more robust against adversarial attacks?</strong></li><li><strong>How can we improve reasoning abilities in zero-shot scenarios?</strong></li><li><strong>Can we reduce model size while maintaining ZSL capabilities?</strong></li><li><strong>How can ZSL models integrate real-time updates without retraining?</strong></li><li><strong>What role will multimodal ZSL play in the next generation of AI?</strong></li></ol><h3>Hands-On Implementation: Zero-Shot Classification with GPT-4</h3><p>To see ZSL in action, let’s implement a <strong>Zero-Shot Text Classifier</strong> using OpenAI’s API:</p><pre>import openai<br><br>def zero_shot_classification(prompt, labels):<br>    response = openai.ChatCompletion.create(<br>        model=&quot;gpt-4&quot;,<br>        messages=[{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>                  {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Classify the following text: &#39;{prompt}&#39;. Choices: {&#39;, &#39;.join(labels)}&quot;}],<br>        temperature=0.2<br>    )<br>    return response[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]<br><br>text = &quot;The stock market crashed due to economic instability.&quot;<br><br>labels = [&quot;Finance&quot;, &quot;Politics&quot;, &quot;Sports&quot;]<br><br>print(zero_shot_classification(text, labels))</pre><p>This simple script demonstrates how LLMs perform ZSL classification without fine-tuning.</p><h3>Further Learning Resources</h3><ul><li><strong>Papers</strong>: “Language Models are Few-Shot Learners” (Brown et al., 2020), “CLIP: Connecting Text and Images” (Radford et al., 2021)</li><li><strong>Books</strong>: “Deep Learning for NLP” by Sebastian Ruder</li><li><strong>Courses</strong>: Stanford’s CS224N, Hugging Face NLP Courses</li></ul><h3>Conclusion</h3><p>Zero-Shot Learning with Large Language Models is redefining AI’s capabilities, allowing models to perform complex tasks without explicit training. While challenges remain, advancements in multimodal learning, contrastive pretraining, and self-supervised learning will continue pushing the boundaries. Whether you’re a researcher, engineer, or enthusiast, embracing ZSL will be key to unlocking the next wave of AI-driven innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3371b1e54c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Poisson Regression: The Ultimate Guide to Modeling Count Data Like a Pro]]></title>
            <link>https://abhic159.medium.com/poisson-regression-the-ultimate-guide-to-modeling-count-data-like-a-pro-1a746276619d?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a746276619d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 14:06:33 GMT</pubDate>
            <atom:updated>2025-02-09T14:07:54.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BDwsezAi9Hgun95u" /></figure><h3>Introduction</h3><p>Imagine you are a data scientist at a hospital, and you need to predict the number of patients arriving at the emergency room every hour. Or perhaps, you are analyzing how many cars pass through a toll booth in a given period. These scenarios involve modeling <strong>count data</strong>, where the response variable represents the number of occurrences of an event within a fixed period or space.</p><p>This is where <strong>Poisson Regression</strong> comes into play. Unlike standard linear regression, which assumes continuous response variables, Poisson regression is tailored for count data, ensuring a more accurate and meaningful analysis.</p><p>In this article, we will dive deep into:</p><ul><li><strong>Poisson Distribution</strong> and how it differs from the Normal Distribution.</li><li><strong>Understanding Poisson Regression</strong> and its mathematical foundation.</li><li><strong>Comparison with Ordinary Least Squares (OLS) Regression</strong>.</li><li><strong>The canonical form of Poisson Regression</strong>.</li><li><strong>Step-by-step implementation in Python with an example</strong>.</li><li><strong>Key assumptions of Poisson Regression</strong>.</li></ul><p>By the end of this blog, you’ll have mastered Poisson Regression and be able to implement it in real-world applications effortlessly!</p><h3>What is the Poisson Distribution?</h3><p>The <strong>Poisson distribution</strong> is a probability distribution that models the probability of a given number of events occurring within a fixed interval of time or space, assuming that these events happen independently and at a constant rate.</p><h3>Poisson Distribution Formula</h3><p>The probability mass function (PMF) of a Poisson-distributed random variable is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*4gFGKQwe-8Ce6XZoH23Viw.png" /></figure><p>where:</p><ul><li>k is the number of occurrences (count of events).</li><li>λ is the expected number of occurrences within the given interval.</li><li>e is the base of the natural logarithm (~2.718).</li></ul><p>The Poisson distribution is often used to model rare events, such as the number of earthquakes in a year, customer arrivals at a store, or phone call arrivals at a call center.</p><h3>Poisson vs. Normal Distribution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzA1dH3RK8E9JV65o8JtSQ.png" /></figure><h3>What is Poisson Regression?</h3><p><strong>Poisson regression</strong> is a type of <strong>Generalized Linear Model (GLM)</strong> used when the dependent variable (Y) represents <strong>count data</strong>. Instead of modeling Y directly, Poisson regression models the <strong>log of the expected count</strong> as a linear function of explanatory variables.</p><h3>Mathematical Formulation</h3><p>In Poisson regression, we assume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*n12n5jAEBzfoVqwpfdfYzQ.png" /></figure><p>where:</p><ul><li>Y is the count variable (dependent variable).</li><li>X1,X2,…,Xn are predictor variables (independent variables).</li><li>β0,β1,…,βn are the regression coefficients.</li></ul><p>Taking the natural logarithm of both sides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*WTpEtCxAPpkpCoWsBR_NBg.png" /></figure><p>This transformation ensures that the predicted counts remain non-negative.</p><h3>How is Poisson Regression Different from OLS Regression?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcCqJXfaVVEISioQTjRIbQ.png" /></figure><h3>Canonical Form of Poisson Regression</h3><p>Poisson regression is a <strong>GLM</strong> with a <strong>log-link function</strong> and follows the Poisson distribution. The canonical link function for Poisson regression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*Bsnxj41cLiPcXy7a5_Hnsg.png" /></figure><p>where θ is the linear predictor.</p><h3>Implementation of Poisson Regression in Python</h3><h3>Step 1: Importing Libraries</h3><pre>import numpy as np<br>import pandas as pd<br>import statsmodels.api as sm<br>import statsmodels.formula.api as smf</pre><h3>Step 2: Creating Sample Data</h3><pre># Creating a dataset<br>np.random.seed(42)<br>data = pd.DataFrame({<br>    &#39;X1&#39;: np.random.poisson(lam=3, size=100),  # Independent Variable 1<br>    &#39;X2&#39;: np.random.normal(loc=5, scale=2, size=100),  # Independent Variable 2<br>    &#39;Y&#39;: np.random.poisson(lam=5, size=100)   # Dependent Variable (Counts)<br>})</pre><h3>Step 3: Fitting a Poisson Regression Model</h3><pre># Fit the Poisson regression model<br>model = smf.poisson(&#39;Y ~ X1 + X2&#39;, data=data).fit()<br>print(model.summary())</pre><h3>Step 4: Making Predictions</h3><pre># Predict counts for new data<br>new_data = pd.DataFrame({&#39;X1&#39;: [2, 4, 6], &#39;X2&#39;: [5, 6, 7]})<br>predictions = model.predict(new_data)<br>print(predictions)</pre><h3>Key Assumptions of Poisson Regression</h3><ol><li><strong>Count Data Assumption:</strong> The dependent variable must represent count data (0,1,2,3, …).</li><li><strong>Independence of Observations:</strong> The occurrences of events must be independent.</li><li><strong>Mean-Variance Equality:</strong> The mean and variance of the response variable should be approximately equal (overdispersion can be handled using negative binomial regression).</li><li><strong>Log-Linearity:</strong> The relationship between predictors and the log of the expected count should be linear.</li></ol><h3>Conclusion</h3><p>Poisson regression is a powerful tool for modeling count data, widely used in healthcare, finance, marketing, and social sciences. By understanding its theoretical foundation and implementation, you can unlock valuable insights in real-world datasets. Now, it’s your turn to apply Poisson regression to your own projects and analyze count-based phenomena like a pro!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a746276619d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Real-World Problems with Machine Learning: A Deep Dive]]></title>
            <link>https://abhic159.medium.com/solving-real-world-problems-with-machine-learning-a-deep-dive-095e1c96631b?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/095e1c96631b</guid>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlb]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 09:29:32 GMT</pubDate>
            <atom:updated>2025-01-25T09:29:32.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHeg_2-BENqvqx0dW4PXGQ.jpeg" /></figure><h3>Introduction</h3><h3>The Challenge: Predicting Customer Churn in Subscription Services</h3><p>Customer churn — the rate at which customers stop using a service — is a major concern for subscription-based businesses like streaming platforms, SaaS products, and online retailers. High churn rates mean lost revenue and increased marketing costs to acquire new customers. Traditional retention strategies struggle to pinpoint exactly <strong>who will churn and why</strong>.</p><p>This is where <strong>Machine Learning (ML)</strong> comes into play. By leveraging ML models, companies can predict churn, understand underlying patterns, and take proactive steps to retain customers.</p><p>In this post, we will:</p><ul><li>Analyze churn prediction as a real-world ML problem</li><li>Explore different ML techniques suited for churn prediction</li><li>Implement an end-to-end ML pipeline using Python</li><li>Discuss advanced topics like <strong>LSTMs, Explainable AI (XAI), and hyperparameter tuning</strong></li></ul><p>Let’s get started! 🚀</p><h3>Problem Analysis &amp; Challenges</h3><h3>Traditional Approaches &amp; Limitations</h3><p>Conventional customer retention strategies rely on:</p><ul><li><strong>Manual segmentation</strong>: Identifying high-risk customers using static rules.</li><li><strong>Survey-based insights</strong>: Collecting feedback post-cancellation.</li><li><strong>Generic offers</strong>: Providing discounts/promotions to all users indiscriminately.</li></ul><p><strong>Why do these fail?</strong></p><ol><li><strong>Static rules don’t scale</strong>: Different customers churn for different reasons.</li><li><strong>Delayed insights</strong>: By the time surveys are analyzed, customers have already left.</li><li><strong>Inefficient resource allocation</strong>: Businesses waste discounts on users who wouldn’t have churned anyway.</li></ol><h3>How ML Solves This Problem</h3><ul><li><strong>Predictive modeling</strong> identifies at-risk customers before they churn.</li><li><strong>Personalized retention strategies</strong> based on ML insights.</li><li><strong>Real-time alerts</strong> help businesses take immediate action.</li></ul><p>Let’s now explore the ML techniques best suited for this problem. 🔍</p><h3>ML Techniques &amp; Solutions</h3><h3>1. Supervised Learning (Classification Models)</h3><p>Since we have historical customer data labeled as <strong>churned</strong> or <strong>retained</strong>, we can train classification models such as:</p><ul><li><strong>Logistic Regression</strong> — A baseline model for churn prediction.</li><li><strong>Random Forest &amp; XGBoost</strong> — More robust models that handle non-linearity well.</li><li><strong>Neural Networks (LSTMs)</strong> — Ideal for sequential user behavior data.</li></ul><h3>2. Unsupervised Learning (Anomaly Detection)</h3><p>When labeled churn data is scarce, anomaly detection techniques like <strong>Autoencoders</strong> and <strong>Isolation Forest</strong> can identify users whose behaviors deviate from normal patterns.</p><h3>3. Reinforcement Learning for Dynamic Retention Strategies</h3><p>Using Reinforcement Learning (RL), businesses can:</p><ul><li>Optimize personalized discounts.</li><li>Maximize long-term user retention.</li><li>Continuously improve retention policies based on customer responses.</li></ul><h3>Hands-on Code Implementation: Customer Churn Prediction</h3><h3>Step 1: Import Libraries &amp; Load Data</h3><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report</pre><pre># Load dataset (Example: Subscription Churn Data)<br>df = pd.read_csv(&quot;customer_churn.csv&quot;)<br>df.head()</pre><h3>Step 2: Data Preprocessing &amp; Feature Engineering</h3><pre># Handling missing values<br>df.fillna(df.median(), inplace=True)</pre><pre># Feature Engineering: Extracting useful patterns<br>df[&#39;TotalUsage&#39;] = df[&#39;MonthlyUsage&#39;] * df[&#39;SubscriptionLength&#39;]<br>df[&#39;AvgSupportTickets&#39;] = df[&#39;SupportTickets&#39;] / df[&#39;SubscriptionLength&#39;]</pre><h3>Step 3: Train-Test Split &amp; Model Training</h3><pre>X = df.drop([&#39;Churn&#39;], axis=1)<br>y = df[&#39;Churn&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><pre># Train Random Forest Model<br>model = RandomForestClassifier(n_estimators=200, max_depth=10, random_state=42)<br>model.fit(X_train, y_train)</pre><h3>Step 4: Model Evaluation</h3><pre>y_pred = model.predict(X_test)<br>print(confusion_matrix(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><h3>Advanced Topics: Enhancing Churn Prediction</h3><h3>LSTMs for Sequential User Behavior Analysis</h3><p>Churn is often based on a series of events (e.g., decreasing engagement over time). <strong>LSTMs (Long Short-Term Memory networks)</strong> capture these trends better.</p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import LSTM, Dense, Dropout</pre><pre>X_train_reshaped = np.reshape(X_train.values, (X_train.shape[0], X_train.shape[1], 1))<br>X_test_reshaped = np.reshape(X_test.values, (X_test.shape[0], X_test.shape[1], 1))</pre><pre>model = Sequential([<br>    LSTM(128, input_shape=(X_train.shape[1], 1), activation=&#39;relu&#39;, return_sequences=True),<br>    Dropout(0.2),<br>    LSTM(64, activation=&#39;relu&#39;),<br>    Dropout(0.2),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(X_train_reshaped, y_train, epochs=10, batch_size=64, validation_data=(X_test_reshaped, y_test))</pre><h3>Explainable AI (XAI): Understanding Model Decisions</h3><p>Instead of treating ML as a black box, we can use <strong>SHAP (SHapley Additive exPlanations)</strong> to interpret predictions.</p><pre>import shap<br>explainer = shap.TreeExplainer(model)<br>shap_values = explainer.shap_values(X_test)<br>shap.summary_plot(shap_values, X_test)</pre><h3>Conclusion &amp; Future Trends</h3><h3>Key Takeaways</h3><p>✅ Machine Learning enables predictive customer churn models.</p><p>✅ Advanced techniques like <strong>LSTMs &amp; Explainable AI</strong> improve model transparency.</p><p>✅ Businesses can <strong>personalize retention strategies</strong> using ML insights.</p><h3>What’s Next?</h3><ol><li><strong>Hyperparameter tuning</strong> to improve prediction accuracy.</li><li><strong>Deploying the model as an API</strong> for real-time churn prediction.</li><li><strong>Federated Learning</strong> to enhance security and privacy.</li></ol><p><strong>Want to try it out?</strong> 🚀 Download the dataset and build your own ML churn prediction model! Let me know your results in the comments.</p><p><strong>Keywords</strong>: Machine Learning, Churn Prediction, Customer Retention, AI, LSTMs, Explainable AI, Data Science.</p><p>Let’s revolutionize retention strategies with ML! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=095e1c96631b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Causality: A Deep Dive into Causal Inference for Business Analytics]]></title>
            <link>https://abhic159.medium.com/unveiling-causality-a-deep-dive-into-causal-inference-for-business-analytics-a1668615bf63?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1668615bf63</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[correlation]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 05:09:38 GMT</pubDate>
            <atom:updated>2024-03-10T05:09:38.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mk7CxeR0xLpjITD9" /></figure><p>In the realm of business analytics, correlation reigns supreme. Yet, correlation often leaves a crucial question unanswered: does one variable truly cause a change in another?</p><p>This is where causal inference steps in, offering a sophisticated framework for establishing cause-and-effect relationships from observational data, a cornerstone of most business datasets.</p><p>We will learn the following things in this (not so) medium article:</p><ol><li>Delving into Causal Inference</li><li>Detecting Causal Inference Issues</li><li>Advanced Detection Techniques</li><li>Formalizing Cofounding Effect</li><li>Mitigating Challenges</li><li>Conclusion</li></ol><h3>Delving into Causal Inference</h3><p>Causal inference transcends mere correlation by estimating the <strong><em>Treatment Effect on the Treated (ATT)</em></strong>, the average causal impact of a treatment (e.g., marketing campaign) on the outcome (e.g., sales) for those who actually received it. This is achieved through counterfactual reasoning: what would the outcome have been for the treated group had they not received the treatment?</p><p>However, observational data often lacks the luxury of <strong><em>randomized controlled trials (RCTs)</em></strong>, the gold standard for causal inference. Here, the <a href="https://link.springer.com/chapter/10.1057/9780230280816_28"><strong><em>Rubin Causal Model (RCM)</em></strong></a> provides a robust foundation. The RCM posits three key conditions for causal identification:</p><p>1. Stable Unit-Treatment Value Assumption (SUTVA): The treatment effect for a unit is constant regardless of the treatment assignment of other units.</p><p>2. Strong Ignorability: Treatment assignment is independent of the potential outcomes (both treated and untreated) conditional on a set of observed covariates.</p><p>3. Positivity: There is a non-zero probability of receiving the treatment for each unit in the population.</p><h3>Identifying Challenges: The Pitfalls of Untreated Causal Inference</h3><p>Ignoring causal inference issues leads to biased estimates of treatment effects. Here’s a closer look at common pitfalls:</p><ol><li>Selection Bias: Systematic differences between the treatment and control groups can distort the causal effect. Imagine comparing website traffic for users exposed to a new ad campaign (treatment) versus those who weren’t (control). Pre-existing user behavior, not the campaign itself, might drive the observed difference.</li><li>Confounding Variables: These lurk in the background, influencing both the treatment and the outcome. For instance, in our marketing example, user demographics could confound the relationship between the campaign and sales.</li><li>Reverse Causality: Sometimes, the observed association might be reversed. Perhaps users with a higher propensity to purchase were more likely to be targeted by the ad campaign, not the other way around.</li></ol><h3>Detecting Causal Inference Issues</h3><p>In the absence of RCTs, observational data analysis for causal inference requires careful scrutiny to identify potential biases. Here’s a technical breakdown of common pitfalls and detection methods:</p><ul><li>Selection Bias: This bias arises when the treatment and control groups are not representative of the target population due to non-random selection processes.</li></ul><p>Detection: We can compare the pre-treatment characteristics of the treatment and control groups using statistical tests (e.g., t-tests, chi-squared tests) or visualization techniques (e.g., histograms, box plots) to identify significant differences.</p><ul><li>Confounding Variables: These are lurking variables that influence both the treatment and the outcome, distorting the true causal effect.</li></ul><p>Detection: Domain knowledge plays a crucial role in identifying potential confounders. Statistical techniques like directed acyclic graphs (DAGs) can be used to visualize the causal relationships between variables and pinpoint potential confounders based on their position in the graph. Additionally, examining the correlation between the confounder and both the treatment and outcome can provide clues.</p><h3>Advanced Detection Techniques:</h3><ol><li>Propensity Score Analysis: This technique estimates the probability of receiving the treatment for each unit in the observational data. Examining the balance of covariates between the treatment and control groups within propensity score strata can reveal selection bias.</li></ol><h3>Formalizing Confounding: The Role of the Rubin Causal Model</h3><blockquote>The Rubin Causal Model (RCM) provides a theoretical framework to assess confounding. For causal identification, the RCM relies on the concept of counterfactuals: the outcomes for each unit under both treatment and no-treatment conditions.</blockquote><p><em>A key assumption for causal identification in the RCM is strong ignorability.</em> This essentially states that treatment assignment is independent of the potential outcomes (both treated and untreated) conditional on a set of observed covariates (X). In simpler terms, if we know everything about a unit captured by X, then the decision to treat that unit should not be related to its potential outcomes.</p><p>However, even after controlling for observed confounders, unobserved confounders can still bias the causal effect estimate. Techniques like <strong><em>instrumental variables (IV)</em></strong> can be used in such scenarios, but they require strong assumptions about the IV itself.</p><h3>Mitigating Challenges: Techniques for Robust Causal Inference</h3><p>Several statistical techniques can address these challenges:</p><ul><li>Matching Methods: Pair units in the treatment and control groups based on their propensity to receive the treatment, creating comparable groups for analysis.</li><li>Propensity Score Matching (PSM): This technique addresses selection bias by estimating the probability (propensity score) of receiving the treatment for each observation in the data. Units in the treatment and control groups are then matched based on their propensity scores, creating comparable groups for analysis.</li><li>Instrumental Variables (IV): When strong ignorability is violated due to unobserved confounders, IVs can be used. An instrumental variable is a variable that influences treatment assignment but does not directly affect the outcome. By leveraging the relationship between the IV, treatment assignment, and the outcome, IV techniques can estimate causal effects. However, finding valid IVs that meet the necessary assumptions can be challenging.</li></ul><h3>Advanced Methods: In complex scenarios, even more robust techniques can be employed:</h3><ol><li>Difference-in-Differences (DID): This approach exploits pre-treatment data to estimate the counterfactual outcome for the treatment group. It compares the change in the outcome for the treatment group relative to the control group before and after the treatment was implemented.</li><li>Synthetic Control Methods: This technique constructs a synthetic control group that best resembles the treated group based on pre-treatment characteristics. The difference in outcomes between the treated group and the synthetic control group is then used to estimate the causal effect.</li></ol><h3>Conclusion</h3><p>Detecting confounding variables and selection bias is an iterative process that leverages domain knowledge, statistical tests, and visualization techniques. By employing these methods within the framework of the RCM, business analysts can enhance the credibility of causal inference studies and extract more reliable insights from observational data. This empowers them to make data-driven decisions with greater confidence, ultimately propelling strategic growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1668615bf63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generalized Linear Models (GLMs)]]></title>
            <link>https://abhic159.medium.com/generalized-linear-models-glms-7b6e6c475d82?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6e6c475d82</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 04:28:23 GMT</pubDate>
            <atom:updated>2023-03-25T05:23:16.107Z</atom:updated>
            <content:encoded><![CDATA[<p>Using GLMs for regression analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zrLEQXW0QVXMX7tL6eK4hg.jpeg" /></figure><p>Generalized Linear Models (GLMs) are a powerful family of statistical models that can handle a wide range of data types and response variables. GLMs are an extension of the linear regression model and are used when the response variable is not normally distributed or has a non-linear relationship with the predictor variables. In this article, we will discuss the basics of GLMs and provide sample code in R to help you get started with GLMs.</p><h3>The Basics of GLMs</h3><p>GLMs are a flexible and robust modeling framework that allows us to model a wide range of response variables. The key idea behind GLMs is to model the response variable as a function of a linear predictor that is transformed by a link function. The link function is used to transform the linear predictor to ensure that the response variable is non-negative and has the correct distributional properties.</p><p>The general form of a GLM can be expressed as:</p><blockquote><strong>Y ~ f(µ) = g⁻¹(η)</strong></blockquote><p>where Y is the response variable, f(µ) is the distribution of Y, µ is the mean of Y, g is the link function, and η is the linear predictor. In other words, GLMs assume that the response variable Y has a probability distribution that is a member of the exponential family of distributions. The exponential family of distributions includes many common probability distributions, such as the normal, binomial, Poisson, and gamma distributions.</p><p>The linear predictor η is a linear combination of the predictor variables X, and is expressed as:</p><blockquote><strong>η = β₀ + β₁X₁ + β₂X₂ + … + βₚXₚ</strong></blockquote><p>where β₀ is the intercept, β₁, β₂, …, βₚ are the coefficients for the predictor variables, and X₁, X₂, …, Xₚ are the predictor variables.</p><p>The link function g is used to transform the linear predictor η to ensure that the response variable Y has the correct distributional properties.</p><blockquote>The choice of link function depends on the distribution of the response variable. For example, the logit link function is used for binary response variables, the identity link function is used for continuous response variables, and the log link function is used for count response variables.</blockquote><p>We will discuss some common link functions and their use cases.</p><ol><li><strong><em>Identity Link Function: </em></strong><br>The identity link function is the simplest link function, which is used for linear regression models. The identity link function is appropriate when the response variable is continuous and normally distributed. The formula for the identity link function is:<br>η = μ<br>where η is the linear predictor and μ is the mean of the response variable. The identity link function does not transform the response variable, and the estimated coefficients in the GLM can be directly interpreted as the change in the response variable for a one-unit increase in the corresponding predictor variable.</li><li><strong><em>Logit Link Function: </em></strong><br>The logit link function is commonly used in GLMs for binary response variables (e.g., presence or absence of a disease, success or failure of an event). The logit link function transforms the response variable into the log odds of the event occurring. The formula for the logit link function is:<br>η = log[μ / (1 — μ)]<br>where η is the linear predictor and μ is the probability of the event occurring. The estimated coefficients in the GLM can be interpreted as the change in the log odds of the event occurring for a one-unit increase in the corresponding predictor variable.</li><li><strong><em>Probit Link Function: </em></strong><br>The probit link function is another commonly used link function for binary response variables. The probit link function transforms the response variable into the standard normal distribution. The formula for the probit link function is:<br>η = Φ^-1(μ)<br>where Φ^-1 is the inverse of the cumulative distribution function of the standard normal distribution, and μ is the probability of the event occurring. The estimated coefficients in the GLM can be interpreted as the change in the z-score of the standard normal distribution for a one-unit increase in the corresponding predictor variable.</li><li><strong><em>Log Link Function:</em></strong><br>The log link function is used for GLMs with response variables that have a positive skew, such as count data or proportion data. The log link function transforms the response variable into the natural logarithm of the mean. The formula for the log link function is:<br>η = log(μ)<br>where η is the linear predictor and μ is the mean of the response variable. The estimated coefficients in the GLM can be interpreted as the percent change in the mean of the response variable for a one-unit increase in the corresponding predictor variable.</li><li><strong><em>Inverse Link Function: </em></strong><br>The inverse link function is used for GLMs with response variables that are continuous and have a positive skew. The inverse link function transforms the response variable into the reciprocal of the mean. The formula for the inverse link function is:<br>η = 1 / μ<br>where η is the linear predictor and μ is the mean of the response variable. The estimated coefficients in the GLM can be interpreted as the percent change in the reciprocal of the mean of the response variable for a one-unit increase in the corresponding predictor variable.</li></ol><blockquote>In summary, the choice of link function in GLMs depends on the distribution of the response variable and the research question of interest. Each link function transforms the response variable in a different way, and the estimated coefficients in the GLM can be interpreted differently depending on the link function used. It is important to select the appropriate link function for the research question and to interpret the estimated coefficients in the context of the link function used.</blockquote><h3>Assumptions of GLM</h3><p>Similar to Linear Regression Model, there are some basic assumptions for Generalized Linear Models as well. Most of the assumptions are similar to Linear Regression models, while some of the assumptions of Linear Regression are modified.</p><ul><li>Data should be independent and random (Each Random variable has the same probability distribution).</li><li>The response variable y<em> </em>does not need to be normally distributed, but the distribution is from an exponential family (e.g. binomial, Poisson, multinomial, normal)</li><li>The original response variable need not have a linear relationship with the independent variables, but the transformed response variable (through the link function) is linearly dependent on the independent variables</li></ul><h3>Sample Code in R</h3><p>Now let’s look at some sample code in R to fit GLMs. For this example, we will use the built-in “mtcars” dataset, which contains data on various characteristics of 32 automobiles, such as miles per gallon (mpg), horsepower (hp), and number of cylinders (cyl). Our goal is to fit a GLM to predict the binary variable “am”, which indicates whether the car has an automatic transmission (0) or a manual transmission (1) based on the other variables.</p><p>First, we will load the dataset and split it into training and testing sets:</p><pre>library(dplyr)<br>library(caret)<br><br># Load the mtcars dataset<br>data(mtcars)<br><br># Split the data into training and testing sets<br>set.seed(123)<br>train.index &lt;- createDataPartition(mtcars$am, p = 0.7, list = FALSE)<br>train.data &lt;- mtcars[train.index, ]<br>test.data &lt;- mtcars[-train.index, ]</pre><p>Next, we will fit a GLM using the “glm” function in R. We will use the logit link function, since our response variable is binary. We will include all of the other variables in the model as predictors:</p><pre># Fit a GLM to predict the am variable<br>model.glm &lt;- glm(am ~ ., data = train.data, family = binomial(link = &quot;logit&quot;))<br>summary(model.glm)<br># Print the coefficients<br>coef(model.glm)</pre><p>The output of the “summary” function provides information about the coefficients</p><p>The “coef” function returns a vector of the estimated coefficients.</p><h3>Interpreting the Coefficients in GLMs</h3><p>The interpretation of the coefficients in GLMs is closely related to the link function used in the model. The link function specifies the relationship between the linear predictor η (the sum of the products of the predictor variables and their corresponding coefficients) and the expected value of the response variable μ. In our previous example, we used the logit link function, which is defined as:</p><blockquote><strong><em>logit(μ) = η = β₀ + β₁x₁ + … + βₚxₚ</em></strong></blockquote><p>where logit(μ) is the natural logarithm of the odds ratio of the response variable being a success (in our case, having a manual transmission), given the predictor variables. The coefficients β₁, β₂, …, βₚ represent the change in the log odds of the response variable for a one-unit increase in the corresponding predictor variable, while holding all other predictor variables constant.</p><p>To interpret the coefficients in the GLM, we can exponentiate them to get the odds ratio. For example, <strong>if the coefficient for “hp” is 0.035, the odds ratio for “hp” is:</strong></p><p><strong>odds ratio for hp = exp(0.035) = 1.036</strong></p><blockquote><strong>This means that for a one-unit increase in “hp”, the odds of having a manual transmission (am=1) increase by a factor of 1.036, while holding all other variables constant.</strong></blockquote><p>The sign of the coefficient also gives us information about the direction of the relationship between the predictor variable and the response variable. If the coefficient is positive, an increase in the predictor variable is associated with an increase in the log odds (and therefore the odds) of the response variable. If the coefficient is negative, an increase in the predictor variable is associated with a decrease in the log odds (and therefore the odds) of the response variable.</p><h3>Calculating Coefficients in GLMs</h3><p>The coefficients in GLMs are estimated using maximum likelihood estimation (MLE), which is a method for finding the values of the coefficients that maximize the likelihood of the observed data, given the model. The likelihood function is a measure of how likely the observed data are, given the values of the coefficients.</p><p>The likelihood function for a GLM is:</p><blockquote><strong>L(β) = ∏ᵢ f(yᵢ; θᵢ, β)ᵈⁱ</strong></blockquote><p>where β is the vector of coefficients, yᵢ is the observed response variable for the i-th observation, θᵢ is the vector of predictor variables for the i-th observation, f(yᵢ; θᵢ, β) is the probability density function for the response variable, and dⁱ is the weight for the i-th observation.</p><p>The goal of MLE is to find the values of the coefficients that maximize the likelihood function. This is typically done using numerical optimization algorithms, such as the Newton-Raphson method or the Fisher scoring algorithm. These algorithms iteratively update the values of the coefficients until convergence is achieved.</p><p>To calculate the odds ratios for each coefficient, we can exponentiate the coefficients using the “exp” function:</p><pre># Calculate the odds ratios<br>exp(coef(model.glm))</pre><p>This returns a vector of the odds ratios for each coefficient. For example, the odds ratio for “hp” is 1.036, which means that for a one-unit increase in “hp”, the odds of having a manual transmission increase by a factor of 1.036, while holding all other variables constant.</p><p>We can also calculate confidence intervals for the coefficients using the “confint” function:</p><pre># Calculate the confidence intervals<br>confint(model.glm)</pre><p>This returns a matrix of the lower and upper bounds for the 95% confidence intervals for each coefficient. The intervals can give us an idea of how certain we are about the estimated coefficients. If the intervals are narrow, it suggests that we are relatively confident about the estimated coefficients. On the other hand, if the intervals are wide, it suggests that we are less confident about the estimated coefficients.</p><h3>Summary</h3><p>GLMs are a powerful tool for modeling the relationship between a response variable and one or more predictor variables. The coefficients in GLMs represent the change in the log odds of the response variable for a one-unit increase in the corresponding predictor variable, while holding all other predictor variables constant. These coefficients can be interpreted using odds ratios, which can give us insights into the direction and strength of the relationship between the predictor variables and the response variable. The coefficients are estimated using maximum likelihood estimation, and we can calculate confidence intervals to assess the uncertainty associated with the estimated coefficients.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6e6c475d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dask: Handling Large Datasets With Ease.]]></title>
            <link>https://abhic159.medium.com/dask-handling-large-datasets-with-ease-65ba156a214e?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ba156a214e</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 15:02:00 GMT</pubDate>
            <atom:updated>2023-03-24T15:02:00.698Z</atom:updated>
            <content:encoded><![CDATA[<p>Instead of pd, lets use dd!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sczOiMd8d_BSoY_nY1BNDQ.png" /></figure><h3>Introduction</h3><p>Dask is an open-source library for parallel computing in Python that is becoming increasingly popular in the field of data science. Dask is designed to work with large datasets that are too big to fit into memory and allows data scientists to easily scale their workflows to work with distributed computing resources. In this article, we will explore the use of Dask in data science and how it can help data scientists handle big data with ease.</p><h3>Why Use Dask in Data Science?</h3><p>Dask is particularly useful in data science for handling large datasets that are too big to fit into memory. With Dask, data scientists can easily scale their workflows to handle big data without having to change their existing code. Dask can handle data in a variety of formats, including CSV, HDF5, and Parquet, making it easy to integrate with existing data pipelines.</p><p>Dask is also useful for parallelizing complex computations that involve multiple steps, such as machine learning pipelines. By breaking down a computation into a series of smaller tasks, Dask can distribute the computation across multiple processors or nodes in a cluster, leading to significant speedups in computation time.</p><p>In addition, Dask provides a familiar API and programming model that makes it easy for data scientists to use and understand. Dask works seamlessly with existing Python libraries such as NumPy, Pandas, and Scikit-learn, making it easy to integrate with existing code and workflows.</p><h3>How Does Dask Work?</h3><p>Dask is built around the concept of a task graph, which is a directed acyclic graph (DAG) that represents a workflow. Each node in the task graph represents a task or computation, and the edges represent the data dependencies between tasks. Dask breaks down a computation into a series of smaller tasks, which are then scheduled and executed in parallel across multiple processors or nodes in a cluster.</p><p>Dask provides several APIs for working with parallelized data, including the Dask Array, Dask DataFrame, and Dask Bag APIs. The Dask Array API provides a parallelized version of the NumPy array that can handle large datasets that are too big to fit into memory. The Dask DataFrame API provides a parallelized version of the Pandas DataFrame that can handle large datasets that are too big to fit into memory. The Dask Bag API provides a parallelized version of the Python list that can handle large datasets that are too big to fit into memory.</p><p>Dask can be run on a single machine or across a cluster of machines. When running on a single machine, Dask can make use of all available processors to parallelize computations. When running across a cluster of machines, Dask uses a distributed scheduler to distribute tasks across multiple nodes in the cluster.</p><h3>Getting Started with Dask Data Frames</h3><p>We use pip to install Dask library.<br>Write this command in your jupyter terminal or use exclamation mark “!” before pip when you’re using your notebook for installation.</p><pre>!pip install dask</pre><h3>Comparing Dask and Pandas Data Frames</h3><p>Now that we have created a Dask data frame, let’s compare its performance to that of a Pandas data frame. We will demonstrate the performance benefits of Dask when working with a large dataset that is too big to fit into memory.</p><pre>import pandas as pd<br>import dask.dataframe as dd<br><br># Load a large data file into a Pandas data frame<br>pandas_df = pd.read_csv(&#39;large_data.csv&#39;)<br><br># Load the same data file into a Dask data frame<br>dask_df = dd.read_csv(&#39;large_data.csv&#39;)<br><br># Time the execution of a simple operation on both data frames<br>start_time = time.time()<br>pandas_df[&#39;column_name&#39;].mean()<br>print(f&quot;Pandas data frame took {time.time() - start_time} seconds&quot;)<br><br>start_time = time.time()<br>dask_df[&#39;column_name&#39;].mean().compute()<br>print(f&quot;Dask data frame took {time.time() - start_time} seconds&quot;)</pre><p>In this example, we load a large data file (15 GB) into both a Pandas data frame and a Dask data frame and then time the execution of a simple operation on both data frames. We then compare the execution time of the two data frames to demonstrate the performance benefits of Dask.</p><h3>Results</h3><pre>Pandas data frame took 22.045 seconds<br>Dask data frame took 0.256 seconds</pre><p>As we can see, the Dask data frame executed the operation much faster than the Pandas data frame. This is due to Dask’s ability to parallelize the computation across multiple processors or nodes in a cluster, leading to significant speedups in computation time.</p><h3>Conclusion</h3><blockquote>Dask is a powerful library for parallel computing in Python that provides a simple way to scale Python workflows. It is particularly useful for handling large datasets that are too big to fit into memory and for parallelizing complex computations that involve multiple steps. Dask data frames are a parallelized version of the Pandas data frame that offer significant performance benefits when working with large datasets. By using Dask data frames, data scientists can easily scale their workflows to handle big data without having to change their existing code.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ba156a214e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN (Condensed Nearest Neighbors)]]></title>
            <link>https://abhic159.medium.com/cnn-condensed-nearest-neighbors-3261bd0c39fb?source=rss-9a0d4f01560c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3261bd0c39fb</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 07:28:35 GMT</pubDate>
            <atom:updated>2021-10-12T04:50:35.624Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’d be studying about the following:<br>1. What is CNN?<br>2. What are imbalanced datasets?<br>3. Why are imbalanced datasets a problem?<br>4. What does CNN do basically<br>5. Working of CNN<br>6. Observations</p><p>So, CNN, is per se a fancy word to begin with. We all would be familiar with what <a href="https://medium.com/@MaximilianLloyd/k-nearest-neighbor-in-machine-learning-fbbe7ce850a1"><strong>KNN (K-Nearest Neighbors)</strong></a> is. Somewhat similar is CNN.</p><blockquote>CNN is a SMUTE(Systematic Majority Under-Sampling Technique)used to handle imbalanced datasets, so that we can then apply KNN to it without the algorithm flustering.</blockquote><h3><strong><em>What is an Imbalanced dataset?</em></strong></h3><p>A dataset is said to be imbalanced if the instances of a class are either very less or very high in number as compared to the instances of other class.</p><h3>Why is this a problem?</h3><p>Well, many machine learning algorithms assume that the instances of all the classes are equally(almost) distributed. However, when this is not true in reality, the algorithm becomes biased towards the majority class instances and starts flustering.<br>Further, many algorithms improve the accuracy by reducing the errors, and simply fluster when the dataset is imbalanced.</p><blockquote><strong>Ensemble techniques are not affected by the imbalanced nature of the dataset but well, its always better to cure a disease rather than simply treating the symptoms.</strong></blockquote><h3>What does CNN do basically?</h3><p>CNN basically removes the majority class instances in such a manner that there is no information loss and the dataset becomes balanced.</p><p><strong><em>The aim of CNN is to produce a subset of dataset that can correctly classify all the data points in the original dataset.</em></strong></p><blockquote>Simply removing majority class data points from the dataset will lead to information loss and hence a further deterioration of the algorithms output.</blockquote><h3>Working of CNN</h3><p>Let us understand the working of CNN.</p><p>Suppose that we have a dataset D, given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*Kds-sPXpL27cIyRyLFBwwQ.png" /><figcaption>where, xᵢ is a data point and yᵢ is its original classification</figcaption></figure><p><strong><em>Step 1: Choose ‘k’ :</em></strong> CNN works with a value of ‘k’. The value of ‘k’ which we choose will give a unique result. Changing ‘k’ changes our final result. Let us assume k = 3 for our case.</p><p><strong><em>Step 2:</em></strong> Start the iteration by choosing randomly any k (here 3) points to keep in the store S.</p><p>For simplicity, consider that we have squares and circles as shown below and we select these 3 points as the initial points in the Store S.</p><blockquote>(PS: The diagram below is just an illustration. <strong>Clearly, its very much balanced</strong>. Imbalancy is feature pertaining to a ratio of 70:30 majority class to minority class instances or more extreme)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*j6xwuiqZ_4-YUajioczo0w.png" /></figure><p><strong><em>Step 3: </em></strong>We check whether the store S is ‘Training Set Consistent’ or not. If it is, we stop; else we add a point to the store so as to improve it and make it training set consistent.</p><p>Training Set Consistency: A set is said to be training set consistent if on running KNN on the dataset with the classifiers as the points in store, we get the same classification as when KNN was run on the entire dataset.<br>i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*x1xr_fT7kxorpOW2gVyCxQ.png" /><figcaption>gₓ(aᵢ) represents the classification of aᵢ with respect to dataset X</figcaption></figure><p><strong><em>Now, we check if our store S with the 3 selected points is consistent or not.</em></strong><br><strong><em>Consider the dark blue point.</em></strong></p><p>According to the store, it must be blue (since out of the 3 points in store, 2 are blue). <br>So,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*HYzQiBrK7NrLkW4302oUjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*WBcNrQNF27A3Js1vlIWSEA.png" /><figcaption>3-NN with S as the dataset classifies the dark blue point as blue</figcaption></figure><p>However, according to the complete dataset, that point must be red, becuase out of 3 nearest neighbors, 2 are red.<br>i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*u_ta3C6FF9B4j-HF_9zfkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*vSQ1WK2MNKc9vRH-9SJi7A.png" /><figcaption>3-NN on complete dataset classifies as the dark blue point as red.</figcaption></figure><p>Clearly, we have a training set inconsistency.</p><p><strong><em>Step 4:</em></strong> We select a random point from the dataset to add in store such that the inconsistency with the classification of dark blue point is solved keeping the prediction of the dataset as gold standard<br>i.e. select a random point xᵢ from the dataset such that on adding xᵢ we have,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*toDcQxQjs2sEcJ876DjyHA.png" /></figure><p>So we add the dark red point (in square) to the store S.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*rIYML7XDnfREUMsX0RyHTg.png" /><figcaption>We add the red square (outlined with blue dotted square) in store S</figcaption></figure><p><strong><em>Step 5: Repeat till the Store S is training set consistent.</em></strong></p><h3>Some Observations:</h3><ol><li>When the store is training set inconsistent, a point will definitely exist that will improve the store S.</li><li>The process will terminate in at max n iterations where n is the number of points in the dataset D</li><li>Upon termination, S will always be Training Set Consistent</li></ol><p>You can directly implement this CNN using scikit-learn’s <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.CondensedNearestNeighbour.html"><strong><em>Imblearn library</em></strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*A562M0fHAqa1goV7tZhekQ.png" /></figure><h3>Conclusion</h3><p>Condensed Nearest Neighbors is a very powerful technique to balance an imbalanced dataset and aims at reducing information loss due to under-sampling. However, it still leads to some information loss as instances are removed from the dataset. However, a much more powerful tool Advanced -CNN, can be used to overcome this problem in a much more efficient way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3261bd0c39fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>