<?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 Debanjan Saha on Medium]]></title>
        <description><![CDATA[Stories by Debanjan Saha on Medium]]></description>
        <link>https://medium.com/@dsdojo?source=rss-10981b26bbe6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aEDGMdzJbDbAWVT3mLkvgw.jpeg</url>
            <title>Stories by Debanjan Saha on Medium</title>
            <link>https://medium.com/@dsdojo?source=rss-10981b26bbe6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:56:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsdojo/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[Apple Intelligence]]></title>
            <link>https://dsdojo.medium.com/apple-intelligence-1971a6e49740?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1971a6e49740</guid>
            <category><![CDATA[apple-intelligence]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 10:09:23 GMT</pubDate>
            <atom:updated>2024-06-11T10:31:49.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a world where your Apple devices not only understand you but anticipate your needs, seamlessly integrating into your daily life to make every task effortless. Welcome to the forefront of artificial intelligence with Apple Intelligence, where cutting-edge generative models and meticulous optimization techniques converge to revolutionize user experience. By prioritizing human-centric evaluation and leveraging advanced fine-tuning methods, Apple is not just keeping pace with technological advancements but setting new standards for efficiency, safety, and usability. Dive into the world of Apple Intelligence and discover how your favorite devices are becoming smarter, more responsive, and incredibly intuitive.</p><blockquote>“Walk a mile to avoid a Fight, but when one starts, don’t hold back”</blockquote><p>Apple has always been known for its innovation and strategic planning. While other tech giants were openly competing for dominance in artificial intelligence (AI), Apple was quietly preparing behind the scenes. As we entered the 21st century, Apple recognized that the future of technology would heavily rely on hardware performance. This led to the development and release of their own custom chips, known as “Apple Silicon,” starting with the Apple M1 chip in 2020. These chips were designed to handle demanding tasks efficiently and optimize memory usage.</p><p>However, the technology landscape continued to evolve rapidly. In 2022, OpenAI introduced GPT-3.5, more commonly known as ChatGPT. This AI model quickly became a sensation, revolutionizing how people interacted with technology. ChatGPT’s popularity soared, becoming one of the most widely used online tools.</p><p>Recognizing the potential of Large Language Models (LLMs) like ChatGPT, Apple decided to invest heavily in generative AI (GenAI), dedicating a significant portion of its $3 trillion market cap to this area. Despite their efforts, Apple faced challenges related to hardware-software integration and reducing latency — the time it takes for data to travel between devices and servers. The race to optimize these language models and enhance their performance has been intense, with Apple continuously striving to lead the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dABn19BPlBAbqM_quPBcsg.png" /><figcaption>Apple Intelligence Announcement at WWDC 2024</figcaption></figure><p>Yesterday (June 10, 2024) at Worldwide Developer Conference (WWDC), Apple announced a major partnership with OpenAI. This collaboration aims to integrate ChatGPT’s advanced AI capabilities into Apple’s ecosystem, making it easier for users to access powerful AI tools directly on their devices. This partnership marks a significant step in Apple’s journey towards making AI more accessible and integrated into everyday life. Apple Intelligence is now supported on iOS 18, iPadOS 18 and macOS Sequoia.</p><h3>What is Apple Intelligence?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*apQj99CUeznkRcd-" /></figure><p>Apple Intelligence is an advanced AI-powered orchestration tool designed to help users seamlessly manage, search, and navigate their data within the Apple ecosystem. Using simple command-like instructions from the user, the agent can request Call-to-Action (CTA) capabilities, like prioritizing messages, optimizing travel routes, retrieving files, even generating cool images, and so much more. In addition to all of that, Apple Intelligence has been deeply rooted into Siri and in turn to the entire device — making Siri the most powerful than ever. This tool leverages the capabilities of LLMs while maintaining Apple’s strong emphasis on security and privacy — one of the company’s core principles.</p><p>Apple Intelligence operates through two main components:</p><ol><li><strong>On-Device LLM</strong>: For smaller tasks, Apple Intelligence uses a 100% local LLM with 3 billion parameters. This on-device model ensures that many operations can be performed quickly and securely without needing to connect to external servers.</li><li><strong>Private Cloud Compute (PCC)</strong>: For more complex tasks, Apple Intelligence taps into a larger LLM housed in what Apple calls the Private Cloud Compute (PCC) built using Apple Silicon servers. This setup allows for intensive computations while ensuring user data remains private (on-device). Apple assures that even they do not have access to the data processed in these private containers. They also claim that “<strong><em>PCC will cryptographically refuse to talk to any iPhone, iPad or Mac unless it’s software has been publicly logged for inspection</em></strong>”.</li></ol><p>Both of these components integrate seamlessly into all the data used by various apps in the Apple eco-system and can reference them directly using a graph-like structure using its semantic index and feed it to the LLM. Apple Intelligence decides which part of the computation can be done on device and only sends the rest to the PCC. This has been made possible owing to the years of effort in hardware-software optimization by Apple. By combining these two engines, Apple Intelligence provides powerful AI capabilities directly on users’ devices, enhancing functionality without compromising privacy.</p><h4>Breakdown</h4><p>Let’s try to understand the innovation in Apple Intelligence in greater depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRueu95q5vogga4l8QIKLw.png" /><figcaption>Apple Intelligence Pipeline (Source: Apple ML website)</figcaption></figure><h4>Pre-Training</h4><p>If you’re new to the world of LLMs, these models are typically trained in two main phases: pre-training and fine-tuning.</p><p><strong>Pre-training</strong> is the initial stage where the model learns from a large and diverse dataset to develop a general understanding of language. For Apple Intelligence, it uses Apple’s open-source <a href="https://github.com/apple/axlearn">AXLearn</a> framework, which is built on top of Google’s JAX (a framework for numerical computation) and XLA (Accelerated Linear Algebra, a framework for speeding up TensorFlow operations).</p><p>Here’s a breakdown of the techniques used during pre-training to optimize compute and enable massively parallel processing:</p><ul><li><a href="https://en.wikipedia.org/wiki/Data_parallelism"><strong>Data Parallelism</strong></a> — Large tasks are split into smaller, independent subtasks that can be processed simultaneously, speeding up the training process.</li><li><a href="https://colossalai.org/docs/concepts/paradigms_of_parallelism/#tensor-parallel"><strong>Tensor Parallelism (TP)</strong></a>— This model parallelism technique divides the computation of a model across multiple GPUs by splitting tensors into separate, non-overlapping pieces.</li><li><a href="https://arxiv.org/abs/2105.13120"><strong>Sequence Parallelism (SP)</strong></a> — The sequence dimension of input tensors is divided across multiple GPUs, allowing for parallel processing of sequence data.</li><li><a href="https://engineering.fb.com/2021/07/15/open-source/fsdp/"><strong>Fully Sharded Data Parallel (FSDP)</strong></a> — This method shards a model’s parameters, gradients, and optimizer states across all available GPUs, enabling efficient use of computational resources.</li></ul><p>These advanced techniques ensure that the pre-training of Apple’s models is highly optimized for performance, utilizing massively parallel processing (MPP) to achieve efficient and effective training.</p><h4>Training Data</h4><blockquote>“Data is the new Oil” — Clive Humby, 2006</blockquote><p>Apple has made it clear that the training data for their AI models comes from several sources:</p><ol><li><strong>Licensed Data</strong>: Data that Apple has legally obtained and has permission to use.</li><li><strong>Functional Data</strong>: Data that helps enhance specific features of their products.</li><li><strong>Public Data</strong>: Information from public websites, collected by AppleBot, Apple’s in-house web crawler.</li></ol><p>Apple ensures that any public website they index can choose to opt out if they do not want their data used for training purposes.</p><p>Importantly, Apple explicitly mentions “<strong><em>We never use our users’ private personal data or user interactions when training our foundation models</em></strong>”. This commitment to privacy sets Apple apart from many other tech companies.</p><p>Additionally, Apple takes extra steps to ensure the quality and safety of their training data by:</p><ul><li><strong>Removing Personal Identifiable Information (PII)</strong>: This includes sensitive information like social security numbers and credit card numbers that may have been accidentally leaked online.</li><li><strong>Filtering Out Profanity and Low-Quality Content</strong>: To prevent the model from learning anything “toxic” or inappropriate.</li><li><strong>Data Enrichment</strong>: Apple filters, transforms, and extracts features from the data, using machine learning models to identify and utilize high-quality content.</li></ul><blockquote>Garbage-In, Garbage-Out (GIGO)</blockquote><p>The principle of “Garbage In, Garbage Out” (GIGO) underscores Apple’s rigorous approach to data quality. By using high-quality, carefully vetted data, Apple ensures that their models are trained effectively, resulting in a robust and reliable AI system.</p><p>Kudos to Apple for going the extra mile to ensure their AI training data is both ethical and high-quality, contributing to their reputation as a trusted and user-centric brand.</p><h4>Post-Training</h4><p>After completing the pre-training phase, Apple further refines their models using a combination of human-annotated and synthetic data. This process, known as fine-tuning, enhances the model’s performance and accuracy.</p><p>Apple uses two innovative algorithms during post-training:</p><ol><li><strong>Rejection Sampling Fine-Tuning (RFT) Algorithm with Teacher Committee</strong>: This algorithm, introduced by <a href="https://arxiv.org/pdf/2308.01825">Yuan et al. in 2023</a>, improves the model’s mathematical reasoning by correcting reasoning paths. It is incorporated into a genetic algorithm inspired by the teacher-learner model, where multiple “<strong>teacher</strong>” models evaluate the outputs and guide the “<strong>learner</strong>” model towards better performance.</li><li><strong>Reinforcement Learning from Human Feedback (RLHF)</strong>: This technique, originally known as <a href="https://link.springer.com/chapter/10.1007/978-3-642-23780-5_30">Preference-based Reinforcement Learning</a> (PhRL) and introduced by Cheng et al. in 2011, and utilizes <a href="https://arxiv.org/abs/2005.09814">mirror descent policy optimization</a> (MDPO) and a leave-one-out advantage estimator. This method allows the model to learn and improve based on feedback from human interactions, optimizing its responses to align with human preferences.</li></ol><p>Apple reports that using these advanced algorithms significantly boosts their model’s performance compared to standard methods. By incorporating these sophisticated techniques, Apple ensures their AI models are not only powerful but also aligned with user expectations, providing more accurate and reliable results.</p><h4>Optimization</h4><p>Apple employs a range of innovative techniques to optimize their generative models for both on-device and server environments, ensuring speed and efficiency.</p><p><strong>On-Device and Server Model Optimizations</strong></p><ol><li><strong>Grouped-Query-Attention</strong> — Both on-device and server models use this technique to enhance the efficiency of attention mechanisms, which are critical for processing and generating language.</li><li><strong>Shared Input and Output Vocab Embedding Tables</strong> — By mapping embedding tensors without duplication, this technique reduces memory requirements and inference costs.<br> — On-device model vocab size: 49K tokens.<br> — Server model vocab size: 100K tokens (includes additional language and technical tokens).</li></ol><p><strong>On-Device Inference Optimizations</strong></p><ol><li><strong>Low-Bit Palletization</strong> <br>— Achieves necessary memory, power, and performance requirements by reducing the bit precision of model weights.<br> — Maintains model quality using a framework with LoRA adapters and a mixed 2-bit and 4-bit configuration, averaging 3.5 bits-per-weight.</li><li><strong>Talaria Tool</strong> — An interactive tool for model latency and power analysis, guiding the selection of optimal bit rates for each operation.</li><li><strong>Activation Quantization</strong> — Reduces the precision of activation values to save memory and increase inference speed, without significantly impacting accuracy.</li><li><strong>Embedding Quantization</strong> — Lowers the precision of embedding vectors to reduce memory usage and computation costs.</li><li><strong>Efficient Key-Value (KV) Cache Update</strong> — Optimizes the update process of the KV cache on neural engines to enhance inference speed and reduce latency.</li></ol><h4>Performance Metrics</h4><ul><li><strong>Time-to-First-Token Latency</strong>: Achieved latency of about 0.6 milliseconds per prompt token on iPhone 15 Pro.</li><li><strong>Generation Rate</strong>: Achieved a generation rate of 30 tokens per second.</li><li><strong>Token Speculation Techniques</strong>: Further enhancements in token generation rate observed when employing these techniques.</li></ul><p>These optimizations collectively ensure that Apple’s generative models are not only powerful but also highly efficient, both on-device and on their private cloud.</p><h4>Model Adaptation</h4><p>Apple’s foundation models are fine-tuned to handle everyday activities and can adapt dynamically to specific tasks. Here’s how this process works:</p><p><strong>Dynamic Specialization with Adapters</strong>:</p><ul><li>Apple uses adapters — small neural network modules — to fine-tune their models for specific tasks. These adapters can be plugged into different layers of the pre-trained model.</li></ul><p><strong>Targeted Fine-Tuning</strong>:</p><ul><li>The attention matrices, attention projection matrix, and fully connected layers in the transformer architecture’s decoding layers are adjusted using these adapters.</li><li>By fine-tuning only the adapter layers, the core parameters of the base pre-trained model remain unchanged. This approach maintains the model’s general knowledge while tailoring it to specific tasks.</li></ul><p><strong>Efficient Memory Usage</strong>:</p><ul><li>Adapter parameters are stored using 16 bits.</li><li>For the approximately 3 billion parameter on-device model, the parameters for a rank 16 adapter usually require only tens of megabytes.</li><li>Adapters can be dynamically loaded, temporarily stored in memory, and swapped as needed. This allows the model to specialize in real-time while efficiently managing memory and ensuring the system remains responsive.</li></ul><p><strong>Rapid Training and Deployment</strong>:</p><ul><li>Apple has developed an efficient infrastructure for quickly retraining, testing, and deploying adapters whenever the base model or training data is updated.</li><li>Adapter parameters are initialized using an accuracy-recovery method, ensuring they start off effectively.</li></ul><p>This approach ensures that Apple’s AI models are not only powerful but also highly adaptable, providing optimal performance for a wide range of tasks while maintaining system efficiency and responsiveness.</p><h4>Performance and Evaluation</h4><p>Apple’s generative models enhance user communication and productivity by leveraging advanced AI techniques. Human evaluation ensures these models provide a high-quality user experience.</p><p>For specific tasks like summarizing emails, Apple fine-tunes adapters using accuracy-recovery low-rank (LoRA) techniques, training on high-quality synthetic data. Evaluations with diverse, real-world datasets demonstrate significant improvements in handling various inputs, showing superior performance over standard models.</p><p>Both on-device and server models are tested on a wide range of tasks, from brainstorming to coding. Apple’s models consistently outperform competitors in human evaluations, proving more efficient and effective. The on-device model surpasses larger models in various benchmarks.</p><p>Safety and reliability are prioritized through continuous adversarial testing to mitigate risks. Instruction-following capabilities are also benchmarked, showing better performance than similarly sized models. Internal tests confirm the models’ strong writing abilities, even without specific adapters.</p><p>Apple’s approach combines advanced techniques, targeted fine-tuning, and rigorous evaluations, delivering powerful, efficient, and user-friendly AI solutions while maintaining high standards of safety and reliability.</p><h3>Connections with OpenAI</h3><p>While Apple did not explicitly talk about their degree of connections with OpenAI, but they did mention the integration of OpenAI into Siri for improved real-time language translation, and more complex tasks. Rumours have it, that the partnership of Apple with OpenAI is temporary, while Apple is gearing up its own AI foundational models to refine its own AI capabilities, which resonates with Apple’s commitment to security and privacy. We anxiously await for the press release where Apple commits to switch entirely to its in-house models, but till then, we will see the controversies and memes flowing in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIXSdADYjl6HWKDTHdxCOg.png" /><figcaption>Elon being sceptical about OpenAI</figcaption></figure><h4>Disclaimer</h4><p>All information in this article has been sourced from Apple press release at WWDC 2024: <a href="https://machinelearning.apple.com/research/introducing-apple-foundation-models">https://machinelearning.apple.com/research/introducing-apple-foundation-models</a></p><p>Don’t miss the WWDC event hosted live including YouTube: <a href="https://www.youtube.com/live/RXeOiIDNNek?si=DCzdX3yiPKCUo_IE">https://www.youtube.com/live/RXeOiIDNNek?si=DCzdX3yiPKCUo_IE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1971a6e49740" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT4-Omni is Fast! Here’s Why?]]></title>
            <link>https://dsdojo.medium.com/gpt4-omni-is-fast-heres-why-207f3b4527c4?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/207f3b4527c4</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Sat, 18 May 2024 08:44:51 GMT</pubDate>
            <atom:updated>2024-05-18T09:03:17.090Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been experimenting with the various Large Language Models (LLMs) released in recent times, but since OpenAI released GPT4 Omni (GPT4-o), I have been captivated by its capabilities. Here is a deep dive into what Omni brings to the table.</p><h3>Capabilities</h3><p>While GPT4 was quite popular and powerful, GPT4-o packs quite a punch. Here is what has improved:</p><ol><li>Generation of more coherent and detailed images from text</li><li>Browsing the web for current information. Gone are the days when ChatGPT used to say that its memory was limited by the data when it was last refreshed.</li><li>Running code snippets inside OpenAI runtime containers to ensure the accuracy of the code. Gone are the days when developers had to spend hours trying to debug the code provided by ChatGPT.</li><li>Improved Data Analytics, wherein ChatGPT can run the codes or create visualisations by itself to determine which model or visual is more appealing.</li><li>Improved memory management wherein ChatGPT can remember certain key information like birthdays, anniversaries, meetings, flight schedules, etc. that the user shares with it.</li></ol><p>While some of these features were already present in GPT4, OpenAI had been constantly experimenting with newer features for Omni and deploying them. I recall that a couple of weeks ago, I randomly asked ChatGPT about an incident that took place very recently, and it was able to accurately describe the incident. This was definitely OpenAI Canary testing their new features.</p><p>If all these advanced features don’t make ChatGPT the GOAT, it has one final trick. <strong>SPEED</strong>. Yes, you heard that right. GPT4-o is one of the fastest LLMs on the market right now. People who have had some experience working with LLMs know that Latency is a very big problem when working with LLMs (even 1/1000th the size of ChatGPT), but OpenAI has nailed this to perfection.</p><h3>Latency</h3><p>To be really honest, I was quite impressed by the inferencing speed of GPT4–o, and to understand this engineering marvel, I spent some time digging deeper into the “closed” model trying to figure out what OpenAI could have possibly done, and here are my findings:</p><ol><li>Optimized Model Architecture: They’ve fine-tuned the model architecture to balance performance and speed, employing advanced techniques like transformer optimizations and efficient layer implementations.</li><li>Hardware Acceleration: Leveraging state-of-the-art hardware, including GPUs and TPUs, helps accelerate the computation required for model inference. These specialized hardwares are designed to handle the parallel processing needs of large models efficiently.</li><li>Distributed Computing: By distributing the computation across multiple nodes and using high-speed interconnects, the system can handle large-scale data processing more efficiently.</li><li>Software Optimizations: Improvements in the software stack, including better algorithms for data handling, memory management, and parallel processing, contribute to faster inferencing times.</li><li>Caching and Preprocessing: Implementing smart caching mechanisms and efficient data preprocessing steps helps reduce the overall time required for inferencing.</li></ol><p>All of these features look promising, but it is not until we really dive into each of them to understand exactly what has changed. Be advised, this might just blow your mind.</p><h3>Optimized Model Architecture</h3><h4><strong>Sparse Attention Mechanisms</strong></h4><p>Those who have been working with Attention mechanisms for a while now know that computing Attention (self-attention) requires some degree of computation. Self-attention has quadratic complexity, which can be represented as O(dn^2), where n is the sequence length and d is the token size. Imagine the computation required for computing multi-head attention, wherein multiple such self-attention heads are calculated for every pair of tokens (including masking) in parallel.</p><p>Instead of computing attention scores for every pair of tokens, sparse attention mechanisms only focus on the most relevant tokens, reducing computational complexity. Recently, a paper was published at NeurIPS last year that introduced the concept of Dynamic Sparse Flash Attention, which seems to be a key ingredient used by OpenAI. More avid readers are encouraged to read the paper [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMpgcGQv0z7u_npuihMwvQ.png" /><figcaption>Image from Dynamic Sparse Flash Attention [1], Pagliardini et al. 2023 showing how calculating a sparse subsets of Flash Attention essentially improves computation</figcaption></figure><h4>Layer Pruning</h4><p>Pruning is not a new concept in Artificial Intelligence (AI) world. It has been there for a long time (Decision Tree optimization). Pruning in the context of Deep Learning (DL) refers to removing less critical neurons or even entire layers that contribute minimally to the final output, which helps reduce the overall model size and inference time without significantly impacting performance.</p><p>After the success of Transformer Architecture (Vaswani et al., 2017), many researchers worked on pruning the Attention Matrix [B x H x T x T], wherein some set of researchers tried pruning the attention heads [B x H’ x T x T] (Li et al., 2021 [2]), while other set of researchers (Goyal et al., 2020 [3]) tried pruning tokens (dropping entire tokens) to alter the attention matrix [B x H x T_Q x T_KV], which rapidly increased inferencing speed without compromising too much on the output accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*bZBFYRy0mL7H5eB-.png" /><figcaption>Image from PoWER-BERT, Goyal et al. 2020 showing how consecutive encoder stacks removes word vectors with lower significance levels</figcaption></figure><p>In my opinion, OpenAI has probably used some framework that has combined both of these pruning mechanisms to reduce the inferencing complexity without compromising on accuracy.</p><h4>Efficient Transformers</h4><p>The elephant in the room was definitely the quadratic complexity of self-attention, as I mentioned above. So that had to be addressed. Kitaev et al., 2019, introduced Reformer [5], which reduced the computation to O(n log n) using the Locally Sensitive Hashing (LSH) technique, which deserves a special mention, but this technique was found efficient only when the sequence lengths were larger than 2048 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*sqIstMtjaA-YjOFS.png" /><figcaption>Image from Reformer [5] displaying LSH technique reducing computation complexity</figcaption></figure><p>Fortunately, Facebook AI Research (FAIR) had already done the hard work wherein (Wang et al., 2020) introduced Linformer [4], which reduced the quadratic complexity to linear complexity using a low-rank matrix adaptation by decomposing the original scaled dot-product attention into multiple smaller attentions through linear projections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*47dvl2Hq4rSEwiB6.png" /><figcaption>Image from Linformer [4] showing the transformer architecture on the left, Linformer performance on the right and the low-rank matrix adaptation involved</figcaption></figure><p>Following that, Deepmind introduced the Performer [6] architecture (Choromanski et al., 2022), which could estimate kernelizable full-rank attention mechanisms using feature maps and orthogonal random features in linear time and space complexity without relying on sparsity or low-rankness, which had a very strong mathematical background.</p><p>OpenAI most likely used a combination of these techniques, as presented in Linformer or Performer, in conjunction with their customized attention kernels, which approximate the full attention mechanism with lower computational overhead, allowing faster processing while maintaining accuracy.</p><h4>Mixed Precision Training</h4><p>Previous research (Micikevicius et al., 2017) had already demonstrated how using lower precision (e.g., FP16) for certain parts of the model during training and inference can speed up computations significantly without sacrificing much precision. More recently, research [8] has shown that this can be further extended to use very low quantization precision to 4-bits of weights and activation tensors using advanced techniques like adaptive Gradient Scaling (GradScale). These techniques provide a massive boost of 7x times over the standard FP16 systems without sacrificing a lot on accuracy. Since, most of these techniques involve some kind of framework to maintain accuracy intact even after using low precision, OpenAI must be using their own quantization framework, most likely a combination of FP4, FP8 and FP16.</p><h4>Layer Normalization Improvements</h4><p>For a transformer, one needs a carefully designed learning rate warm-up stage and a very efficiently placed layer normalization. The placement of layer normalization between the residual blocks has been known to explode the gradients at the output layers, which is undesirable and makes the training unstable. On the other hand, placing the layer normalization inside the residual blocks offers more manageable gradients at the output layers. Research [9] has shown that this can be done without even using the warm-up stage, resulting in a significant drop in the model training, fine-tuning, and inferencing times without sacrificing too much accuracy. Optimizing the implementation of layer normalization can reduce the computational cost associated with this step.</p><h4>Gradient Checkpointing</h4><p>Gradient checkpointing [10], originally introduced by Chen et al., 2016, has been a well known technique in DL-world for a while now. This technique leverages the use of intermediate feature maps, computational graph analysis, which is essentially a trade-off between memory consumption and computation costs. Saving memory during training by recomputing some of the intermediate activations instead of storing them, which can be extended to inference for more efficient memory usage. Since GPT4-omni is generally available as an application for both mobile and desktop applications, it is crucial that it leaves behind a minimal footprint in order to accelerate computation. In my opinion, OpenAI has done a great job here and can automatically manage the computation graphs really well in real-time inferencing.</p><p>These were some of the key points of the technological marvel behind GPT4-omni; however, despite these state-of-the-art techniques serving billions in real time, one might wonder that some of these techniques are really trade-offs between one thing and the other, particularly when the company is optimizing the product for speed. There seems to be a strong focus on what to keep and what can be omitted to get a really fast model. While focus is on improving speed, it should not come at the cost of accuracy, especially when pruning is an important aspect.</p><p>In order to maintain the model’s accuracy even after pruning, OpenAI leverages many such techniques, such as:</p><ol><li>Adaptive Pruning: The model can use dynamic techniques to decide which parts of the network to prune based on the specific context and importance of the information. This ensures that less critical pathways are pruned while retaining key information.</li><li>Contextual Memory Mechanisms: Implementing memory mechanisms that retain important context across interactions can help. For example, transformers with enhanced memory components can store and retrieve relevant context even if certain pathways are pruned.</li><li>Attention Mechanisms: Sophisticated attention mechanisms can help the model focus on the most relevant parts of the input dynamically. Even if some paths are pruned, the attention mechanism can still highlight important context from the remaining pathways.</li><li>Regularization Techniques: These techniques can help maintain the balance between pruning and retaining essential information. They ensure that the pruning process doesn’t disproportionately affect critical pathways.</li><li>Post-Pruning Fine-Tuning: After pruning, the model can be fine-tuned on relevant tasks to adjust for any potential loss of information, ensuring it still performs well in understanding and generating accurate responses.</li></ol><p>And by doing all that, OpenAI has created a model that is very accurate as well as super fast in real-time. Thus, giving birth to GPT4-omni, taking the LLM competition game to the upper echelon.</p><p>All that I have mentioned in this article is based on my understanding of Large Language Models, and optimization of LLMs. The opinions are solely my own and do not represent my affiliation or anyone else. While these details are intellectual property reserved at the sole discretion of OpenAI, I have tried to explain how using these techniques might lead to the creation of GPT4-o.</p><p>If you have liked this post, don’t forget to like, clap, and share this article with anyone else who might find it beneficial. Feel free to check out my other articles, where I have talked about various other concepts related to Data Science, Machine Learning, Natural Language Processing and more. If you think I have done a good job, do follow me on Medium, which motivates me to write more such articles. Take care, until next time!</p><h3>References</h3><ol><li>Pagliardini, M., Paliotta, D., Jaggi, M., &amp; Fleuret, F. (2023). Fast Attention Over Long Sequences With Dynamic Sparse Flash Attention. <em>Neural Information Processing Systems</em>.</li><li>Li, J., Cotterell, R., &amp; Sachan, M. (2021). Differentiable Subset Pruning of Transformer Heads. <em>Transactions of the Association for Computational Linguistics, 9</em>, 1442–1459.</li><li>Goyal, S., Choudhury, A.R., Raje, S., Chakaravarthy, V.T., Sabharwal, Y., &amp; Verma, A. (2020). PoWER-BERT: Accelerating BERT Inference via Progressive Word-vector Elimination. <em>International Conference on Machine Learning</em>.</li><li>Wang, S., Li, B.Z., Khabsa, M., Fang, H., &amp; Ma, H. (2020). Linformer: Self-Attention with Linear Complexity. <em>ArXiv, abs/2006.04768</em>.</li><li>Kitaev, N., Kaiser, L., &amp; Levskaya, A. (2020). Reformer: The Efficient Transformer. <em>ArXiv, abs/2001.04451</em>.</li><li>Choromanski, K., Likhosherstov, V., Dohan, D., Song, X., Gane, A., Sarlós, T., Hawkins, P., Davis, J., Mohiuddin, A., Kaiser, L., Belanger, D., Colwell, L.J., &amp; Weller, A. (2020). Rethinking Attention with Performers. <em>ArXiv, abs/2009.14794</em>.</li><li>Micikevicius, P., Narang, S., Alben, J., Diamos, G.F., Elsen, E., García, D., Ginsburg, B., Houston, M., Kuchaiev, O., Venkatesh, G., &amp; Wu, H. (2017). Mixed Precision Training. <em>ArXiv, abs/1710.03740</em>.</li><li>Sun, X., Wang, N., Chen, C., Ni, J., Agrawal, A., Cui, X., Venkataramani, S., Maghraoui, K.E., Srinivasan, V., &amp; Gopalakrishnan, K. (2020). Ultra-Low Precision 4-bit Training of Deep Neural Networks. <em>Neural Information Processing Systems</em>.</li><li>Xiong, R., Yang, Y., He, D., Zheng, K., Zheng, S., Xing, C., Zhang, H., Lan, Y., Wang, L., &amp; Liu, T. (2020). On Layer Normalization in the Transformer Architecture. <em>ArXiv, abs/2002.04745</em>.</li><li>Chen, T., Xu, B., Zhang, C., &amp; Guestrin, C. (2016). Training Deep Nets with Sublinear Memory Cost. <em>ArXiv, abs/1604.06174</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207f3b4527c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers (NLP): Intuition]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dsdojo.medium.com/transformers-nlp-intuition-d7d156e10ecf?source=rss-10981b26bbe6------2"><img src="https://cdn-images-1.medium.com/max/1920/1*kiuTf0jyVFQbBrXdlKpaXA.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Unlocking the AI Marvel: The Power Behind Transformers in NLP!&#x201D; &#x1F680; Dive into the heart of Large Language Models (LLMs) like ChatGPT, BARD&#x2026;</p><p class="medium-feed-link"><a href="https://dsdojo.medium.com/transformers-nlp-intuition-d7d156e10ecf?source=rss-10981b26bbe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dsdojo.medium.com/transformers-nlp-intuition-d7d156e10ecf?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7d156e10ecf</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 04:42:09 GMT</pubDate>
            <atom:updated>2023-11-21T10:35:09.715Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Gain, Lift and Decile Charts]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dsdojo.medium.com/gain-lift-and-decile-charts-4efd3573aae6?source=rss-10981b26bbe6------2"><img src="https://cdn-images-1.medium.com/max/1432/1*5E_xu2HOPwBlUxHD1oqOZw.png" width="1432"></a></p><p class="medium-feed-snippet">Are you struggling to accurately evaluate your classification model&#x2019;s performance?</p><p class="medium-feed-link"><a href="https://dsdojo.medium.com/gain-lift-and-decile-charts-4efd3573aae6?source=rss-10981b26bbe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dsdojo.medium.com/gain-lift-and-decile-charts-4efd3573aae6?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4efd3573aae6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[lift-chart]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 15:02:39 GMT</pubDate>
            <atom:updated>2023-02-23T15:02:39.735Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The ROC-AUC Curve!]]></title>
            <link>https://dsdojo.medium.com/the-roc-auc-curve-e0df642f76fe?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0df642f76fe</guid>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[area-under-the-curve]]></category>
            <category><![CDATA[roc-curve]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 14:11:13 GMT</pubDate>
            <atom:updated>2023-02-20T14:17:36.509Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Imagine you have a crystal ball that can predict the future with incredible accuracy. Sounds awesome, right? But how do you know if your crystal ball is as good as it claims to be? That’s where the ROC curve comes in.</blockquote><h3>Introduction</h3><p>The Area Under the Curve (AUC) of the Receiver Operating Characteristic (ROC) curve is a widely used evaluation metric in machine learning and statistical modeling. But AUC-ROC is more than just a fancy acronym — it’s a powerful tool for evaluating the performance of models, and it can help you understand how well your model is able to distinguish between positive and negative cases. The ROC curve is not only informative, but also visually stunning, with its characteristic shape and shading that make it a pleasure to look at. Whether you’re a data scientist, a machine learning enthusiast, or simply curious about the power of AUC-ROC, you’re in for a treat! Get ready to dive into the world of AUC-ROC, where data meets beauty!</p><p>The term AUC-ROC, and ROC-AUC mean the same thing, and I would use them interchangeably. This article will go over the ROC-AUC in detail, including how they are constructed and evaluated, how they may be used to evaluate the performance of a classification model, as well as a step-by-step walk-through of the entire process.</p><p><strong>Preamble:</strong> In my last article, I explained the fundamentals of Performance Metrics, and this article will expand on that. If you haven’t already read my previous article on <a href="https://medium.com/@MLdebanjan/the-only-performance-metrics-article-you-will-ever-need-135cf5e693e2">Basic Performance Metrics</a>, I strongly advise you to do so before continuing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXVxnxIdOhL4RiOt9HeImw.gif" /><figcaption>Probability of classifier [1]</figcaption></figure><h3>Propensity Chart / ROC Curve</h3><p>A propensity chart, also known as a <strong>Receiver Operating Characteristic (ROC)</strong> curve, is a graphical representation of a binary classifier system’s performance. It compares the <strong>true positive rate</strong> (<strong>TPR</strong>) against the <strong>false positive rate</strong> (<strong>FPR</strong>) for various threshold values. I have already discussed about these metrics in my <a href="https://medium.com/@MLdebanjan/the-only-performance-metrics-article-you-will-ever-need-135cf5e693e2">previous article</a>, before proceeding any further I recommend you to check them out if these terms are new to you. The <strong>TPR</strong> represents the proportion of true positives that are correctly identified as such, whereas the <strong>FPR</strong> represents the proportion of true negatives that are wrongly categorized as positives.</p><blockquote>Fun Fact: ROC (Receiver Operating Characteristic) analysis was first developed during World War II to evaluate radar signal detection performance. The concept was later adopted in the field of medicine and other areas to evaluate diagnostic and predictive models.</blockquote><blockquote>Welcome to the magical world of ROC curves!</blockquote><p>ROC-AUC is a powerful tool for evaluating the performance of predictive models, allowing you to measure their accuracy and identify the best threshold values for predicting outcomes.</p><h4>Create a ROC Curve in Six Easy Steps:</h4><ol><li>First, gather your model’s predicted scores and true labels.</li><li>Then, sort the predicted scores in descending order</li><li>Establish the range of possible thresholds.</li><li>Calculate the true positive rate (TPR) and false positive rate (FPR) for each threshold value</li><li>Plot the resulting points on a graph with TPR on the y-axis and FPR on the x-axis. As you move from left to right on the ROC curve, the threshold decreases, indicating that more observations are rated as positive.</li><li>The area under the curve (AUC) represents the overall performance of your model, with 1.0 signifying a perfect classifier and 0.5 suggesting a random classifier.</li></ol><h4>Example Walk-Through</h4><p>Let’s take an example and try to understand these steps in details. In this example, we shall use a random classification model to classify whether a book will be a best-seller or not. The observations are probabilities if it will be a best-seller — positive (‘1’) or not so — negative (‘0’). Here our objective is to understand the evaluation criteria in detail, so we will not go deep into model selection and assume any random model to produce the outputs.</p><p><strong>Step 1</strong> — First we take a dataset of 30 observations, which provides us the model’s prediction scores or probabilities (predicted_scores) and the true labels (actual_labels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*kjVkoWAH3qiyfdEEY1cPjw.png" /><figcaption>Sample Dataset</figcaption></figure><p><strong>Step 2</strong> — Now we will sort the dataset based on the predicted_scores column in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*XjkkMBGFnubsu1jn18h2mg.png" /><figcaption>Sorted Dataset</figcaption></figure><p><strong>Step 3</strong> — Now, we will select some threshold value. For this example if we select a threshold of 0.33 — any observations with scores below this threshold will be categorized as negative (‘0’) class and all observations greater than or equal to this threshold will be categorized as positive (‘1’) class. This is denoted by the ‘threshold’ column below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*yt6Pfy-Gg7Ulo5vmhj1rug.png" /></figure><p><strong>Step 4</strong> — Now, we will calculate the TPR or Sensitivity (True Positives / Total Actual Positives) and FPR or (1-Specificity) (False Positives / Total Actual Negatives) for each threshold. The more thresholds you select, the more refined curve you shall get. For the sake of simplicity, we shall use only 30 evenly spaced thresholds between [0,1], and calculate the TPR and FPR varying the threshold as in the previous step.</p><p><strong>Step 5</strong> — Now, using these set of TPR and FPR values, we will plot the ROC curve with Sensitivity or TPR as the Y-axis, and (1-Specificity) or FPR as the X-axis. We shall also include a baseline (naive) classifier (denoted by the red dotted lines). If our model is near or below this baseline, we shall consider our model to have really bad performance.</p><p><strong>Step 6</strong> — Finally, we will calculate the Area under the ROC Curve (AUC) using numerical methods such as the trapeziodal rule (numpy.trapz or scipy.integrate.trapezoid). If we have a good model, the AUC should be near to 1, and if the AUC is below 0.5, we will know that our model’s performance is worse than a random guess (baseline). We will plot the AUC as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*Y397ggMgK4BFjSWDQAXuCg.png" /><figcaption>ROC — AUC Curve</figcaption></figure><p>We can notice, that the performance of our model was good, as the ROC curve is more towards the upper-left corner of the plot, indicating a high TPR and a low FPR. We can also justify this with the fact that we got a AUC value of 0.9955, which would be very close to an ideal classifier (AUC=1.0)</p><h4>Key Insights from ROC-AUC Curve</h4><p>Here are some of the key-insights you can derive by looking at any ROC-AUC curve:</p><ol><li>The closer the ROC-AUC curve is to the top-left corner of the plot, the better the model’s performance. This indicates that the model is correctly predicting a high percentage of true positives while maintaining a low false-positive rate.</li><li>An AUC of 0.5 suggests that the model’s predictions are no better than random guessing. An AUC of 1.0, on the other hand, indicates that the model is perfect at discriminating between positive and negative examples.</li><li>The ROC-AUC curve is a helpful tool for selecting the best threshold value for classification. By looking at the curve, you can determine the optimal tradeoff between sensitivity (true positive rate) and specificity (true negative rate) for your particular problem.</li><li>The ROC-AUC curve can be used to compare the performance of different models on the same task. The model with a higher AUC is generally regarded as the better performer.</li><li>The ROC-AUC curve can also be used to evaluate the quality of probabilistic predictions. A model that produces well-calibrated probabilities should have an AUC close to 1.0.</li></ol><h4>Comparing ROC-AUC for various classifiers</h4><p>Here, we will compare the ROC-AUC curves for three types of classifiers —perfect, moderate, worse classifiers, and see how they differ from one another.</p><h4>Perfect Classifier</h4><p>A perfect ROC-AUC curve has a TPR of 1 and an FPR of 0. This means that all positive examples were correctly identified by the model, and none of the negative examples were mistakenly labeled as positive. A perfect ROC-AUC curve is one in which the classifier perfectly separates the positive and negative classes without any overlap, giving an AUC score of 1. This means that the model is a great classifier and can perfectly tell the difference between the two classes. This is the best case, but it doesn’t happen very often.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*D2F694dJkfByURR7vnDwlA.png" /><figcaption>ROC-AUC for a Perfect Classifier with AUC = 1.0</figcaption></figure><h4>Moderate Classifier</h4><p>A moderate ROC-AUC curve usually has a TPR that is less than 1 and an FPR that is greater than 0, but it is still better than random chance. This means that the model gets more positive examples right than negative examples right, but there are still some wrong classifications. A moderate ROC-AUC curve is one in which the positive and negative classes overlap, giving the classifier an AUC score between 0.5 and 1. This shows that the model can tell the difference between the two classes to some degree, but it could still be better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*v2bQTtMTvW_QofndVthVkw.png" /><figcaption>ROC-AUC for a Moderate Classifier with AUC = 0.7416</figcaption></figure><h4>Worse Classifier</h4><p>A worse ROC-AUC curve has a TPR that is not much better than random chance and an FPR that is very high. This means that the model is not working well and is misclassifying a lot of positive and negative examples. A worse ROC-AUC curve is one in which the positive and negative classes overlap a lot, giving the classifier an AUC score of less than 0.5. This means the model can’t tell the difference between the two classes and is worse than a random classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*kyb1u19LPKA5SoqhffouzQ.png" /><figcaption>ROC-AUC for a Worse Classifier with AUC = 0.4442</figcaption></figure><p>It’s important to note that the ROC-AUC curve is just one evaluation metric for classification models, and it’s important to consider other metrics such as precision, recall, accuracy, and F1 score to fully evaluate the performance of a model. However, the ROC-AUC curve is a useful tool for visualizing and comparing the performance of different classifiers.</p><h3>Some Applications of AUC-ROC Curve</h3><p>Although we utilized a classification model, there are several circumstances when AUC-ROC can be adapted for use in regression models. In some cases, a regression model may produce a probability that an event will occur, and the threshold of this probability sets the predicted value. In these situations, AUC-ROC can be used to evaluate the model’s performance. It should be noted, however, that this is not a common approach and may not be suited for all regression problems.</p><ul><li>Medical diagnosis: AUC-ROC can be used to figure out how well a model for medical diagnosis works. For example, if you want to predict whether a patient has a certain disease or not, you can use AUC-ROC to measure how well the model can correctly identify patients who have the disease and avoid giving false positives.</li><li>Credit risk analysis: In credit risk analysis, AUC-ROC can be used to measure how well a model predicts how likely it is that a borrower will not pay back a loan. A high AUC-ROC score shows that the model is good at telling the difference between borrowers with high risk and those with low risk.</li><li>Detecting fraud: AUC-ROC can be used to measure how well a fraud detection model works. For example, AUC-ROC can be used to figure out how well a model can spot fraudulent credit card transactions while reducing the number of false positives.</li><li>Marketing campaigns: AUC-ROC can be used to measure how well a marketing campaign is doing when it’s aimed at a certain type of customer. For example, in email marketing, AUC-ROC can be used to measure how well the campaign is able to correctly identify customers who are likely to make a purchase and avoid targeting customers who are not likely to make a purchase.</li><li>Image recognition: AUC-ROC can be used to measure how well a model works at recognizing images. In the case of medical image analysis, for example, AUC-ROC can be used to measure how well the model can find abnormalities in images while reducing the number of false positives.</li></ul><h3>Conclusion</h3><p>In conclusion, ROC-AUC curves are an essential tool in evaluating the performance of classification models. The curve provides a visual representation of a model’s ability to distinguish between positive and negative classes, and the AUC score summarizes its overall performance. A perfect ROC-AUC curve would have a TPR of 1 and an FPR of 0, while a worse curve would be indistinguishable from a random classifier. It is crucial to consider the ROC-AUC curve and AUC score when selecting the best model for a given problem. With this powerful tool, we can confidently choose the model that maximizes performance and minimizes errors, making it an essential tool in the field of machine learning.</p><h4>Reference:</h4><ol><li>Chou, S.-Y. (2019) <em>AUC — Insider’s Guide to the theory and applications</em>, <em>Sin</em>. Available at: <a href="https://sinyi-chou.github.io/classification-auc/">https://sinyi-chou.github.io/classification-auc/</a> (Accessed: February 20, 2023).</li></ol><h3>About Author</h3><p>Debanjan Saha, a.k.a, “Deb”, is a data enthusiast with a background in Data Engineering from Northeastern University in Boston. With over 5 years of experience in the field, he has developed a deep understanding of various data-related concepts and techniques. Passionate about turning data into insights, he has helped many organizations optimize their operations and make informed decisions. As a Data Scientist, he has successfully led projects involving data analysis, visualization, statistical modeling, and model deployment. His skills include proficiency in Python, Matlab, PySpark, Computation, Optimization, and Azure Databricks, among others.</p><p>When not working with data, Deb enjoys listening to music and playing guitars. He is also a frequent contributor to online communities, sharing expertise in the form of articles and tutorials on platforms like Medium. To learn more about him and stay updated on his latest work, you can connect with Debanjan on <a href="https://www.linkedin.com/in/debanjanaiml/">LinkedIn</a> and follow him on <a href="https://medium.com/@MLdebanjan">Medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0df642f76fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The only Performance Metrics article you will ever need!]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dsdojo.medium.com/the-only-performance-metrics-article-you-will-ever-need-135cf5e693e2?source=rss-10981b26bbe6------2"><img src="https://cdn-images-1.medium.com/max/608/1*Y-LuD7eiy45fW0HpwkKv0A.jpeg" width="608"></a></p><p class="medium-feed-snippet">Performance metrics are a crucial part of machine learning, as they allow us to evaluate the quality of a model and make informed&#x2026;</p><p class="medium-feed-link"><a href="https://dsdojo.medium.com/the-only-performance-metrics-article-you-will-ever-need-135cf5e693e2?source=rss-10981b26bbe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dsdojo.medium.com/the-only-performance-metrics-article-you-will-ever-need-135cf5e693e2?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/135cf5e693e2</guid>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 15:02:40 GMT</pubDate>
            <atom:updated>2023-02-17T15:02:40.953Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[T-Distributed Stochastic Neighbor Embedding (t-SNE)]]></title>
            <link>https://dsdojo.medium.com/t-distributed-stochastic-neighbor-embedding-t-sne-1ca180634d23?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca180634d23</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 15:02:40 GMT</pubDate>
            <atom:updated>2023-02-15T15:02:40.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>T-Distributed Stochastic Neighbor Embedding (t-SNE) is a powerful technique for dimensionality reduction that has taken the machine learning and data visualization communities by storm. In an era of big data and high-dimensional datasets, t-SNE provides an easy approach for reducing complex data to a lower-dimensional space, enabling visualization and comprehension of the data’s underlying structure. In numerous applications, including image classification, text analysis, gene expression, and many others, t-SNE has proven to be particularly effective at revealing patterns and correlations. This potent technique has not only revolutionized the way data is represented, but it has also led the way for new insights and discoveries in a variety of sectors. In this article, we will explore the mathematics behind t-SNE, explain how it operates, and demonstrate its visualization capabilities for high-dimensional data.</p><h3>t-SNE</h3><p>t-SNE (t-Distributed Stochastic Neighbor Embedding) is an effective and widely-applied method for displaying high-dimensional data. It is an unsupervised machine learning technique that reduces the dimensionality of huge datasets and identifies patterns, relationships, and clusters in multidimensional and complicated data. In 2008, Laurens van der Maaten and Geoffrey Hinton introduced this approach.</p><h4>How does it work?</h4><p>t-SNE transforms high-dimensional data into a two-dimensional scatter plot or other low-dimensional representation. This low-dimensional representation is designed to preserve as much as possible the distance between points in the high-dimensional space in the low-dimensional space. This facilitates the visualization of the relationships between points in the high-dimensional space and reveals the data’s underlying structure.</p><p>The t-SNE algorithm defines a probability distribution across the high-dimensional data points such that the similarity between points is proportional to the likelihood that they are neighbors. It works by preserving the local and global structure of the data by mapping it to a low-dimensional representation that is optimized using the Kullback-Leibler divergence. This is accomplished by computing the conditional probability distribution across each point’s neighbors. The t-SNE then maps these probabilities to a two-dimensional scatter plot, where the distances between points correspond to the similarities in the high-dimensional space.</p><h4>Math under the hood of t-SNE</h4><p>The mathematics underlying t-SNE can be interpreted as follows:</p><ol><li><strong>KL Divergence</strong>: The initial step is to compute the Kullback-Leibler (KL) divergence between the high-dimensional and low-dimensional probability distributions. KL divergence is a measurement of the difference between two probability distributions. In t-SNE, the probability distributions of high-dimensional data points are compared to those of low-dimensional data points.</li><li><strong>High-Dimensional Similarity</strong>: The following step is to determine the high-dimensional similarity between the data points. This is accomplished by calculating the pairwise distances between data points in the high-dimensional space.</li><li><strong>Low-Dimensional Similarity</strong>: The following step is to determine the low-dimensional similarity between the data points. This is accomplished by converting the high-dimensional similarity to the low-dimensional similarity. The altered low-dimensional similarity will subsequently be utilized to construct the gradient descent update for the t-SNE optimization procedure.</li><li><strong>Gradient Descent Optimization</strong>: Finally, gradient descent optimization is used to update the low-dimensional representation of the data points. This entails computing the gradient of the KL divergence with regard to the low-dimensional representation of the data points and thereafter updating the representation until convergence.</li></ol><p>t-SNE involves minimizing the KL Divergence as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*VrI2_p4HJICWZvESY0jGeQ.png" /><figcaption>t-SNE Objective</figcaption></figure><p>The objective function of t-SNE can be represented as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*fQbvQv-BRPuklse8y1z68Q.png" /><figcaption>t-SNE Cost Function</figcaption></figure><p>where p_ij and q_ij are the probabilities that data points i and j are neighbors in the original high dimensional space and the low dimensional space, respectively. The sum over j is taken over all data points that are not equal to i.</p><p>The probability p_ij can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*-lKmNhEoRUBK9VNXESnNpw.png" /><figcaption>High Dimensional Spatial Probability</figcaption></figure><p>where x_i and x_j are the data points in the high dimensional space, and sigma_i is a parameter that can be tuned to control the variance of the Gaussian distribution used to compute the probabilities.</p><p>The probability q_ij can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*_KMIqbdIAHYDL7G8ivOWcg.png" /><figcaption>Low Dimensional Spatial Probability</figcaption></figure><p>where y_i and y_j are the data points in the low dimensional space.</p><p>By minimizing the t-SNE objective, we can obtain a low dimensional representation that preserves the structure of the data. This can be done using gradient descent optimization techniques. The optimization process can be computationally expensive, but it can be accelerated using techniques such as Barnes-Hut approximation and early exaggeration.</p><h4>Code Implementation</h4><p>Let us look at an example of high dimension visualization using t-SNE. In this implementation we will use the <a href="https://www.openml.org/search?type=data&amp;sort=runs&amp;id=554&amp;status=active">MNIST</a> dataset available at OpenML which contains hand-written digits with 784 pixels (features) for each image, and overall 70,000 such images. Since, this is a prime example of high-dimensional data, we will try to visualize this data using t-SNE as:</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import fetch_openml<br>from sklearn.manifold import TSNE<br><br># Load the MNIST data from the OpenML repository<br>mnist = fetch_openml(&#39;mnist_784&#39;, version=1)<br><br># Select a smaller number of samples for computational efficiency<br>n_samples = 1000<br>X = mnist.data[:n_samples]<br>y = mnist.target[:n_samples]<br><br># Fit the t-SNE model to the data<br>tsne = TSNE(n_components=2, <br>            perplexity=30, <br>            learning_rate=200, <br>            n_iter=1000, <br>            random_state=0)<br>X_tsne = tsne.fit_transform(X)<br><br>tsne_df = pd.DataFrame(X_tsne, columns=[&#39;x&#39;, &#39;y&#39;])<br>tsne_df[&#39;class&#39;] = y<br>tsne_df[&#39;class&#39;] = tsne_df[&#39;class&#39;].astype(&#39;category&#39;).cat.codes<br><br># Plot the resulting t-SNE visualization<br>fig, ax = plt.subplots(1,1, figsize=(10, 8))<br>colors = plt.get_cmap(&quot;Spectral&quot;)<br>for label in np.unique(tsne_df[&#39;class&#39;]):<br>    class_df = tsne_df[tsne_df[&#39;class&#39;] == label]<br>    color = colors(label / 10.0)<br>    plt.scatter(class_df[&#39;x&#39;], class_df[&#39;y&#39;], <br>                color=color, <br>                label=str(label))<br>ax.set_title(&quot;t-SNE visualization of MNIST dataset&quot;)<br>ax.set_xlabel(&quot;t-SNE axis 1&quot;)<br>ax.set_ylabel(&quot;t-SNE axis 2&quot;)<br>ax.legend()<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*_VBl7FUMv0q0qVf7_lk61A.png" /><figcaption>MNIST 2D Data Visualization using t-SNE</figcaption></figure><p>In this MNIST plot, we can observe clusters of similar digits. For example, the 0s are grouped together, and the 1s are grouped together, and so on. This indicates that the t-SNE algorithm has successfully captured the similarity structure in the high-dimensional MNIST data.</p><p>Note that the axes are centered around 0 because the t-SNE algorithm minimizes the distance between instances in the high-dimensional space and their projections in the 2D space, so that the resulting plot is optimized for visualizing the relationships between instances.</p><p>By visualizing the data in this way, it may be easier to identify patterns, groupings or similarities in the data that were not easily recognizable from the raw data. Additionally, it provides a way to explore and understand complex, high-dimensional datasets in a more intuitive way.</p><h3>Applications of t-SNE</h3><p>t-SNE is utilized extensively in numerous disciplines, including computer science, biology, neuroscience, and the social sciences. It is frequently employed to visualize high-dimensional data, such as images, videos, audio signals, and texts, and for exploratory data analysis and feature engineering.</p><ol><li><strong>Image recognition</strong>: t-SNE has been used to visualize the intermediate activations of Convolutional Neural Networks (CNNs) trained on image datasets, helping researchers understand how the networks learn and recognize patterns in images.</li><li><strong>Natural language processing</strong>: t-SNE has been used to visualize the high-dimensional representations of words and documents, making it easier to understand the relationships between them and identify patterns in the data.</li><li><strong>Genomics</strong>: t-SNE has been used to visualize high-dimensional gene expression data, enabling researchers to identify subtypes of diseases and understand the underlying biology.</li><li><strong>Healthcare</strong>: t-SNE has been used to visualize electronic health records (EHRs), helping healthcare professionals identify patterns in patient data and make more informed decisions about diagnosis and treatment.</li><li><strong>Marketing</strong>: t-SNE has been used to visualize customer data, enabling companies to segment their target audience and identify patterns in customer behavior.</li><li><strong>Fraud detection</strong>: t-SNE has been used to visualize fraudulent transactions, making it easier to identify unusual patterns and detect fraudulent activity.</li></ol><p>These are just a few common real-world scenarios where t-SNE has proved to be very beneficial, but the scope of using t-SNE extends far beyond.</p><h3>Conclusion</h3><p>In conclusion, t-SNE is an effective method for visualizing high-dimensional data that can assist uncover patterns, relationships, and clusters in complicated and multidimensional data. t-SNE’s ability to capture complicated, non-linear relationships between data points is one of its primary features, making it particularly helpful for visualizing high-dimensional data. In addition, it is highly efficient at discovering clusters in the data, even when the clusters are difficult to discern in the high-dimensional space.</p><p>If you find this article useful, please follow me for more such related content, where I frequently post about Data Science, Machine Learning and Artificial Intelligence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca180634d23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrapper Based Feature Selection Techniques]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dsdojo.medium.com/wrapper-based-feature-selection-techniques-dd3ff6d1b79f?source=rss-10981b26bbe6------2"><img src="https://cdn-images-1.medium.com/max/1225/1*luP0MwEyYkPza9jUkxzSPg.jpeg" width="1225"></a></p><p class="medium-feed-snippet">There are many ways in which features can be selected from a set of predictors to improve the performance of the machine learning models&#x2026;</p><p class="medium-feed-link"><a href="https://dsdojo.medium.com/wrapper-based-feature-selection-techniques-dd3ff6d1b79f?source=rss-10981b26bbe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dsdojo.medium.com/wrapper-based-feature-selection-techniques-dd3ff6d1b79f?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd3ff6d1b79f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[wrapper-methods]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 15:01:56 GMT</pubDate>
            <atom:updated>2023-02-13T15:01:56.519Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Filter Based Feature Selection Techniques]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dsdojo.medium.com/filter-based-feature-selection-techniques-8f0be980c8fd?source=rss-10981b26bbe6------2"><img src="https://cdn-images-1.medium.com/max/1157/1*0dJsqCq8qa5fnYXTXwA1Fw.jpeg" width="1157"></a></p><p class="medium-feed-snippet">When there are a lot of predictors (or features), it is often best to pick the most important ones and get rid of the rest. There are many&#x2026;</p><p class="medium-feed-link"><a href="https://dsdojo.medium.com/filter-based-feature-selection-techniques-8f0be980c8fd?source=rss-10981b26bbe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dsdojo.medium.com/filter-based-feature-selection-techniques-8f0be980c8fd?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0be980c8fd</guid>
            <category><![CDATA[correlation]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[chi-square-test]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-test]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 03:58:12 GMT</pubDate>
            <atom:updated>2023-02-12T03:58:12.376Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[[Probability Review] Top 6 Basic Probability Distributions You Should Know!]]></title>
            <link>https://dsdojo.medium.com/top-6-basic-probability-distributions-you-should-know-ed2d32cdb37c?source=rss-10981b26bbe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2d32cdb37c</guid>
            <category><![CDATA[probability-theory]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[expectations]]></category>
            <category><![CDATA[probabilistic-programming]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <dc:creator><![CDATA[Debanjan Saha]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 06:33:46 GMT</pubDate>
            <atom:updated>2023-02-11T07:48:56.038Z</atom:updated>
            <content:encoded><![CDATA[<p>As a <em>data scientist</em> or <em>machine learning engineer</em>, you should be quite familiar with a few probability distributions. We may often model a real-world occurrence using these probability distributions in real-world circumstances, but it is necessary to understand the complexities of each distribution as well as their applications. In this article, we will go through the six most fundamental probability distributions that everyone should be familiar with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuAEVPoGkjVp09-iwReZxA.png" /><figcaption>Probability Distributions</figcaption></figure><h3>Bernoulli Distribution</h3><p>Bernoulli Distribution is a discrete probability distribution that models the outcome of a single binary event, i.e., a trial with only two possible outcomes, commonly referred to as “success” or “failure”. The random variable X follows a Bernoulli distribution and has a probability of 1 (success) and a probability of 0 (failure) (1-p).</p><h4>PMF, Expectation and Variance</h4><p>A Bernoulli distribution with parameter p has the following Probability Mass Function (PMF), expectation and variance as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*B6C6DEMR6Gccys_Ruob-HQ.gif" /><figcaption>Bernoulli Distribution</figcaption></figure><p>E(X) = p gives the expected value (mean) of a Bernoulli random variable X with parameter p.</p><p>The variance of X is given by Var(X) = p * (1-p).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*3YLR7zfRHvanz08l8vhnqA.png" /><figcaption>Bernoulli Trial with p = 0.30</figcaption></figure><p>Because a Bernoulli distribution is a discrete distribution, its PMF can be represented as a bar graph with two bars corresponding to the two potential outcomes (success and failure) and their respective probabilities. Each bar’s height represents the probability of the related outcome.</p><p>The probabilities of the two events change as the parameter p changes and more number of trials are conducted, and so does the plot of the PMF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*foRjWTTYevjVgYMB61a6pw.png" /></figure><h4>Usage</h4><p>Here are a few examples of how a Bernoulli distribution might be used:</p><ol><li>A <strong>fair coin flip </strong>results in either heads (success) or tails (failure), and both outcomes are equally likely, with probability p = 0.5. The Bernoulli distribution can be used to model the outcome of the coin toss in this scenario.</li><li><strong>Click-through rate: </strong>The Bernoulli distribution can be used to model the probability that a user will click on an <strong>advertisement</strong> after viewing it. <strong>Click-through rate </strong>in internet advertising. Let’s imagine there is a 10 percent probability that a user will click on an advertisement. p = 0.1 in this situation.</li><li><strong>Medical treatment success/failure: </strong>The Bernoulli distribution can be used to model the success or failure of a medical therapy. A Bernoulli distribution, for example, can be used to model the likelihood of a cancer patient surviving following therapy, with p denoting the probability of survival.</li><li><strong>Online Advertisements:</strong> The probability that a client will make a purchase after browsing an online store can be modeled using the Bernoulli distribution. The probability of a consumer making a purchase, for example, is 0.3, thus p = 0.3.</li></ol><p>These are just a few instances of how the Bernoulli distribution might be applied in practice. The Bernoulli distribution is a straightforward but versatile model that can be used in a wide range of subjects and disciplines.</p><h4>Relation with other distributions</h4><p>Several probability distributions are connected to the Bernoulli distribution:</p><ul><li><strong>Binomial Distribution:</strong> If X1, X2,…, Xn are independently and identically distributed (i.i.d) Bernoulli random variables with parameter p, then the sum Y = X1 + X2 +… + Xn has a Binomial distribution with parameters n and p. In n independent Bernoulli trials, the Binomial distribution models the number of successes.</li><li><strong>Poisson Distribution:</strong> The Poisson distribution is a limiting example of the Binomial distribution in which the number of trials n approaches infinity and the probability of success p approaches 0 while np remains constant. In other words, if the average number of wins in n independent Bernoulli trials is fixed at np, the Binomial distribution approaches a Poisson distribution with parameter np as n grows very big.</li><li><strong>Geometric Distribution:</strong> The Geometric distribution models the number of Bernoulli trials required to reach the first success. Because each trial is a independent and identically distributed Bernoulli trial, it is related to the Bernoulli distribution.</li><li><strong>Negative Binomial Distribution:</strong> In a series of independent and identically distributed Bernoulli trials, the Negative Binomial Distribution models the number of failures prior to the r-th success.</li></ul><p>Finally, the Bernoulli distribution serves as a foundation for many other significant distributions and is widely utilized in statistical modeling and analysis.</p><h3>Binomial Distribution</h3><p>The Binomial Distribution is a discrete probability distribution that models the number of successes in n independent Bernoulli trials, each having the same chance of success p. The Binomial distribution is used to address queries such as, “<em>How many successful outcomes can we expect from a particular number of trials?</em>” Or, “<em>What is the probability of exactly k successful outcomes in n trials?</em>”</p><h4>PMF, Expectation and Variance</h4><p>A Binomial distribution with parameters n and p has the following Probability Mass Function (PMF), expectation and variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*GKYunDVmEaIcCY63uUm31g.gif" /><figcaption>Binomial Distribution</figcaption></figure><p>The expectation (mean) suggests that we can expect <em>np</em> successful outcomes in <em>n </em>trials on average. The variance quantifies the distribution’s <strong>spread </strong>or <strong><em>dispersion</em></strong>.</p><p>Plotting the PMF of a Binomial distribution is <em>similar to </em>plotting the PMF of a <strong>Bernoulli</strong> distribution, except that the Binomial distribution contains several bars corresponding to the various values of X (displayed as small <strong>circular markers </strong>in the line plots for aesthetic purposes), and the height of each bar represents the probability of that number of successes in n trials. The geometry of the PMF changes as the parameters n and p change. For instance, as the number of trials increases, the distribution becomes increasingly spread out and approaches a normal distribution. As p increases, the distribution shifts to the right, and as success probability p reduces, the distribution shifts to the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*0JSCEzTdqFJ3DxllSLcFUg.png" /><figcaption>Binomial Distribution PMF plot by varying the parameters</figcaption></figure><p>Finally, the Binomial distribution is a valuable tool for predicting the probability of a particular number of successful outcomes and modeling the number of successful outcomes in a fixed number of trials.</p><h4>Usage</h4><p>Here are some scenarios that can be described using a Binomial distribution:</p><ol><li><strong>Tossing a coin:</strong> Assume you toss a fair coin n times. Let X be the number of heads in n consecutive flips. Because each flip is an independent Bernoulli trial with a success probability of 0.5, X has a Binomial distribution with parameters n and p = 0.5.</li><li><strong>Medical treatment success:</strong> Suppose you test a new medical treatment on n patients, with X being the number of patients who respond positively to the treatment. Then X has a Binomial distribution with parameters n and p, where p is the treatment’s unknown success probability.</li><li><strong>Quality control in a manufacturing process:</strong> Assume a manufacturing process produces n items, with X representing the number of defective items in the batch. Then X has a Binomial distribution with parameters n and p, where p is the manufacturing process’s unknown defect probability.</li><li><strong>Marketing campaign:</strong> Assume a marketing campaign has a goal of reaching n customers, and X is the number of customers who respond to the campaign. Then X has a Binomial distribution with parameters n and p, where p is the consumers’ unknown response rate.</li></ol><p>The Binomial distribution can be used to model real-world circumstances in a variety of ways, as seen here. In statistics and data analysis, the Binomial distribution is a versatile and extensively used distribution.</p><h4>Relation with other distributions</h4><p>In various ways, the Binomial distribution is related to several other probability distributions. Here are a couple such examples:</p><ul><li><strong>Poisson Distribution: </strong>The Poisson distribution is a limiting instance of the Binomial distribution that occurs when the number of trials n is very large and the success probability p is very small, so that np remains constant. In other words, if X has a Binomial distribution with parameters n and p, then X converges to a Poisson distribution with parameter = np as n and p become extremely big and very small, respectively.</li><li><strong>Normal Distribution:</strong> The sum of a large number of independent and identically distributed random variables approaches a normal distribution, according to the Central Limit Theorem. If X1, X2,…, Xn are independent Bernoulli random variables with the same success probability p, then the sum Y = X1 + X2 +… + Xn has a Binomial distribution with n and p as parameters. As n increases, Y approaches a normal distribution, according to the Central Limit Theorem.</li><li><strong>Negative Binomial Distribution:</strong> The Negative Binomial distribution is a generalization of the Binomial distribution that models the number of failures until the k-th success in a series of independent Bernoulli trials. The Negative Binomial distribution is a discrete distribution similar to the Binomial distribution in that both model the number of successful outcomes in a certain number of trials.</li><li><strong>Hypergeometric Distribution:</strong> The Hypergeometric distribution is similar to the Binomial distribution in that it models the number of successful outcomes in a set number of trials. Unlike the Binomial distribution, however, the Hypergeometric distribution considers both the overall number of items and the number of items of each kind. The Hypergeometric distribution is used to model scenarios in which trials are not independent and the number of items of each category varies from trial to trial.</li></ul><p>These are some of the most prevalent relationships between the Binomial distribution and other probability distributions. Understanding these relationships is critical for selecting the best distribution to model a given circumstance.</p><h3>Uniform Distribution</h3><p>The uniform probability distribution is a continuous probability distribution that models a situation in which all conceivable outcomes have the same probability. It is defined by two parameters: a and b, which reflect the distribution’s minimum and maximum values, respectively.</p><h4>PDF, Expectation and Variance</h4><p>A uniform distribution’s probability density function (pdf) is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*gDb4icfjuQoWLt6M7HG1pg.gif" /><figcaption>Uniform Distribution</figcaption></figure><p>In other words, the PDF of a uniform distribution is a constant value within the interval [a,b] and 0 outside of this interval. The uniform distribution is frequently used to model circumstances in which there is no knowledge about the underlying distribution of the data and all values within the defined range are equally likely.</p><p>A uniform distribution’s expected value (mean) is given by its average or the mean of the distribution. A uniform distribution’s variance is always positive, and it reduces as the interval [a,b] shrinks. It is the most commonly used distribution in real world situations, where the shape of the distribution is assumed to remain constant throughout given we do not much information about the underlying distribution of the population. It is often regarded as a good place to start statistical analysis on.</p><p>The plot of the PDF of a uniform distribution with different parameters a and b, as shown below, looks rectangular and consistent within any interval described by the parameters a an b.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*8vxEJz_paTVzca2Zb9oiag.png" /></figure><p>The purple curve in this plot depicts a uniform distribution with parameters a = 0 and b = 1, the blue curve a uniform distribution with parameters a = 1 and b = 2, the green curve a uniform distribution with parameters a = 2 and b = 4, and the yellow curve a uniform distribution with parameters a = 3 and b = 6. As we can see, the uniform distribution’s shape remains constant, but its range shifts as the parameters a and b change.</p><h4>Usage</h4><p>Here are a few examples of when uniform distribution can be used:</p><ol><li><strong>Rolling a fair die:</strong> All possible outcomes (1, 2, 3, 4, 5, 6) are equally likely when rolling a fair die. In this situation, the uniform distribution with a = 1 and b = 6 can be used to model the probability of each outcome.</li><li><strong>Choosing a random number between 0 and 1:</strong> If a computer creates a random number between 0 and 1, the uniform distribution with a = 0 and b = 1 can be used to model the probability of each outcome.</li><li><strong>Adult male height distribution:</strong> If we measured the height of a random sample of adult males, we may anticipate the distribution of heights to be roughly uniform throughout some interval. The uniform distribution might be used to model the probability of each height in this situation, with a and b being the least and greatest observed heights, respectively.</li><li><strong>Choosing a random point on a circle: </strong>If we were to choose a random point on a circle, we could use the uniform distribution to model the probability of each angle, with a = 0 and b = 360. (degrees).</li></ol><p>These are just a few examples of how uniform distribution might be applied. The parameters a and b define the range of the uniform distribution, which models a situation in which all possible outcomes are equally likely.</p><h4>Relation with other distributions</h4><p>The uniform distribution is related to other distributions in several ways:</p><ul><li><strong>As a building block:</strong> The uniform distribution is often used as a building block for more complex distributions. For example, the triangular distribution, which models a situation where the likelihood of an outcome is greatest at a certain point and decreases linearly to either side, is defined as a mixture of two uniform distributions.</li><li><strong>As a model for lack of information:</strong> As mentioned earlier, the uniform distribution is often used when there is a lack of information about the underlying distribution of the data. In these cases, the uniform distribution is used as a default or prior distribution to capture the uncertainty in the data.</li><li><strong>As a model for continuous data:</strong> The uniform distribution is a continuous distribution, which means it models data that can take on any value within a specified range. This makes it well-suited for modeling continuous data, such as the height of adult males or the weight of a package.</li><li><strong>As a special case of other distributions:</strong> The uniform distribution can also be seen as a special case of other distributions. For example, the uniform distribution is a special case of the beta distribution, with the shape parameters equal to 1.</li></ul><p>Overall, the uniform distribution is a simple but versatile distribution that has a wide range of applications in probability and statistics. It is related to other distributions in various ways, and is often used as a building block or model for data with a lack of information.</p><h3>Gaussian (Normal) Distribution</h3><p>The Gaussian distribution, often known as the normal distribution, is a continuous probability distribution characterized by its probability density function (PDF), which may be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*VUCuulz3cANXVnS0uFz6wQ.gif" /><figcaption>Gaussian Distribution</figcaption></figure><p>The Gaussian distribution is bell-shaped and symmetrical, and it models data that is uniformly distributed on both sides of the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*EJjetBsUGVD5-w1_8XEqJg.png" /><figcaption>Standard Gaussian PDF Curve</figcaption></figure><p>The Gaussian distribution PDF plot is a bell-shaped curve, with the mean in the center and the standard deviation dictating the breadth of the curve. The curve becomes wider and flatter as the standard deviation increases, and narrower and higher as the standard deviation falls.</p><p>The mean is the distribution’s center and indicates the expected value of the data. The standard deviation is a measure of data spread that reflects how far the data deviates from the mean. When we experiment with different mean (mu) and standard deviation (sigma) values to see how the Gaussian bell curve changes, we see that the form of the curve does not change with a change in the mean, with a fixed standard deviation, but the position of the mean merely shifts. When the standard deviation is changed, the graph dramatically alters. A higher standard deviation implies that the data is dispersed over a larger range, whereas a lower standard deviation suggests that the data is more concentrated around the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBR0JA3mWpMIFS8mvn-zhA.png" /></figure><p>The Gaussian distribution is extensively used to model data that is spread out symmetrically about a central value in numerous domains, including engineering, economics, and biology. It is also extensively used as a default or prior distribution in Bayesian statistics, as well as in error and residual modeling in a variety of applications.</p><h4>Usage</h4><p>Here are some Gaussian distribution examples:</p><ol><li><strong>Adult male height:</strong> It is sometimes represented as a Gaussian distribution, with the mean being around 5 feet 10 inches and the standard deviation being approximately 3 inches.</li><li><strong>Test grades: </strong>Test grades can alternatively be modeled as a Gaussian distribution, with the mean being the average grade and the standard deviation indicating how much the grades deviate from the mean.</li><li><strong>Stock Prices: </strong>Stock prices can also be described as a Gaussian distribution, with the mean representing the average daily change and the standard deviation indicating how much the daily changes depart from the mean.</li><li><strong>Regression Analysis: </strong>In regression analysis, the errors or residuals between the expected and actual values are frequently described as a Gaussian distribution, with the mean being zero and the standard deviation being a measure of the prediction’s error or uncertainty.</li><li><strong>Human Blood Pressure: </strong>Human blood pressure can alternatively be described as a Gaussian distribution, with the mean representing the average blood pressure and the standard deviation indicating how much the blood pressure deviates from the mean.</li></ol><p>These are just a few instances of how the Gaussian distribution might be used to model real-world data. The Gaussian distribution is a versatile and adaptable distribution that is frequently utilized in a wide range of applications. Its <strong>symmetrical </strong>and <strong>bell-shaped</strong> shape gives it a suitable fit for a wide range of data sources.</p><h4>Relation with other distributions</h4><p>In numerous ways, the Gaussian distribution is related to other distributions. Here are a few examples of important relationships:</p><ul><li><strong>Central Limit Theorem</strong>: The Central Limit Theorem says that, regardless of the distribution of the individual random variables, the total of a large number of independent and identically distributed (i.i.d.) random variables will converge to a Gaussian distribution. This indicates that the Gaussian distribution can be used to approximate the distribution of a large number of random variables.</li><li><strong>Gaussian Mixture Models (GMM):</strong> Gaussian mixture models are a sort of probabilistic model that consists of a combination of various Gaussian distributions. These models are useful for simulating complex data distributions that can be broken down into numerous Gaussian distributions.</li><li><strong>Gaussian Processes (GP): </strong>Gaussian processes are a form of probabilistic model that is based on the Gaussian distribution. Gaussian processes are utilized for many different applications, such as regression, classification, probabilistic forecasting, hyper-parameter optimization, machine learning, deep learning, reinforcement learning. It forms the basis of Bayesian analysis and optimization.</li><li><strong>Linear regression with Gaussian noise: </strong>Linear regression models are used to simulate the relationship between one or more independent variables and a dependent variable. The errors or residuals between expected and actual values are frequently modeled as a Gaussian distribution, with the mean being zero and the standard deviation representing the prediction’s mistake or uncertainty.</li></ul><p>These are only a few of the many connections between the Gaussian distribution and other distributions. The Gaussian distribution is a well-known and commonly used distribution that is related to a wide range of other distributions and models in statistics and machine learning.</p><h3>Poisson Distribution</h3><p>The Poisson distribution is a discrete probability distribution that models the number of events that occur within a given time or space interval. It is often used to model questions like “<em>How many occurrences of any particular event can be modeled within a given time-frame?</em>”, hence it is widely used in the real world and the industry.</p><h4>PMF, Expectation and Variance</h4><p>The probability mass function (PMF), the expectation, and the variance of the Poisson distribution are shown below. It’s important to remember that the expected number of events doesn’t change over time. This means that the average number of events between any two intervals doesn’t change. To back this up, we can also see that the expectation is the same as the data’s variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*RpKMb6ovx_DqfqqsCrOCuQ.gif" /><figcaption>Poisson Distribution</figcaption></figure><p>The Poisson distribution has several notable characteristics:</p><ul><li>The Poisson distribution’s mean and variance are equal. This suggests that the Poisson distribution is a “<strong>memoryless</strong>” distribution, in the sense that the average number of future events is independent of the number of prior events.</li><li>A limiting instance of the Binomial distribution is the Poisson distribution. The Binomial distribution approaches the Poisson distribution as n approaches infinity and p approaches 0, whereas = np remains constant.</li></ul><p>The Poisson distribution is frequently used to model the number of events that occur within a specified span of time or location, such as the number of calls received by a call center, emails received by a user, or cosmic rays detected by a detector.</p><p>The plot of the Poisson distribution is affected by the value of the expectation. The Poisson distribution is severely skewed to the left for small values of expectation, but it approaches a symmetrical shape for large values of expectation as denoted by the parameter lambda. The Poisson distribution plot for various values of is presented below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*kWSY4i-3NghGJAhCojWBxw.png" /><figcaption>Poisson Distribution</figcaption></figure><h4>Usage</h4><p>The Poisson distribution can be used to model the number of events that occur in a specific interval of time or space given the average number of events per unit of time or space in each of these cases. It could be used to model the number of events in a few different real-world scenarios, such as :</p><ol><li>The number of calls a call center receives in a given hour.</li><li>The number of customers who enter a store during a specific hour.</li><li>The amount of emails a user receives in a given hour.</li><li>The number of accidents at a specific intersection in a given year.</li><li>The number of defective products in a large shipment of items.</li></ol><p>And many more such real world questions.</p><h4>Relation with other Distributions</h4><p>Several other distributions are connected to the Poisson distribution, including:</p><ul><li><strong>Binomial Distribution:</strong> A limiting example of the Binomial distribution is the Poisson distribution. The Binomial distribution approaches the Poisson distribution as n approaches infinity and p approaches 0, whereas = np remains constant.</li><li><strong>Exponential Distribution: </strong>In a Poisson process, the time between subsequent events is exponentially distributed.</li><li><strong>Gaussian Distribution:</strong> According to the central limit theorem, the sum of a large number of independent and identically distributed Poisson variables will tend to follow a Gaussian distribution.</li><li><strong>Poisson Distribution:</strong> The Poisson distribution is a specific case of the Negative Binomial distribution, in which the number of successes is fixed at one and the number of failures is equal to k.</li><li><strong>Gamma Distribution:</strong> The Poisson distribution is a subset of the Gamma distribution with a shape parameter of one.</li></ul><p>Each of these distributions has its own distinct qualities, and the distribution chosen will be determined by the precise requirements of the task at hand. The Poisson distribution, on the other hand, is a good starting point for modeling count data and is frequently employed as a first approximation in many applications.</p><h3>Exponential Distribution</h3><p>In a Poisson process, the Exponential Distribution is a continuous probability distribution that models the time between events. The average rate of events is the single quantity that characterizes the exponential distribution.</p><p>The exponential distribution’s Probability Density Function (PDF) is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Xd8UtzMTSE_9E0n7Mw3XFg.gif" /><figcaption>Exponential Distribution</figcaption></figure><p>As the rate parameter is increased, the PDF steepens and the time between events shortens. In contrast, as the rate falls, the PDF flattens and the interval between events increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*aBv7nWeB6qzLiRLoRqf3mQ.png" /><figcaption>Exponential Distribution</figcaption></figure><h4>Usage</h4><p>Here are a few instances of scenarios that the exponential distribution can model:</p><ol><li>The interval between machine component failures</li><li>The amount of time that passes between client arrivals at a store.</li><li>The amount of time that passes between radioactive decay events</li><li>The interval between calls to a call center</li><li>The amount of time that passes between bus arrivals at a bus stop.</li></ol><p>The rate parameter can be computed from data and used to model the time between occurrences using the exponential distribution in each of these cases.</p><h4>Relation with other distributions</h4><p>In a few ways, the exponential distribution is related to other distributions:</p><ul><li>As a <strong>variant of the gamma distribution:</strong> The exponential distribution is a variant of the gamma distribution with shape parameter k = 1.</li><li>As the <strong>time between events in a Poisson process: </strong>A Poisson process is a discrete-time process in which the exponential distribution models the time between occurrences.</li><li><strong>Memoryless property:</strong> The exponential distribution has a <strong>memoryless </strong>property, which means that its future behavior is unaffected by its past behavior. This is in contrast to memory-containing distributions such as the normal or gamma distributions.</li><li><strong>As a foundation for other distributions:</strong> The exponential distribution can be used to construct other distributions such as the Weibull, extreme value, and log-normal distributions.</li></ul><p>These relationships highlight the exponential distribution’s versatility and utility in simulating real-world occurrences.</p><h3>Conclusion</h3><p>In conclusion, we took a closer look at each probability distribution and attempted to comprehend why it behaves as it does. We conducted a comprehensive ablation study of all parameters and observed how parameter changes induced shifts in the various distributions. We saw uniform distribution, normal distribution and how they are most commonly used distributions in the real world. We also encountered the <strong>memoryless </strong>features of Poisson and exponential distributions, which clarified their applicability in simulations of the real world.</p><p>We examined the article’s detailed examples and scenarios to gain a thorough knowledge of the many circumstances in which these distributions may be applied. The significance of probability distribution lies in the application of these fundamentals to data science challenges in the actual world. Using sophisticated analytics techniques such as Tableau, Power B.I., etc., it is possible to perform more advanced analytics on the data distributions and generate elaborate interactive visualizations and dashboards.</p><p><strong><em>Congratulations</em>, if you made it this far. Can’t thank you enough!!</strong> This is probably the longest article I’ve written on Medium, but I wanted to talk about these distributions in more depth because they are very important and form the basis of any data science. If you want to talk to me or grab some coffee, you can add me on LinkedIn. I’ll accept your request.</p><p>Oh, and if you are still not following me on Medium, I would appreciate you if you could follow me on Medium. It really helps me get the motivation to write more such articles on Data Science, Machine Learning and Artificial Intelligence. I have been thinking of writing about linear algebra and matrices. Let me know if you want me to review Linear Algebra.</p><h3>Author: “Deb”</h3><p>Hit me up on <a href="https://www.linkedin.com/in/debanjanaiml/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2d32cdb37c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>