<?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 Rakeshbobbati on Medium]]></title>
        <description><![CDATA[Stories by Rakeshbobbati on Medium]]></description>
        <link>https://medium.com/@rakeshbobbati_85122?source=rss-02d6b6b23627------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vdMfF-CEqt3LedIv</url>
            <title>Stories by Rakeshbobbati on Medium</title>
            <link>https://medium.com/@rakeshbobbati_85122?source=rss-02d6b6b23627------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:21:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakeshbobbati_85122/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[Maximising Outcomes in Data Science Model testing with Multi-Armed Bandit Approaches]]></title>
            <link>https://medium.com/@rakeshbobbati_85122/maximising-outcomes-in-data-science-with-multi-armed-bandit-approaches-6f3fe545efa0?source=rss-02d6b6b23627------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3fe545efa0</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[upper-confidence-bound]]></category>
            <category><![CDATA[thompson-sampling]]></category>
            <category><![CDATA[multi-armed-bandit]]></category>
            <category><![CDATA[epsilon-greedy-algorithm]]></category>
            <dc:creator><![CDATA[Rakeshbobbati]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 18:25:53 GMT</pubDate>
            <atom:updated>2024-07-22T18:51:23.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*WkZ-9_NADGQUog5_Drfn_g.png" /></figure><h3><strong>Differences Between A/B Testing and Multi-Armed Bandit Testing</strong></h3><p><strong>A/B Testing</strong>: A/B testing involves comparing two versions (A and B) of a variable (e.g., a web page, email, or app feature) to determine which one performs better based on a specific metric (e.g., click-through rate, conversion rate). <a href="https://medium.com/@rakeshbobbati_85122/a-b-testing-with-practical-examples-6b0f27c50852">Here</a> is the blog with an example and python code.</p><p><strong>Process of A/B testing:</strong></p><ol><li><strong>Hypothesis:</strong> Formulate a hypothesis about which version will perform better.</li><li><strong>Random Assignment:</strong> Randomly divide the audience into two groups. One group is exposed to version A, and the other to version B.</li><li><strong>Data Collection:</strong> Collect data over a set period to ensure statistical significance.</li><li><strong>Analysis:</strong> Analyse the results to determine which version performed better.</li><li><strong>Decision:</strong> Implement the winning version.</li></ol><p><strong>Advantages:</strong></p><ul><li>Simple to understand and implement.</li><li>Provides clear, binary results.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Requires a significant amount of data to reach statistical significance.</li><li>Traffic is split evenly, which can lead to potential losses if one version performs poorly.</li><li>Time-consuming, as it requires running the test for a fixed duration.</li></ul><p><strong>Use Cases:</strong></p><ul><li><strong>Simple Comparisons:</strong> When you want to compare two versions of a webpage, email, or app feature.</li><li><strong>Sufficient Traffic and Time:</strong> When you have enough traffic and can afford to wait for statistically significant results.</li><li><strong>Clear Hypotheses:</strong> When you have a clear hypothesis and want a straightforward answer.</li></ul><h4>When to Use A/B Testing</h4><ol><li><strong>Simplicity:</strong> When the test design needs to be simple and easy to interpret.</li><li><strong>Low Opportunity Cost:</strong> When the potential cost of exploring suboptimal versions is low.</li><li><strong>Ample Traffic and Time:</strong> When you have enough traffic and can afford to wait for statistically significant results.</li><li><strong>Clear Decision-Making:</strong> When you want a straightforward, binary result to inform your decision-making.</li></ol><h3><strong>Multi-Armed Bandit Testing:</strong></h3><ul><li>Multi-Armed Bandit (MAB) testing is an advanced approach inspired by the multi-armed bandit problem in probability theory. It aims to maximise the cumulative reward by dynamically allocating more traffic to better-performing versions.</li><li>MAB testing is a sophisticated and adaptive approach to experimentation. The problem gets its name from the metaphor of a gambler facing multiple slot machines (bandits), each with an unknown payout. The gambler must decide which machines to play, how many times to play each, and in which order to maximize the total reward. This problem highlights the trade-off between exploration (trying different machines to discover their payouts) and exploitation (playing the machine that currently seems to offer the best payout).</li></ul><p><strong>Process:</strong></p><ol><li><strong>Initialisation:</strong> Start with multiple versions (arms) of the variable you want to test.</li><li><strong>Exploration:</strong> Initially, distribute traffic evenly to gather performance data.</li><li><strong>Exploitation:</strong> Gradually allocate more traffic to better-performing versions based on real-time data.</li><li><strong>Continuous Adjustment:</strong> Continuously monitor and adjust traffic allocation to maximise performance.</li></ol><p><strong>Advantages:</strong></p><ul><li>Faster convergence to the optimal version.</li><li>Reduced opportunity cost by allocating more traffic to better-performing versions early.</li><li>Adaptive to changes in performance over time.</li><li>Real time adjustments: Continuously adjusts to changing conditions and new information. Suitable for dynamic environments where the performance of options may change over time.</li><li>Requires fewer samples to identify the best option compared to A/B testing, as it continuously learns and adapts.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>More complex to implement and understand compared to traditional A/B testing.</li><li>Requires a deeper understanding of the underlying algorithms and their parameters. (Exploration, Exploitation , Epsilon-greedy method, Upper Confidence Bound (UCB) Algorithm and Thompson Sampling method)</li><li>Continuous monitoring and adjustment can be resource-intensive.</li><li>May require more computational power and sophisticated infrastructure.</li><li>If not properly configured, there is a risk of premature exploitation based on insufficient data, leading to suboptimal decisions.</li></ul><p><strong>Use Cases:</strong></p><ul><li><strong>Dynamic Environments:</strong> When the environment is dynamic, and you need the testing method to adapt to changes over time.</li><li><strong>Speed is Critical:</strong> When you need to identify the optimal version quickly.</li><li><strong>High Opportunity Cost:</strong> When the cost of exploring suboptimal versions is high, and you want to minimise losses.</li><li><strong>Continuous Optimisation:</strong> When running ongoing optimisations rather than one-time tests.</li></ul><h4>When to Use Multi-Armed Bandit Testing</h4><ol><li><strong>Need for Speed:</strong> When quick identification of the best-performing version is critical.</li><li><strong>Dynamic Allocation:</strong> When you want to dynamically allocate traffic to maximise overall performance.</li><li><strong>High Opportunity Cost:</strong> When the cost of exploring suboptimal versions is high, and you want to minimise potential losses.</li><li><strong>Continuous Adaptation:</strong> When the testing environment is dynamic, and you need the method to adapt to changes over time.</li><li><strong>Limited Traffic:</strong> When you have limited traffic and want to make the most out of it by continuously optimising the allocation.</li></ol><p>Knowledge of some topics is mandatory before getting deep into <strong>MAB</strong></p><ol><li>Exploration and Exploitation</li><li>Epsilon Greedy Method ( combination of Exploration and Exploitation for optimal results)</li><li>Upper confidence bound (UCB) optimising exploration and exploitation</li><li>Thomson Sampling Yet another optimising algorithm that solves exploration-exploitation dilemma</li></ol><p><strong>Explanation of topics in detail:</strong></p><p><strong>Exploration: </strong>Exploration is a critical part of the MAB framework, ensuring that all options or cases or variations are sufficiently tested to gather reliable data. Far below, we’ll dive into the concept of exploration and exploitation also I will provide an example using the epsilon-greedy,UCB and Thompson sampling algorithms, simple yet effective MAB algorithms. <strong>Exploration</strong> involves trying different options to gather information about their potential rewards. This phase is crucial because without sufficient exploration, you might miss out on the best-performing option due to initial randomness or noise in the data. The goal is to ensure that each option is tested enough to make an informed decision about which one performs the best.</p><p>Proper exploration can lead to discovering high-reward arms that might have been overlooked.</p><p>Exploring suboptimal arms can result in lower immediate rewards. We waste our time and resources exploring all options</p><p><strong>Example: </strong>Let’s consider a scenario where a person watches movies from three different genres: Drama, Thriller, and Action. Each genre provides a happiness index (reward) drawn from a specific range:</p><ul><li>Drama: [0,5] — a movie can provide happiness from 0 to 5</li><li>Thriller: [0,7] — a movie can provide happiness from 0 to 7</li><li>Action: [0,9] — a movie can provide happiness from 0 to 9</li></ul><p>We’ll explore by randomly selecting a genre for each of the 10 attempts and then calculate the regret based on the optimal choice, which would be watching Action movies, given its higher upper bound 9 on happiness. Ideally we should watch all 9 happiness giving action movies to get optimal happiness.</p><p><em>Optimal Happiness= 9×10 = 90</em></p><h4>Steps</h4><ol><li><strong>Initialisation</strong>: No initial happiness estimates since we are purely exploring.</li><li><strong>Exploration</strong>: Randomly select a genre for each attempt and record the happiness index.</li><li><strong>Calculate Regret</strong>: Compare the total obtained happiness with the total happiness if the optimal genre (Action) was always chosen.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*_Jn6Js0Ah2e93DW0lYj6aQ.png" /></figure><p><em>Total Obtained Happiness=4.2+8.5+6.1+3.7+7.8+5.5+9.0+2.9+4.8+8.2=60.7</em></p><p><em>Regret = Optimal Happiness−Total Happiness = 90−60.7 =29.3</em></p><p><strong>Exploitation: </strong>Always choosing those variation where we get maximum output. Using the information provided to choose the option that currently seems to have the highest payout probability. Which is action movies here as it has upper bound of 9.</p><p>So from above example problem with optimal happiness of 90 out of all 10 views. When we watch 10 movies from actions the distribution is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*gW0rvjDDy2sxu5hRX690jw.png" /></figure><p><em>Total Obtained Happiness=8.3+7.9+8.5+9.0+7.6+8.8+8.1+9.0+7.7+8.9=83.8</em></p><p><em>Regret = Theoretical Maximum Happiness−Total Happiness=90−83.8=6.2</em></p><p>But if we initially do not know the lower and upper bound which will be in real world scenario. We can put some trails to explore all options and exploit that option which will give maximum reward till now. In that case we might end up using sub optimal option. May be in our example case we may choose thriller. If explore initial 3 options for all genre and thriller give best happiness outcome in our 3 attempts. In this case we did not explore enough options to get a good option. So we fall into a dilemma of using either exploring or exploiting.</p><h3>Balancing Exploration and Exploitation</h3><p>The essence of multi-armed bandit testing lies in effectively balancing exploration (trying out different options to gather data) and exploitation (using the gathered data to choose the best option). Here’s a deeper look into how different algorithms address this balance:</p><p><strong>Epsilon-Greedy Algorithm:</strong></p><ul><li><strong>Exploration Phase:</strong> With a small probability ε, a random option is selected to ensure that each option is tried enough times to gather data.</li><li><strong>Exploitation Phase:</strong> With a high probability (1-ε), the option with the highest estimated reward is selected.</li><li><strong>Trade-off:</strong> Easy to implement but might not be efficient if ε is not well-tuned.</li></ul><h4>Steps</h4><ol><li><strong>Initialisation</strong>: Start with initial estimates of the average happiness for each genre as 0.</li><li><strong>Exploration and Exploitation</strong>: For each attempt, decide to explore or exploit based on ϵ\epsilonϵ.</li><li><strong>Update Estimates</strong>: Update the estimated average happiness for the chosen genre based on the observed happiness index.</li><li><strong>Calculate Regret</strong>: Compare the total obtained happiness with the total happiness if the optimal genre (Action) was always chosen.</li></ol><p>From the above movie example:</p><p>Let’s assume the following random happiness indices for each attempt:</p><h4>Initial Estimates</h4><p><em>Reward_Drama=0 , Reward_Thriller=0 , Reward_Action=0</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1PPyUEeb0hr_elryX4egg.png" /></figure><p><em>Total obtained Happiness = 7.5+3.2+5.1+8.7+6.4+4.3+9.0+7.1+8.2+2.8 = 62.3</em></p><p><em>Regret = Optimal Happiness−Total Happiness = 90−62.3 = 27.7</em></p><p>Which is better than exploration.</p><p><strong>Upper Confidence Bound (UCB) </strong>:</p><p>The Upper Confidence Bound (UCB) algorithm is another approach to balancing exploration and exploitation. The idea behind UCB is to select the arm (genre) that maximizes the upper confidence bound of the estimated reward. This method ensures that arms with higher uncertainty are explored more often, especially in the early stages.</p><h4>Steps</h4><ol><li><strong>Initialisation</strong>: Start with initial estimates of the average happiness for each genre and a count of how many times each genre has been selected.</li><li><strong>Upper Confidence Bound Calculation</strong>: For each genre, calculate the upper confidence bound.</li><li><strong>Selection</strong>: Choose the genre with the highest upper confidence bound.</li><li><strong>Update Estimates</strong>: Update the estimated average happiness and the count for the chosen genre.</li><li><strong>Calculate Regret</strong>: Compare the total obtained happiness with the total happiness if the optimal genre (Action) was always chosen.</li></ol><p>Upper Confidence Bound Formula:</p><p>The upper confidence bound for genre i is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*LniJkUtsEptEuMaG7tJhyA.png" /></figure><p>Where: (R-cap-i) is the estimated average happiness for genre i.</p><ul><li>(R-cap-i) is the estimated average happiness for genre i.</li><li>c is a constant that determines the degree of exploration (often set to sqrt(2) )</li><li>t is the total number of attempts so far.</li><li>n_i​ is the number of times genre i has been chosen.</li></ul><h4>Initial Estimates</h4><p><em>Reward_Drama=0 , Reward_Thriller=0 , Reward_Action=0 , n_Drama = 0 , n_Thriller = 0 , n_Action = 0</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgEJIajcu3nxbwuMmwLDyA.png" /></figure><p><em>Total Obtained Happiness = 4.2+6.3+7.5+8.1+9.0+5.4+7.2+8.8+3.5+8.0=68.0</em></p><p><em>Regret = Optimal Happiness−Total Happiness =90−68.0 = 22.0</em></p><p><strong>Thomson Sampling </strong>:</p><p>Thompson Sampling is a probabilistic algorithm used in the context of the Multi-Armed Bandit (MAB) problem to balance exploration and exploitation. It is also known as Bayesian Bandits or Posterior Sampling. The algorithm is particularly effective in dynamic and uncertain environments where the underlying probabilities of rewards are unknown and may change over time.</p><p><strong>Key Concepts of Thompson Sampling:</strong></p><p><strong>Bayesian Inference: </strong>Thompson Sampling uses Bayesian inference to model the uncertainty in the reward distributions of each option. It maintains a posterior distribution of the reward probability for each option and updates it as new data (rewards) is observed.</p><p><strong>Posterior Distribution: </strong>For each option, Thompson Sampling maintains a posterior distribution based on prior beliefs and observed rewards. Typically, a Beta distribution is used as it is a conjugate prior for the Bernoulli distribution (success/failure rewards).</p><p><strong>Sampling: </strong>At each step, the algorithm samples a probability of success from the posterior distribution of each option. The option with the highest sampled probability is selected (exploitation), but this sampling inherently includes the possibility of exploring other option.</p><p><strong>Updating: </strong>After selecting an option and receiving the reward, the posterior distribution of the selected option is updated to reflect the new data. This updating process is done using Bayesian updating rules.</p><p><strong>Thompson Sampling Steps</strong></p><ol><li><strong>Initialisation</strong>: Start with prior distributions for the happiness indices of each genre. We’ll use Beta distributions, initialised with parameters α=1 and β=1.</li><li><strong>Sampling</strong>: For each attempt, sample a value from the Beta distribution for each genre.</li><li><strong>Selection</strong>: Choose the genre with the highest sampled value.</li><li><strong>Update</strong>: Update the Beta distribution parameters (α and β) based on the observed happiness index.</li><li><strong>Calculate Regret</strong>: Compare the total obtained happiness with the total happiness if the optimal genre (Action) was always chosen.</li></ol><p><strong>Beta Distribution Updates</strong></p><p>The Beta distribution is updated as follows:</p><ul><li>If the reward is observed, α is increased by the reward value (scaled to the range of the Beta distribution, e.g., [0, 1]).</li><li>β is increased by the difference between the maximum reward and the observed reward.</li></ul><h4>Initial Estimates</h4><p>α_ Drama=1,β_Drama=1 , α_Thriller=1,β_Thriller=1, α_Action=1,β_Action=1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBV63WklJfGEmpFiVhA5bg.png" /></figure><p><em>Total Obtained Happiness=8.3+3.5+5.6+7.5+9.0+6.2+8.1+7.7+2.8+8.0=66.7</em></p><p><em>Regret=Optimal Happiness−Total Happiness=90−66.7=23.3</em></p><h3>Practical Implementation Considerations</h3><p>Implementing Multi-Armed Bandit (MAB) testing involves a series of steps to ensure that the chosen algorithm is effectively balancing exploration and exploitation, maximising the overall reward. Here’s a detailed guide on how to practically implement MAB testing.</p><p><strong>Define Objectives and Metrics:</strong></p><ul><li><strong>Objective:</strong> Clearly define what you want to achieve with the MAB test, such as maximizing click-through rates, conversions, or user engagement.</li><li><strong>Metrics:</strong> Identify the key performance indicators (KPIs) that will be used to measure success, such as clicks, conversions, or revenue.</li></ul><p><strong>Select the Appropriate Bandit Algorithm:</strong></p><ul><li><strong>Epsilon-Greedy:</strong> Simple to implement; suitable for scenarios where a straightforward balance between exploration and exploitation is needed.</li><li><strong>Upper Confidence Bound (UCB):</strong> More sophisticated; useful when you need to consider both the average reward and the uncertainty of estimates.</li><li><strong>Thompson Sampling:</strong> Effective for dynamic environments; uses Bayesian inference to balance exploration and exploitation.</li></ul><p><strong>Set Up the Environment:</strong></p><ul><li>Ensure you have the necessary computational resources and infrastructure to support continuous data collection and processing.</li><li>Use a robust data pipeline to handle real-time data inflow and ensure the integrity and quality of the data collected.</li></ul><p><strong>Deploy and Start Testing:</strong></p><ul><li><strong>Initial Exploration:</strong> Begin by distributing traffic evenly across all arms to gather initial data.</li><li><strong>Continuous Monitoring:</strong> Continuously monitor the performance of each arm and the overall system.</li><li><strong>Adjust Parameters:</strong> Depending on the initial results, adjust the parameters to balance exploration and exploitation better.</li></ul><p><strong>Data Collection and Analysis:</strong></p><ul><li>Collect data on the performance of each arm, focusing on the defined metrics.</li><li>Use statistical methods to analyze the collected data and update the algorithm’s parameters.</li><li>Ensure real-time processing to adapt quickly to changes in performance.</li></ul><p><strong>Dynamic Adjustment:</strong></p><ul><li>Based on the data, dynamically allocate more traffic to the better-performing arms.</li><li>Continuously update the estimates of each arm’s reward probability.</li><li>Adjust the exploration rate (ε) for epsilon-greedy, the confidence intervals for UCB, and the posterior distributions for Thompson Sampling.</li></ul><p>Let us now discuss an example problem similar to my previous <a href="https://medium.com/@rakeshbobbati_85122/a-b-testing-with-practical-examples-6b0f27c50852">A/B testing</a> blog.</p><p><strong>Example of MAB for Conversion Rate Optimisation on an E-commerce Platform like Flipkart or Amazon.</strong></p><h4>Scenario:</h4><p>You are managing a landing page for a flash sale on an e-commerce platform like <strong>Myntra</strong>. The goal is to maximise the conversion rate from visitors landing on the page to purchasing the flash sale product.</p><h4>Steps for Implementing MAB Testing:</h4><p>1. Defining Objectives and Metrics:</p><ul><li><strong>Objective:</strong> Maximise the conversion rate from landing page visitors to buyers. People visiting Home page and clicking on flash sale and finally buying the product.</li><li><strong>Metrics:</strong> Conversion rate (number of purchases / number of visitors).</li></ul><p>2. Select the Appropriate Bandit Algorithm:</p><p>For this scenario, we’ll use the <strong>Upper Confidence Bound (UCB)</strong> algorithm due to its efficiency in balancing exploration and exploitation, particularly in environments where some options might have higher uncertainty.</p><p>3. Set Up the Environment:</p><ul><li><strong>Traffic Allocation:</strong> Split the incoming traffic between different landing page variations.</li><li><strong>Variations (Arms):</strong> Create several versions of the landing page (e.g., different layouts, CTAs, images, product descriptions).</li></ul><p>4. Initialise the Algorithm:</p><ul><li>Initialise the UCB algorithm with equal confidence intervals for each landing page variation.</li></ul><p>5. Deploy and Start Testing:</p><ul><li><strong>Initial Exploration:</strong> Allocate traffic equally among all landing page variations to gather initial data. This helps in estimating the conversion rates for each variation.</li></ul><p>6. Data Collection and Analysis:</p><ul><li><strong>Data Points:</strong> Collect data on the number of visitors and the number of purchases for each landing page variation.</li><li><strong>Update Estimates:</strong> Use the collected data to update the estimated conversion rates and the confidence intervals for each variation.</li></ul><p>7. Dynamic Adjustment:</p><ul><li><strong>Exploration:</strong> Occasionally allocate traffic to less-explored variations to gather more data about their performance.</li><li><strong>Exploitation:</strong> Gradually allocate more traffic to the landing page variation with the highest estimated conversion rate and confidence.</li></ul><p>8. Evaluation and Optimisation:</p><ul><li><strong>Performance Evaluation:</strong> Regularly evaluate the performance of each landing page variation.</li><li><strong>Parameter Optimisation:</strong> Adjust the confidence interval calculations based on the ongoing performance data to improve the accuracy of the estimates.</li></ul><p>9. Scaling and Maintenance:</p><ul><li><strong>Traffic Scaling:</strong> As the algorithm identifies the best-performing landing page, gradually allocate more traffic to this variation while still exploring other options occasionally.</li><li><strong>Continuous Monitoring:</strong> Keep monitoring the performance to ensure that the best variation continues to perform well and adapt to any changes in user behaviour or market conditions.</li></ul><h3>Practical Example:</h3><h4>Initial Setup:</h4><p><strong>Landing Page Variations:</strong></p><ul><li><strong>Variation A:</strong> Standard layout with a prominent “Buy Now” button.</li><li><strong>Variation B:</strong> Layout with a countdown timer and urgency messaging.</li><li><strong>Variation C:</strong> Layout with customer reviews and testimonials.</li></ul><p><strong>Initial Traffic Allocation:</strong></p><ul><li>Equal traffic distribution: 33% of visitors to each variation.</li></ul><h4>Data Collection Phase:</h4><p>After a few hours/days of running the test, collect the data like in the below example.</p><ul><li><strong>Variation A:</strong> 1000 visitors, 50 purchases (Conversion Rate: 5%)</li><li><strong>Variation B:</strong> 1000 visitors, 60 purchases (Conversion Rate: 6%)</li><li><strong>Variation C:</strong> 1000 visitors, 55 purchases (Conversion Rate: 5.5%)</li></ul><h4>UCB Algorithm Calculation:</h4><ul><li><strong>Step 1:</strong> Calculate the average conversion rate for each variation.</li><li><strong>Step 2:</strong> Calculate the confidence interval for each variation based on the number of visitors and conversions.</li><li><strong>Step 3:</strong> Select the variation with the highest upper confidence bound for the next round of traffic allocation.</li></ul><h4>Dynamic Adjustment Phase:</h4><ul><li>Suppose Variation B has the highest upper confidence bound. Allocate more traffic to Variation B, but still allocate a smaller proportion to Variations A and C to continue exploring.</li></ul><h4>Continuous Monitoring:</h4><ul><li>Continue to monitor the performance of each variation and adjust traffic allocation dynamically.</li><li>If Variation C starts performing better over time, the algorithm will shift more traffic towards it.</li></ul><p><strong>Exploration:</strong> Ensures that all variations are tested sufficiently to gather accurate data. In this example, even though Variation B initially shows better performance, Variations A and C are still explored to ensure they don’t outperform in the long run.</p><p><strong>Exploitation:</strong> Focuses traffic on the best-performing variation based on current data. As Variation B shows the highest conversion rate, more traffic is directed to it to maximise overall conversions.</p><p>We can test our Data Science ML models on Experimentation Platforms Tools like “Optimizely” or Google “Optimize” . They provide service for both A/B testing and MAB testing.</p><h3>Conclusion</h3><p>The exploration-exploitation trade-off is at the heart of the Multi-Armed Bandit problem. Effective strategies require balancing the immediate rewards obtained through exploitation with the long-term benefits of exploration. Various algorithms, each with its strengths and weaknesses, address this trade-off in different ways. Understanding these concepts and their implications is crucial for designing and implementing effective decision-making strategies in uncertain environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3fe545efa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Machine Learning Loss Functions and Evaluation Metrics Explained: PART 2…]]></title>
            <link>https://medium.com/@rakeshbobbati_85122/comprehensive-guide-to-machine-learning-loss-functions-and-evaluation-metrics-explained-part-2-ed5e2f35ddc7?source=rss-02d6b6b23627------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed5e2f35ddc7</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[clustering-metrics]]></category>
            <category><![CDATA[classification-metrics]]></category>
            <dc:creator><![CDATA[Rakeshbobbati]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 14:42:20 GMT</pubDate>
            <atom:updated>2024-07-22T18:27:28.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*slY-5dvsrdSOaG7BPLbu3g.png" /></figure><h3>Comprehensive Guide to Machine Learning Loss Functions and Evaluation Metrics Explained: PART 2 (Classification and Clustering).</h3><p>In the previous part, we delved into loss functions and metrics commonly used in regression machine learning models. Today, we will shift our focus to exploring essential loss functions and metrics used in classification and clustering methods. These concepts are crucial for evaluating and improving the performance of machine learning models in tasks where the goal is to categorise data points or group similar items together.</p><p>Understanding Loss Functions and Metrics in Classification and Clustering Methods:</p><h3><strong>Cross-Entropy Loss (Log Loss)</strong></h3><p>Cross-entropy loss quantifies the difference between two probability distributions. It is commonly used when the model outputs a probability for each class, and it measures how far off these probabilities are from the actual class labels.</p><p>For binary classification, the binary cross-entropy loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fJUrO2pKhUiT595TCBwKNA.png" /></figure><p>where:</p><ul><li>N is the number of samples.</li><li>yi is the actual label for sample i (0 or 1).</li><li>pi​ is the predicted probability of the sample i being in class 1</li></ul><p>The loss function penalises predictions based on their confidence and correctness. If the true label yi is 1, the term log(pi​) dominates. If pi is close to 1, log term will be close to 0, leading to a lower loss. If pi is far from 1, the loss will be higher. Similarly, if the true label yi is 0, the term log(1−pi​) dominates. If pi is close to 0, the log term will be close to 0, leading to a lower loss. The cross-entropy loss decreases as the predicted probability gets closer to the actual label. It is especially useful for training models where the output is a probability distribution.</p><h3>Categorical Cross-Entropy Loss</h3><p>Categorical cross-entropy loss extends the binary cross-entropy loss to multi-class classification problems, where the goal is to assign the input to one of multiple classes.</p><p>For multi-class classification with C classes, the categorical cross-entropy loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*rB1hSga2kfhxrjnsgjie3A.png" /></figure><p>where:</p><ul><li>N is the number of samples.</li><li>C is the number of classes.</li><li>y<em>ic</em> is a binary indicator (0 or 1) if class label c is the correct classification for sample i.</li><li>p<em>ic</em> is the predicted probability of sample iii for class c.</li></ul><p>Each term y<em>ic * </em>log⁡(p<em>ic</em>) contributes to the loss only for the correct class c. The loss function sums over all classes C and averages over all samples N. Categorical cross-entropy loss is minimised when the predicted probability for the correct class is maximised. It penalises the model more when the predicted probability for the correct class is lower.</p><p>In neural networks, the soft-max activation function is often used in the final layer to convert logits (raw model outputs) into probabilities that sum to 1.</p><p>Soft-max formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*6J7MB4DAtmGk7RCuN_4Wnw.png" /></figure><p>And for binary classification we use sigmoid function so that the output will be 0 or 1.</p><p>Sigmoid formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*kg-BAyR55Hq5L6G7m9ZVZw.png" /></figure><p>where x is the input to the sigmoid function.</p><ul><li>The output of the sigmoid function is in the range (0, 1), making it ideal for binary classification problems where the output represents the probability of the positive class.</li><li>It is a smooth, differentiable function, which makes it suitable for back propagation in neural networks.</li></ul><h3>Example</h3><p><strong>Binary Classification Example:</strong></p><ul><li>True labels: y = [1,0,1]</li><li>Predicted probabilities: p = [0.9,0.2,0.7]</li></ul><p>Cross-entropy loss: Loss =(−1/3) * [log⁡(0.9)+log⁡(0.8)+log⁡(0.7)]</p><p><strong>Multi-Class Classification Example:</strong></p><ul><li>True labels: y = [[1,0,0],[0,1,0],[0,0,1]] for classes A, B, and C respectively.</li><li>Predicted probabilities: p = [[0.8,0.1,0.1],[0.2,0.6,0.2],[0.1,0.3,0.6]]</li></ul><p>Categorical cross-entropy loss: Loss=(−1/3) * [log⁡(0.8)+log⁡(0.6)+log⁡(0.6)]</p><p>Cross-entropy loss (log loss) and categorical cross-entropy loss are powerful metrics for evaluating classification models. They provide a way to quantify how well a model’s predicted probability distribution matches the true distribution of the data. By minimising these loss functions, models are trained to make more accurate and confident predictions. Understanding these concepts is essential for anyone looking to excel in the field of classification models.</p><h3><strong>Hinge Loss</strong></h3><p>Hinge loss is a loss function primarily used for training support vector machines (SVMs), and it is particularly suited for binary classification tasks. The hinge loss aims to find a decision boundary that maximises the margin between two classes.</p><p>For binary classification, where the target labels y are either +1 or -1, the hinge loss for a single sample is defined as:</p><p><em>Loss=max⁡(0,1−y⋅f(x))</em></p><p>where:</p><ul><li>y is the true label for the sample (either +1 or -1).</li><li>f(x)is the predicted score from the classifier for the sample.</li></ul><p>For a dataset with N samples, the average hinge loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*RjQVIiP4nAoRlzhdKZK8rw.png" /></figure><p>where:</p><ul><li>y<em>i</em> is the true label for the i-<em>th</em> sample.</li><li>f(x<em>i</em>) is the predicted score for the i-<em>th </em>sample.</li><li>The hinge loss function penalises samples that are on the wrong side of the decision boundary or within the margin area.</li></ul><p>If the true label y is +1 and f(x) ≥ 1, or if y is -1 and f(x) ≤ −1, the loss is 0, indicating correct and confident classification. If the true label y is +1 and f(x) &lt; 1 , or if y is -1 and f(x) &gt; −1, the loss increases, indicating a misclassified sample or a sample within the margin.</p><p>The goal of SVM is to maximise the margin between the two classes, which is the distance between the closest points of the classes (support vectors) and the decision boundary. The hinge loss function contributes to this goal by penalising predictions that do not respect the margin.</p><p>Hinge loss is an essential concept in the realm of binary classification, particularly for SVMs. It focuses on maximising the margin between classes, leading to better generalisation. Understanding hinge loss and its implementation in different frameworks allows practitioners to leverage it effectively in various machine learning applications.</p><h3><strong>Confusion Matrix</strong></h3><p>A confusion matrix is a table used to describe the performance of a classification model by comparing the actual labels with the predicted labels. It is especially useful for understanding the performance on individual classes in multi-class classification problems.</p><p>For a binary classification problem, the confusion matrix is a 2x2 table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JHAH4gj11FlcA4PdVMxpg.png" /></figure><ul><li><strong>True Positive (TP):</strong> The model correctly predicts the positive class.</li><li><strong>False Negative (FN):</strong> The model incorrectly predicts the negative class when the true class is positive.</li><li><strong>False Positive (FP):</strong> The model incorrectly predicts the positive class when the true class is negative.</li><li><strong>True Negative (TN):</strong> The model correctly predicts the negative class.</li></ul><h3>1. Precision:</h3><p>Precision, also called Positive Predictive Value, is the ratio of correctly predicted positive observations to the total predicted positives. It answers the question: “Of all the items that were predicted as positive, how many are actually positive?”</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*Vu-ZT8zpAOVBWLX2s7Ka3A.png" /></figure><p><strong>Example:</strong></p><p>If a model identifies 10 instances as positive, and out of those 10, 8 are actually positive and 2 are negative, the precision is 0.8 (or 80%).</p><h3><strong>2. Recall:</strong></h3><p>Recall, also known as Sensitivity or True Positive Rate, is the ratio of correctly predicted positive observations to all observations in the actual class. It answers the question: “Of all the items that are actually positive, how many were predicted as positive?”</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ZVEBGd1nTFLZTmqhp974qQ.png" /></figure><p><strong>Example:</strong></p><p>If there are 12 actual positive instances, and the model correctly identifies 8 of them, the recall is 8/12 ≈ 0.67 (or 67%).</p><h3><strong>3. F1 Score:</strong></h3><p>The F1 score is the harmonic mean of precision and recall. It combines precision and recall into a single metric by balancing both concerns. The F1 score is especially useful when dealing with imbalanced datasets.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*6lYj_G7JiJsaukoQ16krkg.png" /></figure><p>If a model has a precision of 0.8 and a recall of 0.67, the F1 score is:</p><p>F1=2* (0.8 * 0.67)/(0.8 + 0.67​) ≈ 0.73</p><p><strong>Example Calculation</strong></p><p>Let’s say we have a confusion matrix for a binary classification model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IHXfRnalgX-Of0xJDwhCQ.png" /></figure><p>From this confusion matrix:</p><ul><li><strong>TP = 50</strong></li><li><strong>FN = 10</strong></li><li><strong>FP = 5</strong></li><li><strong>TN = 100</strong></li></ul><p><strong>Precision:</strong></p><p>Precision=TP/(TP+FP) ​= 50/(50+5) ​= 50/55 ​≈ 0.91</p><p><strong>Recall:</strong></p><p>Recall = TP/(TP​+FN) = 50/(50​+10) = 50/60 ​≈ 0.83</p><p><strong>F1 Score:</strong></p><p>F1=2 * (Precision * Recall)/(Precision+Recall​) = 2* (0.91 * 0.83)/(0.91+0.83)​≈0.87</p><p>Understanding the confusion matrix and the metrics derived from it, such as precision, recall, and F1 score, is crucial for evaluating the performance of classification models. These metrics provide insights into different aspects of the model’s performance, helping you make informed decisions about model improvements and understand trade-offs between different types of errors.</p><p>When dealing with multi-class classification problems, evaluating the performance of the model becomes more complex. Micro, macro, and weighted averaging methods are used to summarise precision, recall, and F1 score across multiple classes.</p><p>Here’s a detailed explanation of each method:</p><h3>Example Calculation</h3><p>Let’s consider a multi-class classification problem with three classes (A, B, and C) and the following confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNzrk5xi3lM6_vKtCwKqGA.png" /></figure><ul><li><strong>True Positives (TP):</strong> Diagonal elements [50, 40, 45]</li><li><strong>False Positives (FP):</strong> Column sums minus the diagonal [15, 4, 6]</li><li><strong>False Negatives (FN):</strong> Row sums minus the diagonal [3, 15, 7]</li></ul><p><strong>Precision, Recall, and F1 Score for each class:</strong></p><ul><li>Class A: Precision = 50 / (50 + 15) = 0.77, Recall = 50 / (50 + 3) = 0.94, F1 = 2 * (0.77 * 0.94) / (0.77 + 0.94) ≈ 0.85</li><li>Class B: Precision = 40 / (40 + 4) = 0.91, Recall = 40 / (40 + 15) = 0.73, F1 = 2 * (0.91 * 0.73) / (0.91 + 0.73) ≈ 0.81</li><li>Class C: Precision = 45 / (45 + 6) = 0.88, Recall = 45 / (45 + 7) = 0.87, F1 = 2 * (0.88 * 0.87) / (0.88 + 0.87) ≈ 0.88</li></ul><p><strong>Macro-Averaged Metrics:</strong></p><ul><li>Precision (Macro) = (0.77 + 0.91 + 0.88) / 3 ≈ 0.85</li><li>Recall (Macro) = (0.94 + 0.73 + 0.87) / 3 ≈ 0.85</li><li>F1 Score (Macro) = (0.85 + 0.81 + 0.88) / 3 ≈ 0.85</li></ul><p><strong>Weighted-Averaged Metrics:</strong></p><ul><li>Weights (support): Class A = 53, Class B = 55, Class C = 52</li><li>Precision (Weighted) = (53 * 0.77 + 55 * 0.91 + 52 * 0.88) / (53 + 55 + 52) ≈ 0.85</li><li>Recall (Weighted) = (53 * 0.94 + 55 * 0.73 + 52 * 0.87) / (53 + 55 + 52) ≈ 0.84</li><li>F1 Score (Weighted) = (53 * 0.85 + 55 * 0.81 + 52 * 0.88) / (53 + 55 + 52) ≈ 0.85</li></ul><p><strong>Micro-Averaging:</strong> Considers the overall performance by aggregating all the classes’ true positives, false positives, and false negatives.</p><p><strong>Macro-Averaging:</strong> Treats all classes equally by averaging the metric scores for each class, which may not account for class imbalance.</p><p><strong>Weighted-Averaging:</strong> Accounts for class imbalance by weighting the metric scores for each class by the number of true instances in each class.</p><p>Choosing the appropriate averaging method depends on the specific use case and the importance of class balance in the dataset.</p><h3><strong>Why We Need Metrics for Calculating Clustering Accuracy</strong></h3><p>Clustering is an unsupervised learning technique used to group similar data points together. Unlike supervised learning tasks where the model’s performance can be evaluated against a set of ground truth labels, clustering does not have predefined labels. This makes evaluating the accuracy of clustering algorithms challenging.</p><p>However, it is crucial to measure the effectiveness of clustering algorithms to:</p><ol><li><strong>Compare Different Algorithms:</strong> Determine which clustering algorithm performs best for a given dataset.</li><li><strong>Parameter Tuning:</strong> Adjust hyper-parameters to improve the clustering performance.</li><li><strong>Validate Results:</strong> Ensure that the clustering results are meaningful and consistent with the underlying data structure.</li></ol><p>Several metrics have been developed to evaluate the performance of clustering algorithms. These metrics can be broadly categorised into internal and external evaluation metrics.</p><h4>Internal Evaluation Metrics</h4><p>These metrics do not require ground truth labels and evaluate the clustering based on the inherent properties of the data.</p><p><strong>1. Silhouette Score:</strong></p><ul><li><strong>Definition:</strong> Measures how similar an object is to its own cluster (cohesion) compared to other clusters (separation).</li><li><strong>Range:</strong> -1 to 1, where higher values indicate better-defined clusters.</li><li><strong>Formula:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*JGktlxF_Wrr9rayQvUJq_A.png" /></figure><p>where a(i) is the average distance between a sample and all other points in the same cluster, and b(i) is the average distance between a sample and all points in the nearest cluster.</p><p><strong>2. Davies-Bouldin Index:</strong></p><ul><li><strong>Definition:</strong> Measures the average similarity ratio of each cluster with the cluster that is most similar to it.</li><li><strong>Range:</strong> 0 to infinity , where lower values indicate better clustering.</li><li>Formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*1igw7un8M70smfsD-FcLXg.png" /></figure><p>where s<em>i</em> and s<em>j </em>are the average distances between each point in a cluster and the cluster centroid, and d<em>ij</em> is the distance between cluster centroids.</p><p><strong>3. Dunn Index:</strong></p><ul><li><strong>Definition:</strong> Measures the ratio of the minimum inter-cluster distance to the maximum intra-cluster distance.</li><li><strong>Range:</strong> Higher values indicate better clustering.</li><li><strong>Formula:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*xRplPz8zGoZajfcxCxgbDw.png" /></figure><p>where δ(C<em>i</em>,C<em>j</em>) is the distance between clusters <em>i </em>and<em> j</em>, and Δ(C<em>k</em>) is the diameter of cluster k.</p><h4>External Evaluation Metrics</h4><p>These metrics require ground truth labels and evaluate the clustering based on how well the clusters match the actual labels.</p><p><strong>1. Adjusted Rand Index (ARI):</strong></p><ul><li><strong>Definition:</strong> Measures the similarity between the clustering results and the ground truth labels, adjusted for chance.</li><li><strong>Range:</strong> -1 to 1, where 1 indicates perfect clustering, 0 indicates random clustering, and negative values indicate worse-than-random clustering.</li><li><strong>Formula:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ARLettjCFVbVbAOLl8tlWQ.png" /></figure><p>where RI is the Rand Index.</p><p>The Rand Index (RI) is an external evaluation metric used to assess the similarity between two data clusterings. It is particularly useful for evaluating clustering results when ground truth labels are available. The RI measures the agreement between the predicted clusters and the true clusters by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in both the predicted and true clusterings.</p><p>The Rand Index is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*VnUpz19uwnvr86n-N3ETIQ.png" /></figure><p>where:</p><ul><li>a is the number of pairs of elements that are in the same cluster in both the predicted and true clusterings (True Positive, TP).</li><li>b is the number of pairs of elements that are in different clusters in both the predicted and true clusterings (True Negative, TN).</li><li>c is the number of pairs of elements that are in the same cluster in the predicted clustering but in different clusters in the true clustering (False Positive, FP).</li><li>d is the number of pairs of elements that are in different clusters in the predicted clustering but in the same cluster in the true clustering (False Negative, FN).</li></ul><p>The Rand Index ranges from 0 to 1.</p><ul><li>RI = 1 indicates perfect agreement between the predicted and true clusterings.</li><li>RI = 0 indicates no agreement between the predicted and true clusterings.</li><li>Higher values indicate better clustering performance.</li></ul><p><strong>2. Fowlkes-Mallows Index (FMI):</strong></p><ul><li><strong>Definition:</strong> Measures the geometric mean of precision and recall for the clustering results.</li><li><strong>Range:</strong> 0 to 1, where 1 indicates perfect clustering.</li><li><strong>Formula:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*IagOXyjsDGC0a519u4yQXA.png" /></figure><p>where TP, FP, and FN are the counts of true positives, false positives, and false negatives, respectively.</p><h3><strong>Conclusion</strong></h3><p>Understanding the various loss functions and metrics is fundamental to developing effective machine learning models. In classification tasks, metrics like cross-entropy loss, hinge loss, F1 score.</p><p>In clustering, metrics such as the silhouette score, Davies-Bouldin index, and adjusted Rand index are essential for assessing the quality of the grouping.</p><p>By leveraging these loss functions and metrics, data scientists can fine-tune their models to achieve better performance and more accurate predictions.</p><p>Evaluating the accuracy of clustering algorithms is essential to ensure that the resulting clusters are meaningful and useful. Various metrics, both internal and external, provide different perspectives on clustering performance. Choosing the right metric depends on the specific goals and characteristics of the clustering task. Understanding these metrics allows practitioners to make informed decisions about the effectiveness of their clustering algorithms and to refine their models for better performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5e2f35ddc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Machine Learning Loss Functions and Evaluation Metrics Explained: PART 1…]]></title>
            <link>https://medium.com/@rakeshbobbati_85122/comprehensive-guide-to-machine-learning-loss-functions-and-evaluation-metrics-explained-part-1-3e16e495c549?source=rss-02d6b6b23627------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e16e495c549</guid>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Rakeshbobbati]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 12:36:15 GMT</pubDate>
            <atom:updated>2024-06-14T11:38:14.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*e_Zb5iGcZ9HbsHmhjZLFng.png" /></figure><h3><strong>Comprehensive Guide to Machine Learning Loss Functions and Evaluation Metrics Explained: PART 1 (Regression).</strong></h3><p>Loss functions in machine learning are mathematical functions used to quantify the difference between the predicted values produced by a model and the actual target values. They play a crucial role in the training process of machine learning models by guiding the optimisation algorithm in adjusting the model parameters to minimise this difference, thereby improving the model’s performance.</p><p>Here are some commonly used loss functions across different types of machine learning tasks:</p><h3><strong>MAE (mean absolute error):</strong></h3><p>Mean Absolute Error (MAE) is a widely used loss function for regression tasks that measures the average magnitude of the errors between predicted values and actual values without considering their direction. It is an intuitive and straightforward metric that quantifies how close predictions are to the actual outcomes.</p><h4>Formula</h4><p>The formula for Mean Absolute Error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*XjMnisFM-NF38IS1UoAsSw.png" /></figure><p>where: (yi​) represents the actual values. (y^i) represents the predicted values.</p><h4>Gradient of MAE</h4><p>For optimisation purposes, such as using gradient descent, it is important to understand the gradient of the MAE with respect to the predictions (y^​i​). The gradient (or derivative) of the MAE with respect to (y^​i​) is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*iULwbI8rF1iHiww5Cg_lHw.png" /></figure><p>This gradient indicates the direction and magnitude of the change needed to minimise the error for each prediction.</p><h4>Characteristics of MAE</h4><ol><li>Absolute Differences: MAE calculates the average of the absolute differences between actual and predicted values, which means it treats all errors equally, without squaring them.</li><li>Scale Dependency: The value of MAE depends on the scale of the data. If the data values are large, the MAE will also be large, and vice versa. This makes it crucial to consider the context of the data when interpreting MAE.</li><li>Linear Error Response: MAE provides a linear score that does not amplify errors, unlike Mean Squared Error (MSE), which squares the errors. This linearity makes MAE less sensitive to outliers compared to MSE.</li><li>Interpretable: MAE is easy to understand and interpret as it directly represents the average error in the same units as the original data.</li></ol><h4>Advantages</h4><ul><li><strong>Robustness to Outliers</strong>: Since MAE does not square the error terms, it is less sensitive to outliers compared to MSE. This makes it more robust in datasets with anomalies or extreme values.</li><li><strong>Interpretability</strong>: The result of MAE is in the same unit as the target variable, making it easier to interpret in practical terms.</li></ul><h4>Disadvantages</h4><ul><li><strong>Non-differentiability at Zero</strong>: MAE is not differentiable at zero, which can pose challenges for some optimisation algorithms that rely on gradient descent. This issue can be mitigated using techniques like sub-gradient methods.</li><li><strong>Equal Weight to All Errors</strong>: MAE assigns equal weight to all errors, which might not always be desirable, especially in cases where larger errors should be penalised more severely.</li></ul><p>MAE is a simple yet effective loss function for regression tasks. Its robustness to outliers and interpretability make it a popular choice in many applications. However, its limitations, such as non-differentiability at zero and equal weighting of all errors, should be considered when selecting it for specific use cases.</p><h3><strong>Mean Squared Error (MSE)</strong></h3><p>Mean Squared Error (MSE) is one of the most commonly used loss functions in regression tasks within machine learning. It measures the average of the squares of the errors — that is, the average squared difference between the predicted values and the actual values. MSE is particularly useful because it heavily penalises larger errors, making it a sensitive measure for model performance.</p><p>The formula for Mean Squared Error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*AmxKlItDEwg2TG8dAIfVQA.png" /></figure><p>where:</p><ul><li>n is the number of observations.</li><li>(yi​) is the actual value for the i-th observation.</li><li>(y^​i​) is the predicted value for the i-th observation.</li></ul><h4>Characteristics of MSE</h4><ol><li><strong>Squared Differences</strong>: MSE calculates the average of the squared differences between actual and predicted values, which means it amplifies larger errors more than smaller ones.</li><li><strong>Scale Dependency</strong>: Similar to MAE, the value of MSE depends on the scale of the data. Larger values in the data will result in a larger MSE.</li><li><strong>Differentiability</strong>: MSE is differentiable, making it suitable for optimisation algorithms that rely on gradient descent, as the derivative of the loss function can be easily calculated.</li><li><strong>Emphasis on Larger Errors</strong>: Since the errors are squared, MSE places more emphasis on larger errors, making it more sensitive to outliers compared to MAE.</li></ol><h4>Advantages</h4><ul><li><strong>Differentiability</strong>: The MSE function is differentiable, which is advantageous for gradient-based optimisation algorithms.</li><li><strong>Penalises Larger Errors</strong>: By squaring the errors, MSE penalises larger errors more than smaller ones, which can be beneficial when large errors are particularly undesirable.</li></ul><h4>Disadvantages</h4><ul><li><strong>Sensitivity to Outliers</strong>: The squaring of errors makes MSE very sensitive to outliers. A single large error can disproportionately affect the MSE, leading to skewed performance metrics.</li><li><strong>Interpretation</strong>: Unlike MAE, the result of MSE is not in the same unit as the original data (it’s in squared units), which can make interpretation less intuitive.</li></ul><p>In machine learning model training, particularly for regression tasks, MSE is often used as the loss function to optimise. During training, the model parameters are adjusted iteratively to minimise the MSE, thereby improving the model’s predictive accuracy. The gradient of the MSE with respect to the model parameters is calculated and used to update the parameters in the direction that reduces the MSE.</p><p>Mean Squared Error is a fundamental loss function in machine learning, especially for regression tasks. Its sensitivity to larger errors can be both an advantage and a disadvantage, depending on the context. While it is easy to implement and differentiable, making it suitable for gradient descent optimization, its interpretation can be less intuitive due to the squaring of errors. Overall, MSE is a powerful tool for model evaluation and training, but care must be taken to handle outliers appropriately.</p><h3><strong>Huber Loss</strong></h3><p>Huber Loss is a loss function used in regression that combines the best properties of Mean Squared Error (MSE) and Mean Absolute Error (MAE). It is less sensitive to outliers in data than the squared error loss, making it more robust for regression tasks with noisy data. The Huber Loss is quadratic for small errors and linear for large errors, controlled by a parameter δ.</p><h4>Formula</h4><p>The Huber Loss is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*wDUWDWANS1UQgB8ySlcSsA.png" /></figure><p>where:</p><ul><li>a= (yi​−y^​i​) is the residual (difference between the actual value and the predicted value).</li><li>δ is a threshold parameter that determines the point at which the loss function transitions from quadratic to linear.</li></ul><p>For a dataset with n observations, the Huber Loss can be calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*gu-s1dtIijjNHg8yxv45IA.png" /></figure><h4>Characteristics of Huber Loss</h4><ol><li><strong>Robustness to Outliers</strong>: The Huber Loss is less sensitive to outliers compared to MSE because it transitions to a linear loss for large errors, reducing the impact of these large deviations.</li><li><strong>Quadratic for Small Errors</strong>: For errors smaller than δ, the Huber Loss behaves like MSE, providing a smooth and continuous gradient which is advantageous for optimisation.</li><li><strong>Linear for Large Errors</strong>: For errors larger than δ, the Huber Loss behaves like MAE, mitigating the influence of outliers by not squaring the large errors.</li></ol><h4>Advantages Over MSE and MAE</h4><ol><li><strong>Combines the Strengths of MSE and MAE</strong>: MSE penalises large errors more than MAE, making it sensitive to outliers. MAE treats all errors equally, which can be less informative for optimisation. Huber Loss balances these by being quadratic for small errors (like MSE) and linear for large errors (like MAE).</li><li><strong>Differentiability</strong>: Huber Loss is differentiable everywhere, including at the transition point, unlike MAE which is not differentiable at zero. This property makes it suitable for gradient-based optimisation algorithms.</li><li><strong>Robustness to Outliers</strong>: The linear behaviour for large errors reduces the impact of outliers, making Huber Loss more robust than MSE in the presence of noisy data.</li><li><strong>Parameter Tuning (δ)</strong>: The parameter δ allows flexibility to control the sensitivity of the loss function to outliers. By adjusting δ, one can tune the loss function to behave more like MSE or MAE depending on the specific requirements of the problem.</li></ol><p>Huber Loss is a versatile and robust loss function that effectively combines the strengths of MSE and MAE. Its ability to handle outliers while providing a smooth gradient makes it an excellent choice for many regression tasks. By tuning the δ parameter, Huber Loss can be adapted to different types of data and requirements, offering flexibility and robustness in model training and evaluation.</p><h3>Log-Cosh Loss Function</h3><p>Log-Cosh Loss is a loss function used in regression tasks, providing a balance between Mean Squared Error (MSE) and Mean Absolute Error (MAE). It is based on the hyperbolic cosine function and is designed to be both robust to outliers and smooth for optimisation purposes. The function is particularly useful when the distribution of errors includes a mix of small and large errors.</p><h4>Formula</h4><p>The formula for Log-Cosh Loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*me8FU_ptYTqjNjgK0BFy4w.png" /></figure><p>where:</p><ul><li>cosh⁡(x)=(e^x+e^(−x) )/2 is the hyperbolic cosine function.</li><li>yi​ is the actual value.</li><li>y^​i​ is the predicted value.</li><li>n is the number of observations.</li></ul><p>The Log-Cosh Loss is defined as the logarithm of the hyperbolic cosine of the prediction error. The hyperbolic cosine function approximates x²/2​ for small values of x and ∣x∣−log⁡(2) for large values of x. This means the Log-Cosh Loss behaves similarly to the squared error for small errors and to the absolute error for large errors.</p><h4>Characteristics of Log-Cosh Loss</h4><ol><li><strong>Smooth and Differentiable</strong>: Log-Cosh Loss is smooth and differentiable, making it suitable for optimisation with gradient descent algorithms.</li><li><strong>Robustness to Outliers</strong>: It is less sensitive to outliers compared to MSE, as it does not penalise large errors as heavily.</li><li><strong>Balanced Behaviour</strong>: Combines the quadratic nature of MSE for small errors and the linear nature of MAE for large errors, providing a balanced approach.</li></ol><h4>Advantages</h4><ol><li><strong>Smooth Gradient</strong>: The Log-Cosh Loss provides a smooth gradient, making it more stable and reliable for optimization algorithms. This can lead to faster convergence and better model performance.</li><li><strong>Robustness to Outliers</strong>: By approximating MAE for large errors, Log-Cosh Loss reduces the influence of outliers on the model, leading to more robust regression results.</li><li><strong>Balanced Error Treatment</strong>: The loss function treats small and large errors differently, effectively balancing the advantages of both MSE and MAE. This helps in handling data with a mix of error magnitudes.</li></ol><h4>Disadvantages</h4><ol><li><strong>Computational Complexity</strong>: The computation of the hyperbolic cosine function and its logarithm is more complex compared to the simple arithmetic operations in MSE and MAE. This can lead to slightly increased computational overhead.</li><li><strong>Less Intuitive Interpretation</strong>: The Log-Cosh Loss values are less intuitive to interpret compared to MSE and MAE, as they do not directly correspond to average error magnitudes in the original data units.</li></ol><p>Log-Cosh Loss is applicable in various regression tasks, particularly when:</p><ul><li>The data contains outliers that need to be handled robustly.</li><li>A smooth and stable loss function is required for gradient-based optimisation.</li><li>A balance between penalising small and large errors is desired.</li></ul><p>Log-Cosh Loss is a versatile and robust loss function that effectively balances the properties of MSE and MAE. Its smooth gradient and reduced sensitivity to outliers make it an excellent choice for many regression tasks. While it may have slightly higher computational complexity and less intuitive interpretation, its advantages often outweigh these drawbacks, especially in scenarios with a mix of small and large errors.</p><h3>Evaluation Metrics in Regression</h3><p>Regression models predict continuous outcomes, and evaluating their performance requires specific metrics that measure how well the predictions match the actual values. The choice of metric can influence model selection and tuning, and understanding each metric’s characteristics is crucial for making informed decisions. Here’s a detailed view of common evaluation metrics used in regression</p><h3><strong>Mean Squared Error (MSE)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*HoHNUvigIz-F7QONH4hJlQ.png" /></figure><p>It can also be used to evaluate a Model. Though it is not robust to outlier, it can be selected with product need.</p><p><strong>Explanation:</strong></p><ul><li>MSE measures the average of the squares of the errors between predicted and actual values.</li><li>It penalizes larger errors more heavily due to squaring the differences.</li></ul><p><strong>Advantages:</strong></p><ul><li>Differentiable, making it suitable for gradient-based optimization.</li><li>Sensitive to large errors, which can highlight significant model inaccuracies.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Highly sensitive to outliers.</li><li>The value is not in the same unit as the original data, making interpretation less intuitive.</li></ul><h3><strong>Root Mean Squared Error (RMSE)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*dJHA0XMN9N2nI2U5JICzXA.png" /></figure><p>Most used evaluation metric in linear regression fit. RMSE is the square root of MSE, bringing the error metric back to the same unit as the original data.</p><p><strong>Advantages:</strong></p><ul><li>Easier to interpret than MSE because it’s in the same unit as the target variable.</li><li>Penalises large errors but less sensitive than MSE due to the square root.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Still sensitive to outliers.</li><li>Can be less intuitive if the data has large variations.</li></ul><h3><strong>Mean Absolute Error (MAE)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*LCYcNxEpZ6MIeUdIXBGGGw.png" /></figure><p>MAE measures the average of the absolute errors between predicted and actual values. It treats all errors equally without squaring them.</p><p><strong>Advantages:</strong></p><ul><li>Robust to outliers since it does not square the errors.</li><li>The value is in the same unit as the original data, making it easy to interpret.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Not differentiable at zero, which can complicate optimisation.</li><li>Less sensitive to larger errors compared to MSE and RMSE.</li></ul><h3><strong>Mean Absolute Percentage Error (MAPE)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*OD3xkNXckIS_m8zjGvgFDw.png" /></figure><p>MAPE measures the average absolute percentage error between predicted and actual values.It provides an intuitive percentage error metric.</p><p><strong>Advantages:</strong></p><ul><li>Easy to interpret as it gives a percentage error.</li><li>Useful for comparing model performance across different datasets.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Undefined when actual values are zero.</li><li>Can be misleading if actual values are very small, leading to very high percentage errors.</li></ul><h3><strong>R-squared (Coefficient of Determination)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*BF9YBqYOLtfjQB1bIch6nw.png" /></figure><p>R-squared measures the proportion of variance in the dependent variable that is predictable from the independent variables.It compares the model’s performance to that of a simple mean-based model.</p><p><strong>Advantages:</strong></p><ul><li>Provides a normalised measure (between 0 and 1) of model fit.</li><li>Easy to interpret: a higher R-squared indicates a better fit.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Can be misleading for small sample sizes or models with many predictors.</li><li>Does not indicate whether the model predictions are biased or whether the model is the best among different models.</li></ul><h3><strong>Adjusted R-squared</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*N6uLlc-FF4i5ZUc1uujZtQ.png" /></figure><p>Adjusted R-squared adjusts the R-squared value based on the number of predictors in the model. It penalises the addition of non-significant predictors.</p><p><strong>Advantages:</strong></p><ul><li>More accurate than R-squared for models with multiple predictors.</li><li>Prevents overestimation of model performance.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Can still be misleading if the model includes irrelevant predictors.</li><li>Not always easy to interpret if the sample size is very small.</li></ul><h3><strong>Explained Variance Score</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*BXO3nX_nRuyUjZ5DgVJAJA.png" /></figure><p>Measures the proportion of variance explained by the model. Similar to R-squared but does not penalise the model for the number of predictors.</p><p><strong>Advantages:</strong></p><ul><li>Provides a normalised measure (between 0 and 1) of model fit.</li><li>Useful for comparing models.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Does not penalise for overfitting.</li><li>Can be less intuitive for small datasets.</li></ul><h3>Conclusion</h3><p>Choosing the right evaluation metric for a regression model depends on the specific context and goals of the analysis. While MSE and RMSE are sensitive to outliers and useful for highlighting large errors, MAE offer robustness. R-squared and Adjusted R-squared provide insights into the model fit, and metrics like MAPE offer interpretability in percentage terms. Understanding the strengths and limitations of each metric is essential for making informed decisions in model evaluation and selection.</p><p><em>In The next topic I will discuss about loss functions of classification models as well as clustering models and their evaluation metrics</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e16e495c549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Driving Innovation in Data Science: A Guide to Creative Solutions]]></title>
            <link>https://medium.com/@rakeshbobbati_85122/foster-innovative-solutions-as-a-data-scientist-d5b9255fde13?source=rss-02d6b6b23627------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5b9255fde13</guid>
            <dc:creator><![CDATA[Rakeshbobbati]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 06:03:00 GMT</pubDate>
            <atom:updated>2024-06-03T06:15:46.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*KGVUHsvi7OgDb43Vtx-nNg.jpeg" /></figure><p>Innovation is at the heart of data science, driving advancements and uncovering new insights from data. To foster innovative solutions, data scientists need to adopt various strategies that encourage curiosity, experimentation culture, visual thinking, cross-discipline learning, team diversity and reverse engineering. Here are six key steps to help data scientists cultivate an innovative mindset and approach their work creatively.</p><h3>Encourage Curiosity</h3><p>Curiosity is the engine of innovation. As a data scientist, fostering a curious mindset means constantly questioning the status quo and exploring data beyond conventional boundaries. When faced with a problem, don’t just settle for the first solution that comes to mind. Dive deeper into the data, ask “what if” questions, and consider multiple angles. This approach can reveal hidden patterns and insights that a less curious mind might miss, leading to more creative and effective solutions.</p><p>Curiosity should come naturally to data scientists. Asking the right questions is key to understanding, exploring, and deriving insights from raw data. When starting a project, understanding the goal, feasibility, and objective is essential for achieving the best results. Incorporating practices such as design thinking methodologies can be beneficial:</p><ul><li><strong>Empathise:</strong> Understand the needs of the stakeholders.</li><li><strong>Define:</strong> Clearly articulate the problem.</li><li><strong>Ideate:</strong> Brainstorm potential solutions.</li><li><strong>Prototype:</strong> Develop preliminary models or solutions.</li><li><strong>Test:</strong> Evaluate and refine the prototypes.</li></ul><p>Fostering innovative solutions involves:</p><ul><li><strong>Experimentation:</strong> Embrace trial-and-error methods, allowing room for unconventional techniques.</li><li><strong>Creative Problem-Solving:</strong> Use imagination and lateral thinking to explore unique solutions.</li><li><strong>Interdisciplinary Collaboration:</strong> Engage with experts from diverse fields to gain new insights</li><li><strong>Diverse Perspectives:</strong> Encourage unconventional ideas by considering viewpoints beyond traditional approaches.</li></ul><h3>Experimentation Culture</h3><p>Creating a culture of experimentation is vital for innovation. Encourage the practice of testing hypotheses and building prototypes without the fear of failure. Use tools like A/B testing or machine learning algorithms to explore various scenarios and outcomes. This trial-and-error process is essential in discovering what works best and often leads to unexpected solutions that could revolutionise your approach to data science.</p><p>From experience, encouraging team members to explore unconventional approaches and embrace failure as part of the learning process can lead to breakthrough insights and creative solutions. By fostering an environment where curiosity is encouraged and ideas are welcomed, data scientists can push the boundaries of traditional thinking and uncover innovative solutions that drive business success.</p><p>To cultivate an experimentation culture:</p><ul><li><strong>Embrace a Growth Mindset:</strong> View failures as learning opportunities and encourage experimentation without fear of repercussions.</li><li><strong>Establish Clear Goals:</strong> Define clear objectives and success metrics.</li><li><strong>Empower Data Scientists:</strong> Provide resources, autonomy, and support for meaningful experiments.</li><li><strong>Promote Collaboration:</strong> Foster cross-functional collaboration to generate diverse perspectives.</li><li><strong>Encourage Rapid Prototyping:</strong> Build and test prototypes quickly to gather feedback and iterate efficiently.</li><li><strong>Leverage Experimentation Tools:</strong> Utilise tools and platforms to streamline experimentation.</li><li><strong>Celebrate Successes and Learn from Failures:</strong> Recognise and learn from both successes and failures.</li></ul><h3>Visual Thinking</h3><p>Visual thinking can be a powerful tool for data scientists looking to break out of traditional analysis patterns. Instead of relying solely on numerical data and text-based reports, use visualizations like graphs, charts, and mind maps to uncover relationships and trends in the data. These visual tools can help you see the bigger picture and generate ideas that might not be apparent through standard data examination methods.</p><p>While visual thinking provides clarity, it’s important to avoid being swayed by attractive images alone. Over-reliance on visualizations can obscure the intricacies of raw data, leading to overly simplistic inferences. Balancing analytical integrity with aesthetic appeal ensures that interpretations are based on reality and not just their visual representation.</p><p>Use visual thinking to:</p><ul><li><strong>Transform Data into Insights:</strong> Utilise visualisation techniques to uncover patterns, trends, and anomalies.</li><li><strong>Communicate Complex Ideas:</strong> Convey insights clearly and persuasively using charts, graphs, and interactive visualisations.</li><li><strong>Generate Creative Solutions:</strong> Explore new perspectives and generate innovative solutions through visual brainstorming and ideating.</li><li><strong>Facilitate Collaboration:</strong> Use visualisations as a common language for discussion and decision-making.</li><li><strong>Enhance Problem-Solving:</strong> Visualise problems from different angles to identify new approaches and solutions.</li><li><strong>Tell Compelling Stories:</strong> Craft compelling data narratives with visualisations.</li></ul><h3>Cross-Discipline Learning</h3><p>One of the most effective ways to think outside the box is by integrating knowledge from various disciplines. Data science isn’t isolated; it’s at the intersection of statistics, computer science, and domain expertise. By learning from fields such as psychology, economics, or even art, you can apply different frameworks and methodologies to your data projects. This cross-pollination of ideas can spark innovative approaches that stand out in a sea of conventional data analyses.</p><p>Approaches common in one field can surprisingly perform well in another. For example, in a medical-related dataset, understanding the specific meanings of columns and images is crucial for accurate analysis. The knowledge from the medical field can provide context and depth to data science applications, leading to more precise and insightful conclusions.</p><h3>Leveraging diversity in team</h3><p>Diversity within your team can be a goldmine for innovative thinking. Collaborate with colleagues who have different backgrounds, skills, and perspectives. Each team member can contribute unique insights that might not occur to others, leading to a richer understanding of the problem at hand. This collective intelligence can drive you to explore new directions in your data science projects and foster solutions that are both novel and effective.</p><p>Having a team with different educational backgrounds, such as various engineering disciplines, and firm knowledge of data sciences (statistics and math) provides a broader perspective on problem-solving. For instance, a team member with engineering, math, and stats expertise might offer more innovative solutions than a person with a purely computer science background when faced with a specific problem.</p><p>Encourage diverse expertise by:</p><ul><li><strong>Seeking Diverse Expertise:</strong> Assemble a team with varied backgrounds, experiences, and educational disciplines.</li><li><strong>Encouraging Open Communication:</strong> Create a safe space for sharing ideas.</li><li><strong>Embracing Different Perspectives:</strong> Value and incorporate diverse viewpoints for a holistic understanding.</li><li><strong>Leveraging Collective Intelligence:</strong> Harness the power of the team to generate creative solutions.</li><li><strong>Promoting Cultural Sensitivity:</strong> Foster an inclusive environment.</li><li><strong>Addressing Unconscious Bias:</strong> Recognize and mitigate biases.</li><li><strong>Empowering Team Members:</strong> Encourage active participation and decision-making.</li><li><strong>Celebrating Successes:</strong> Acknowledge and celebrate the team’s achievements.</li></ul><h3>Reverse Engineering</h3><p>Reverse engineering involves taking apart successful projects or models to understand how they work. By dissecting the components and processes that led to success, you can gain insights into the underlying principles and potentially apply them in innovative ways to your own projects. This technique can be especially useful when you’re stuck or need to solve a problem already addressed in a different context or industry.</p><p>Reverse engineering is valuable for fostering innovation. It entails deconstructing successful projects or models to comprehend their inner workings fully. By extracting valuable insights into the underlying principles, you can creatively apply them to your own projects, leading to novel solutions.</p><p>Unlocking the secrets of success isn’t just about admiration — it’s about deconstructing the puzzle to reveal the underlying principles. Reverse engineering empowers data scientists to glean inspiration from past triumphs and adapt them in groundbreaking ways.</p><p>Stay connected with the academic community and current research to introduce new methodologies not yet commercialised. Collaboration with university research groups, organising hackathons, and dedicated innovation sprints can stimulate creativity under time constraints.</p><p>In summary, fostering innovative solutions as a data scientist involves embracing curiosity, cross-discipline learning, leveraging team diversity, creating an experimentation culture, utilising visual thinking, and practicing reverse engineering. By adopting these strategies, data scientists can push the boundaries of traditional thinking and uncover innovative solutions that drive business success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5b9255fde13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B testing with practical examples]]></title>
            <link>https://medium.com/@rakeshbobbati_85122/a-b-testing-with-practical-examples-6b0f27c50852?source=rss-02d6b6b23627------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0f27c50852</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python-data-science]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rakeshbobbati]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 19:27:06 GMT</pubDate>
            <atom:updated>2024-03-17T19:35:23.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Experiment design and result analysis post running experiment with practical examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*d3wIt2jzgm9mm9nLakvTXQ.jpeg" /></figure><p>A/B testing is a methodology for comparing two versions of a product against each other to determine which one performs better. A/B testing is essentially an experiment where two or more variants of a product are shown to users at random, and statistical analysis is used to determine which variation performs better for a given conversion goal.</p><p>A/B testing helps a data scientist to answer does a change <strong>(X)</strong> in product causes any improvement on business metric <strong>(Y)</strong></p><p>General approach for A/B testing</p><p>Assume that a we decided to run an experiment on our blogging website where users can subscribe for reading our blogs. We changed the subscribe button position from bottom right to top right. Now we want to test, does changing that button position has improved our subscriptions or not.</p><p>Example 1 : Assume that landing page of our blogging website has 160000 monthly visitors among them 800 click the subscribe button (CTA = Click through action) and finally 500 of them later converted to paying accounts. You would like to roll out the experiment to 30% of users who visit our page monthly. How this experiment can potentially influence Monthly Recurring Revenue (MRR) if Average Revenue Per Account (ARPA) is 50 rupees.</p><ol><li>ARPA = MRR/ (number of paying users)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suHAARZXUIDLEZ2uw8U6Ig.png" /></figure><p>MRR = 25000 i.e ( 50 x 500 )</p><p><strong>2.</strong> Experiment Sample size calculation as we decided to roll the experiment on 30% of population sample size will be 48000 from total 160000. Now we show our old landing page where button is at the bottom to half the population which we will define as (C<strong>ontrol group</strong>). and other half to our new landing page where bottom is at the top right (T<strong>est group</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*CAuhRghoP9x40U7peh31Bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*jPx4EI4erwDfoYMM_Fo8FA.png" /></figure><p><strong>3. Statistical Specifications</strong></p><ul><li><strong>Null hypothesis</strong>: There is no true difference in the conversion rate (<strong>CR</strong>) of the Control group &amp; the Test variant.</li><li><strong>Alternate Hypothesis</strong>: Test variant will convert better than the Control group.</li><li><strong>p-vlaue: </strong>Usually assumed as<strong> 0.05</strong> i.e. Confidence Level = <strong>95%</strong> which gives <strong>type 1 error &lt;=5%</strong> (<strong>alpha</strong>) , This is Ability to reject true negative. This tells us that we can say with a 95% confidence interval that the Test variant actually converts better than the Control group and the results are not by chance.</li><li><strong>Power</strong>: Usually assumed as <strong>80% </strong>with p-value=0.05. <strong><em>type 2 error &lt;= 20%(beta). </em></strong><em>which is</em><strong><em> </em></strong><em>Ability to identify true positive. </em>There is still a <strong>20%</strong> probability that that the Test group does not convert better than the Control group<strong>.</strong></li></ul><p>4. <strong><em>Scenarios</em></strong></p><ul><li>Here, we will be creating scenarios assuming a certain minimum detectable effect (<strong>MDE</strong>) in the landing to paying account conversion rate.</li><li>We will be calculating the minimum experiment duration for these different scenarios.</li><li>We are assuming that the data is normally distributed as we have a significant number of conversions.</li></ul><p><strong><em>Scenario 1 : MDE = 10%.</em></strong></p><p><em>St dev = SQRT(CR * (1-CR)/N) .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*GtDRf0JAJwMtE6990AJXNA.png" /></figure><p><em>Sample Size (N) = 2 * total number of variations * (Z1 + Z2)² * (STD/CR* Uplift)²</em></p><p><em>Z1 = z score for type 1 error = 0.05. For 5% significance, Z1 = 1.96</em></p><p><em>Z2 = z score for power. For 80% power, Z2 = 0.84</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*Ph3nM2gT5eF7Lc3JwJivsA.png" /></figure><p>Now this is an unrealistic scenario. To be able to detect a minimum 10% uplift, we would need to run the experiment for at least 4 months <strong>(208414/48000)</strong>.</p><p>This is so because the BAU conversion rate is lower. It will be quicker if we increase the MDE</p><p><strong><em>Scenario 2: MDE = 25%</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*O53ImoUbeqrWQuE8P90xdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*fowYQa0z363XyLpPT-B-RQ.png" /></figure><p>This scenario is realistic. To be able to detect a minimum of 25% uplift, we would need to run the experiment for at least 1 months</p><p>5. <strong>Conclusions</strong></p><ul><li>We need a minimum sample size of 33,347 users visiting the website in order to be able to detect a minimum uplift of 25% in the conversion rate with a confidence interval of 95%.</li><li>To achieve this sample size requirement, we need to run the experiment for at least 1 month</li><li>This experiment has the potential to increase MRR by rupees 6,250 i.e. 25% if rolled out to 100% users.</li><li>This translates to an incremental 125 paying accounts over the current run-rate of 500</li><li>MRR = CR*50, current MRR = 500*50 , Potential = 160000*(0.4/100)*50.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*G_FJ5pHln7Rcpu3El0NPdA.png" /></figure><p>I would launch the experiment as it seems like a possible scenario that we can increase the conversion rate by 25%.</p><p>Know that if we have multiple changes. In our case if we change the colour of the button or shape of the button along with position. we will know that the B variant has increased the CR but we cannot know that which change contributed to the change. We need to keep other values as constant to know which change contributed to the increase in CR</p><p>We can adjust parameters like Target audience to reduce MDE to suit our needs. We can leverage p-value also but bear in mind that if we adjust p-value the beta value changes accordingly as they are inversely proportional to each other. Below figure shows what alpha, beta and power look like in a graph and illustrates some of the relationships between them. Remember, alpha and beta represent the probabilities of Type I and Type II Errors, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1TZm-3fpjqg1AdwZklWMw.png" /></figure><p>Example 2: Hypothesis testing with Python code.</p><p>Let us assume that we have 2 car pricing models which give used car prices for 10 cars. Now we have to detect which model is giving better prices.</p><pre>from numpy.random import normal<br><br>car_price_model_A = normal(100, 16, 10) # mean = 100 ,std = 16 ,count = 10 <br>car_price_model_B = normal(125, 16, 10) # mean = 125 ,std = 16 ,count = 10<br><br># Randomly generated values for this time are<br># A = [113.0874069904511, 95.6701406433734,123.40198276194985,79.38701926616444,<br>#      ,123.64545796310011,122.12755280250579,122.57846952020384,110.48966803028092,<br>#     ,110.37107839196443,87.92792809901299]<br> <br># B = [111.5163868976799,116.1807367689398,151.49173056069063,153.03420602326733,<br>#     ,130.70767579533174,153.26516127915156,118.5982270794405,141.76294271181928,<br>#    ,149.5273122296966,156.26657689305398]</pre><p>From the above code we know that B model has better average price. Let us do t-test for the above data.</p><pre>import scipy<br>import pandas as pd<br>dict = { &quot;car_price&quot;:list(car_price_model_A)+list(car_price_model_B)<br>        , &quot;group&quot;: [ &quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,<br>                     &quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]}<br>df = pd.DataFrame(dict)<br><br>import scipy<br>t_stat, p_value = scipy.stats.ttest_ind(df[df[&quot;group&quot;]==&quot;A&quot;].car_price, df[df[&quot;group&quot;]==&quot;B&quot;].car_price, <br>                            axis=0, <br>                            equal_var=True, <br>                            nan_policy=&#39;propagate&#39;, <br>                            permutations=None, <br>                            random_state=None, <br>                            alternative=&#39;less&#39;, <br>                            trim=0)<br>print(t_stat, p_value)<br><br># Output is: t_stat = -3.9296390209612126 <br>#            p-value = 0.0004911735271013565<br># The p-value is &lt; 99 so price of model A being lesser than prices of B are<br># most likely true.<br># Note: if &#39;alternate&#39; = &#39;less&#39; means A &lt; B if p-value is at extreme tails &lt; 95%<br>#       if &#39;alternate&#39; = &#39;greater&#39; means A &gt; B if p-value is at extreme tails &lt; 95%</pre><p>The test result are inline i.e B prices are better than A prices</p><p>This t-test is only done if the distributions of both A and B are normal distribution with similar std values. What if std are different for A and B models. Then we perform <strong>Welch’s T-test.</strong></p><pre>import scipy<br>t_stat, p_value = scipy.stats.ttest_ind(df[df[&quot;group&quot;]==&quot;A&quot;].car_price, df[df[&quot;group&quot;]==&quot;B&quot;].car_price, <br>                            axis=0, <br>                            equal_var=False, <br>                            nan_policy=&#39;propagate&#39;, <br>                            permutations=None, <br>                            random_state=None, <br>                            alternative=&#39;less&#39;, <br>                            trim=0)<br># parameter &#39;equal_var&#39; = False for Welch&#39;s T-test. means A and B has different <br>#                         variations</pre><p><strong>Shapiro-Wilk test</strong> is a test of normality, it determines whether the given sample comes from the normal distribution or not.</p><pre>from numpy.random import poisson<br>from scipy.stats import shapiro<br> <br>data = poisson(5, 200)<br> <br># conduct the  Shapiro-Wilk Test<br>shapiro(data)<br># ShapiroResult(statistic=0.9628055095672607, pvalue=4.027883187518455e-05)<br></pre><p>Since tests p-value is less than the alpha(0.05) then we reject the null hypothesis i.e. we have sufficient evidence to say that sample does not come from a normal distribution.</p><pre>from numpy.random import normal<br>from scipy.stats import shapiro<br> <br>data = normal(125, 16, 10)<br> <br># conduct the  Shapiro-Wilk Test<br>shapiro(data)<br><br># ShapiroResult(statistic=0.9537200331687927, pvalue=0.7125772833824158)</pre><p>The p-value is more than the threshold(0.05) which is the alpha(0.05) then we fail to reject the null hypothesis i.e. we do not have sufficient evidence to say that sample does not come from a normal distribution.</p><p>What if both A and B doesn’t follow <em>Normal Distribution </em>or<em> std </em>is different<em>. </em>Then we do<em> </em><strong>Mann Whitney U test.</strong></p><pre>from scipy.stats import mannwhitneyu <br># Take A and B data as <br>A =[3, 4, 2, 6, 2, 5] <br>B =[9, 7, 5, 10, 8, 6] <br>  <br># performing mann whitney test <br>stat, p_value = mannwhitneyu(A, B) <br># Level of significance <br>alpha = 0.05<br># conclusion <br>if p_value &lt; alpha: <br>    print(&#39;Reject Null Hypothesis&#39;) <br>else: <br>    print(&#39;Do not Reject Null Hypothesis&#39;)<br><br># stat=2.00, p_value=0.01<br># Reject Null Hypothesis</pre><p>If you find this article helpful to you, please <strong>follow </strong>to inspire me to publish related blogs on data science and statistics.</p><p>Thanks for your reading and feel free to leave comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0f27c50852" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>