<?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 Raghav Bali on Medium]]></title>
        <description><![CDATA[Stories by Raghav Bali on Medium]]></description>
        <link>https://medium.com/@Rghv_Bali?source=rss-dff4008c1908------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6nRZK0-KCmkqu5I3auzK3w.png</url>
            <title>Stories by Raghav Bali on Medium</title>
            <link>https://medium.com/@Rghv_Bali?source=rss-dff4008c1908------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:55:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Rghv_Bali/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[Notes on DeepSeek v3]]></title>
            <link>https://medium.com/@Rghv_Bali/notes-on-deepseek-v3-08d5a6388cee?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/08d5a6388cee</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[deepseek-v3]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 14:39:29 GMT</pubDate>
            <atom:updated>2025-01-23T14:39:29.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpvw7JuvX6J1VZZy" /><figcaption>Photo by <a href="https://unsplash.com/@profwicks?utm_source=medium&amp;utm_medium=referral">Ben Wicks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Notes on Deepseek v3</h3><h4>Mixture of Experts Model with 671B params trained cost-effectively</h4><h3>Annotated Paper</h3><ul><li><a href="https://hyp.is/go?url=https%3A%2F%2Farxiv.org%2Fpdf%2F2412.19437&amp;group=__world__">Hypothesis.is annotations</a></li></ul><h3>Contributions/Key Insights</h3><ul><li><a href="https://medium.com/DeepSeekv3">DeepSeekv3</a> is a <a href="https://medium.com/Mixture%20Of%20Experts">MoE</a> <a href="https://medium.com/language%20model">language model</a> with <strong>671B</strong> parameters of with <strong>37B</strong> are activated for each token</li><li>It adopts <a href="https://medium.com/Multi-head%20Latent%20Attention">MLA</a> and <a href="https://medium.com/Mixture%20Of%20Experts">MoE</a> architecture to achieve efficient inference and cost effective training respectively</li><li>The also present an <a href="https://medium.com/auxiliary-loss-free">auxiliary-loss-free</a> strategy for load balancing and <a href="https://medium.com/multi-token%20prediction">MTP</a> training and stronger performance</li><li>It is trained on <strong>14.9trillion</strong> diverse and <a href="https://medium.com/high-quality">high-quality</a> tokens</li><li>They also note that the training process was remarkably stable without any irrecoverable loss spikes or rollback requirements -&gt; <em>these are extreme cost saving aspects</em>.</li><li>To improve the training performance they leverage the <a href="https://medium.com/Fill-in-Middle">FIM</a> strategy. Proposed by <a href="https://medium.com/openAI">openAI</a> originally to help models get better at in-filling text, especially for tasks like doc-string generation. <a href="https://arxiv.org/pdf/2207.14255.pdf">link-1</a> <a href="https://medium.com/@SymeCloud/what-is-fim-and-why-does-it-matter-in-llm-based-ai-53f33385585b">link-2</a></li><li>They enable <em>FP8 mixed precision training</em> through their framework and showcase flexibility and effectiveness of <a href="https://medium.com/FP8">FP8</a> training on extremely large scale models.</li><li>They also designed a <a href="https://medium.com/DualPipe">DualPipe</a> algorithm for efficient pipeline parallelism to achieve extreme levels of utilization. This is coupled with <a href="https://medium.com/cross-node">cross-node</a> <a href="https://medium.com/all-to-all%20communication%20kernels">all-to-all communication kernels</a> to utilize <a href="https://medium.com/infiniBand">IB</a> and<a href="https://medium.com/NVLink">NVLink</a> bandwidths. This works presents how hardware and software optimizations can bring in drastic improvements</li><li>They also talk about a 2 stage context length extension. Step one extends it 32K while stage 2 pushes it to 128k. The SFT and RL stages are done after the context length extension steps.</li><li>The context length extension leverages the <a href="https://medium.com/Yet%20another%20Rope%20extensioN%20method">YaRN</a> : <a href="https://arxiv.org/pdf/2309.00071">link-1</a> <a href="https://medium.com/@rcrajatchawla/understanding-yarn-extending-context-window-of-llms-3f21e3522465">link-2</a></li><li>Their benchmarks/experiments showcase that despite being open-sourced and other optimizations, their model out performs other open-source LLMs while achieving comparable performance to closed source models like <a href="https://medium.com/GPT-4o">GPT-4o</a> and <a href="https://medium.com/Claude-3.5-Sonnet">Claude-3.5-Sonnet</a></li><li>Interestingly the work also shares the overall training time and costs. At 5.576 Million USD (considering $2 per GPU hour for H800 GPU) is probably the most economically trained model (it still is beyond reach of most organizations). They report a pretraining time of less than 2 months on a cluster of 2048 GPUs costing about 2664K GPU hours. The overall training cost (which includes context length extension and post training apart from pretraining) is at 2.788M GPU hours. <em>see table 1</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79yF1IKonh12PnikFEXh0A.png" /><figcaption>Deepseek V3 training costs. Source: <a href="https://arxiv.org/abs/2412.19437">paper</a></figcaption></figure><ul><li>They also showcase innovative methodology to distill reasoning capabilities from long <a href="https://medium.com/Chain%20of%20Thought">CoT</a> model (like <a href="https://medium.com/DeepSeekR1">DeepSeekR1</a>) into standard LLMs (like <a href="https://medium.com/DeepSeekv3">DeepSeekv3</a>). Their approach improves reasoning performance of <a href="https://medium.com/DeepSeekv3">DeepSeekv3</a> by incorporating verification and <a href="https://medium.com/reflection">reflection</a> patterns without impacting output style or length</li></ul><h3>Architecture</h3><ul><li>Extends on the vanilla <a href="https://medium.com/transformer">transformer</a> by introducing improvements through<a href="https://medium.com/Multi-head%20Latent%20Attention">MLA</a> and <a href="https://medium.com/Mixture%20Of%20Experts">MoE</a>. <em>see figure 1</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4RdYI_2ct8qoHr7g8x8VA.png" /><figcaption>High-level architecture. Source: <a href="https://arxiv.org/abs/2412.19437">paper</a></figcaption></figure><h4><a href="https://medium.com/Multi-head%20Latent%20Attention">Multi-head Latent Attention</a></h4><ul><li><a href="https://medium.com/low%20rank%20approximation">low rank approximation</a> for <a href="https://medium.com/attention">attention</a> KV matrices that enables caching and faster inference</li><li>they also use <a href="https://medium.com/low%20rank%20approximation">low rank approximation</a> for attention queries as well.</li><li><a href="https://hyp.is/sKpczNixEe-W9gvTED2zAQ/arxiv.org/pdf/2412.19437">see highlights marked on paper/pdf for equations</a></li></ul><h4><a href="https://medium.com/Mixture%20Of%20Experts">MoE</a> with <a href="https://medium.com/auxiliary-loss-free">auxiliary-loss-free</a> Load Balancing</h4><ul><li>Unlike standard <a href="https://medium.com/Mixture%20Of%20Experts">Mixture Of Experts</a> like <a href="https://medium.com/GShard">GShard</a>, <a href="https://medium.com/DeepSeekv3">DeepSeekv3</a> uses fine-grained experts and also isolates some experts as <em>shared-experts</em>.</li><li><a href="https://hyp.is/xQ4EENiyEe-10duwXjoH1A/arxiv.org/pdf/2412.19437">see highlights for equations</a></li></ul><h3>Hardware Improvements and Evaluation Results</h3><ul><li>The paper provides insights into hardware level improvements, <a href="https://hyp.is/uW8HdtmJEe-Xd2MFA8tVpg/arxiv.org/pdf/2412.19437">see highlights for details</a></li><li>They also present detailed studies on various benchmarks. Particularly impressive are the ablation studies where they discuss the impact of <a href="https://medium.com/multi-token%20prediction">MTP</a> on inference performance (even though it is used only in training phase)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08d5a6388cee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on ByteDance Monolith]]></title>
            <link>https://medium.com/@Rghv_Bali/notes-on-bytedance-monolith-623e3a276f9e?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/623e3a276f9e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[live-streaming-features]]></category>
            <category><![CDATA[online-learning]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 14:42:02 GMT</pubDate>
            <atom:updated>2025-01-16T14:42:02.770Z</atom:updated>
            <content:encoded><![CDATA[<h4>Framework for online training of recommendation models using Tensorflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W26FA2hEJQNHiwWh" /><figcaption>Photo by <a href="https://unsplash.com/@jan_huber?utm_source=medium&amp;utm_medium=referral">Jan Huber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Contributions</h4><ul><li>This system is aimed at <a href="https://medium.com/online%20training">online training</a></li><li>The paper talks about challenges with <a href="https://medium.com/Deep%20Learning">Deep Learning</a> to be around <a href="https://medium.com/feature%20sparsity">feature sparsity</a>, <a href="https://medium.com/categorical">categorical</a> nature as well as <a href="https://medium.com/concept%20drift">concept drift</a> or change in the underlying data distribution</li><li>Unlike <a href="https://medium.com/language%20modeling">language modeling</a>, embeddings in the <a href="https://medium.com/recommendation">recommendation</a> domain:</li></ul><blockquote>have a larger number of users and items as compared to word-pieces which makes it difficult to fit large embeddings tables into memory</blockquote><blockquote>the size of such embedding tables grows over time as more users and products are added to the system</blockquote><blockquote>These challenges along with issues like use of hashing techniques leads to higher chances of hash-key collisions thereby deteriorating model quality.</blockquote><p>The work draws inspiration from <a href="https://medium.com/Tensorflow">Tensorflow</a>’s setup of splitting work between worker nodes and parameter server nodes. They term model weights as dense parameters while embedding tables are for sparse features</p><ul><li>The hashing setup is based on <a href="https://medium.com/Cuckoo%20Hashmap">Cuckoo Hashmap</a> which achieves worstcase time complexity for lookups and deletions and expected amortized time for insertions. It works as follows (quoting from the paper):</li></ul><blockquote>it maintains two tables 𝑇0,𝑇1 with different hash functions ℎ0 (𝑥), ℎ1 (𝑥), and an element would be stored in either one of them. When trying to insert an element 𝐴 into 𝑇0, it first attempts to place 𝐴 at ℎ0 (𝐴); If ℎ0 (𝐴) is occupied by another element 𝐵, it would evict 𝐵 from 𝑇0 and try inserting 𝐵 into 𝑇1 with the same logic. This process will be repeated until all elements stabilize, or rehash happens when insertion runs into a cycle.</blockquote><ul><li>Memory optimizations are achieved through careful hashing of IDs. Since IDs follow a long tailed distribution, the ones which are less frequently occurring have limited to no-impact on the model performance and could be removed to make the setup memory efficient</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DuEEBtk7VITgTZQx7T3Dg.png" /><figcaption>Batch and Online Training Setup. Source: <a href="https://arxiv.org/pdf/2209.07663">Paper</a></figcaption></figure><h4>Training setup is divided into 2 stages:</h4><ul><li>First stage is similar to the usual way of using historical data to perform a <strong>batch training</strong>. The authors point out that they do so for only one pass of the training data and this process is performed when they modify model architecture</li><li>Second stage is <strong>online training</strong>. During this stage, Instead of reading mini-batch examples from the storage, a training worker consumes realtime data on-the-fly and updates the training PS. The training PS periodically synchronizes its parameters to the serving PS, which will take effect on the user side immediately.</li><li>The paper also outlines that the size of the model runs into terabytes but the majority contribution comes from sparse features. To mitigate challenges of network bandwidth and time taken to update the whole model, they maintain a hash-table of IDs/keys that get updated during a specific online training interval (could be a few minutes) and then only push/synchronise those weights while updating the rest of the dense weights less frequently (as they require more data points to see considerable change)</li></ul><h4>Experiments</h4><ul><li><strong>Experiment 1</strong> : The setup is based on <a href="https://medium.com/movielens">movielens</a> dataset and uses a <a href="https://medium.com/deepFM">deepFM</a> model with <a href="https://medium.com/AUC">AUC</a> as the metric for comparison</li><li><strong>Experiment 2</strong>: this setup uses an internal <a href="https://medium.com/multi%20tower">multi tower</a> recommendation model being used in production system at <a href="https://medium.com/bytedance">bytedance</a> and the <a href="https://medium.com/Criteo%20Display%20Ads%20Challenge">Criteo Display Ads Challenge</a> dataset for CTR prediction.</li><li>They use 7 days of data from the dataset for training off which 5 days are for batch training while the remaining 2 days data is used for online training. The 2 days data is split into N shards (where N is experimented with 10,50 and 100) to simulate update intervals of 5hrs, 1hr and 30mins respectively.</li><li><strong>Experiment 3</strong>: An actual live A/B test to compare a batch trained model vs a model regularly updated using <a href="https://medium.com/ByteDance%20Monolith">ByteDance Monolith</a> setup</li></ul><h4>Results</h4><ul><li>Models with <a href="https://medium.com/ByteDance%20Monolith">ByteDance Monolith</a> setup consistently outperform across the three experiments. The models also start at a higher AUC and converge at a higher value as well. These models also seem to be robust against <a href="https://medium.com/concept%20drift">concept drift</a></li><li>Higher frequency of weight updates for online training improves the AUC while being more tolerant as well</li></ul><h4>Annotated Paper</h4><ul><li><a href="https://hyp.is/go?url=https%3A%2F%2Farxiv.org%2Fpdf%2F2209.07663&amp;group=__world__">Link</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623e3a276f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on KaLM-Embedding]]></title>
            <link>https://medium.com/@Rghv_Bali/notes-on-kalm-embedding-25c3e0f60bbb?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c3e0f60bbb</guid>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[language-model]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 16:38:19 GMT</pubDate>
            <atom:updated>2025-01-08T18:53:27.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d7RtMEdQcrTg4UH4" /><figcaption>Photo by <a href="https://unsplash.com/@sebastian123?utm_source=medium&amp;utm_medium=referral">Pereanu Sebastian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Impact of High Quality Training Data</h4><blockquote>Personal notes and annotations from <a href="https://arxiv.org/abs/2501.01028">KaLM-Embedding by Hu et. al.</a></blockquote><h3>Notes</h3><ul><li>The key insight and contribution of this work is: <em>Quality of training data plays a very important role in determining the performance of an embedding model</em></li></ul><h4>Key Contributions include:</h4><ul><li><strong>Massive High Quality Training Dataset</strong> where the pre-training dataset comprised of 20 categories while fine tuning stage leveraged smaller but more in number (70) datasets.</li><li><strong>Persona Based synthetic data</strong>: drawing inspiration from the work of wang et. al they leveraged <a href="https://medium.com/QWen2-72B-Instruct">QWen2–72B-Instruct</a> model to generate 550k synthetic data points using randomly sampled personas from <a href="https://medium.com/Persona%20Hub">Persona Hub</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*dVK0Cd6vFCvREjrfkdELFw.png" /><figcaption>Ranking Consistency Filtering. Source: <a href="https://arxiv.org/abs/2501.01028">Hu et. al</a></figcaption></figure><ul><li><a href="https://medium.com/Ranking%20Consistency%20Filtering"><strong>Ranking Consistency Filtering</strong></a> helps in obtaining hard negative samples from dataset. This is also known as <a href="https://medium.com/top-k%20filtering%20for%20fine-tuning%20data%20selection">top-k filtering for fine-tuning data selection</a>. Quoting from the paper “This method involves ranking the similarity between the query and its original positive example data within the entire document corpus of the dataset, and filtering out samples where the positive example data pair does not rank within the top-k.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*CORe9j9sjjqGu6jhaXn8Pg.png" /><figcaption>Semi-Homogeneous Task Batching. Source: <a href="https://arxiv.org/abs/2501.01028">Hu et. al</a></figcaption></figure><ul><li><strong>Semi-homogeneous Task Batching</strong>: It has been noted that utilization of large homogeneous task batch leads to potentially excessive number of false negatives. To balance this, the proposed approach is to sample and recombine from an initial homogeneous batch by mixing and randomly reassigning back data points to their batches.</li><li><a href="https://medium.com/Matryoshka%20Representation%20Learning"><strong>MRL</strong></a>: Is important to enable the model to function at different granularities and performance constraints.</li><li><strong>Task Instruction</strong>-finetuned language models are known for their strong generalization capabilities, yet this strategy remains underutilized in embedding models. We find that verbalized instructions can significantly enhance the performance of embedding models by reducing ambiguity in the embedding space.</li><li><strong>Loss</strong>: The authors mention InfoNCE loss with temperature parameter set to 0.01 for <a href="https://medium.com/QWen2-0.5B">QWen2–0.5B</a> with mean pooling and maximum input text length of 512 tokens trained with mixed precision <a href="https://medium.com/bf16">bf16</a>.</li></ul><h4>Experiments:</h4><ul><li>The impact of task instruction was clearly evident which is correlated to the diversity of fine-tuning dataset</li><li>impact of <a href="https://medium.com/Matryoshka%20Representation%20Learning">MRL</a> is evident to draw more performance from lower dimensional embeddings.</li><li>Semi-homogeneous Task Batches have a positive impact on retrieval and ranking tasks while negatively impacting classification and clustering tasks</li><li>Increasing the number of training steps per epoch had a positive impact while having larger batch-sizes did not have much impact</li></ul><h4>Discussion Points:</h4><ul><li><a href="https://medium.com/Rotary%20Position%20Embedding">RoPE</a> is a possible way to extend this setup for larger context sequences</li><li>Representation of long texts is better managed through multiple vectors as experimental results indicate that long text embeddings are less effective than <a href="https://medium.com/BM25">BM25</a></li></ul><h4>Annotated Version</h4><p>Check the link below till Medium figures out how to render embedded links (pun not intended).</p><ul><li><a href="https://hyp.is/go?url=https%3A%2F%2Farxiv.org%2Fpdf%2F2501.01028&amp;group=__world__">https://hyp.is/go?url=https%3A%2F%2Farxiv.org%2Fpdf%2F2501.01028&amp;group=__world__</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c3e0f60bbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your LLM Apps using DSPy and Langfuse]]></title>
            <link>https://medium.com/data-science/supercharge-your-llm-apps-using-dspy-and-langfuse-f83c02ba96a1?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83c02ba96a1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[dspy]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 19:12:26 GMT</pubDate>
            <atom:updated>2024-10-08T09:15:04.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharge Your LLM Apps Using DSPy and Langfuse</h3><h4>Build Production Grade LLM Apps with Ease</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FEaR7Tk2RBv_5Mw5" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>The Rise of LLMs</strong></h3><p>Large Language Models (LLMs) have emerged as a transformative force, revolutionizing how we interact with and process information. These powerful AI models, capable of understanding and generating human-like text, have found applications in a wide array of fields, from chatbots and virtual assistants to content creation and data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0UPfd0A5HcNF4stc58wPA.png" /><figcaption>Usual Prompt based development workflow. Source: Author</figcaption></figure><p>However, building and maintaining effective LLM-powered applications is not without its challenges. Prompt engineering, <em>the art of crafting precise instructions for LLMs</em>, can be a time-consuming and iterative process. Debugging and troubleshooting LLM behavior can also be complex, given the inherent “black box” nature of these models. Additionally, gaining insights into the performance and cost implications of LLM applications is crucial for optimization and scalability (key components for any production grade setup).</p><h4><strong>The LLM Ecosystem</strong></h4><p>The ecosystem for LLMs is still in its nascent stages. To address some of these challenges, a number of innovative tools and frameworks are being developed. <a href="https://dspy-docs.vercel.app/">DSPy</a> from Stanford University is one such unique take towards formalizing LLM-based app development. <a href="https://langfuse.com/">Langfuse</a> on the other hand has emerged as an offering to streamline and operationalize aspects of LLM app maintenance. To put it in brief:</p><ul><li><strong>DSPY</strong> provides a modular and composable framework for building LLM applications, abstracting away the complexities of prompt engineering and enabling developers to focus on the core logic of their applications.</li><li><strong>Langfuse</strong> offers a comprehensive observability platform for LLM apps, providing deep insights into model performance, cost, and user interactions.</li></ul><p>By combining DSPy and Langfuse, developers can unlock the full potential of LLMs, building robust, scalable, and insightful applications that deliver exceptional user experiences.</p><h3>Unlocking LLM Potential with DSPy</h3><p>Language Models are extremely complex machines with capabilities to retrieve and reformulate information from an extremely large latent space. To guide this search and achieve desired responses we heavily rely on complex, long and brittle prompts which (at times) are very specific to certain LLMs.</p><p>Being an open area of research, teams are working from different perspectives to abstract and enable rapid development of LLM-enabled systems. DSPy is one such framework for algorithmically optimizing LLM prompts and <em>weights</em>.</p><h4><strong>Ok, You Got Me Intrigued, Tell Me More?</strong></h4><p>The DSPy framework takes inspiration from deep learning frameworks such as <em>PyTorch.</em></p><p>For instance, to build a deep neural network using PyTorch we simply use standard layers such as <em>convolution</em>, <em>dropout</em>, <em>linear</em> and attach them to optimizers like <em>Adam</em> and train without worrying about implementing these from scratch every time.</p><p>Similarly, DSPy provides a a set of standard general purpose modules (such as <em>ChainOfThought</em>,<em>Predict</em>), optimizers (such as <em>BootstrapFewShotWithRandomSearch</em>) and helps us build systems by composing these components as layers into a <em>Program</em> without explicitly dealing with prompts! Neat isn’t it?</p><h4><strong>The DSPy Building Blocks &amp; Workflow</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNTpRHEDAonoBjwelknAiQ.png" /><figcaption>Figure 1: (left) DSPy Building Blocks consisting of Signatures, Modules, Optimizers. (right) DSPy Program workflow. Source: Author</figcaption></figure><p>As illustrated in <em>figure 1</em>, DSPy is a pytorch-like/lego-like framework for building LLM-based apps. Out of the box, it comes with:</p><ul><li><a href="https://dspy-docs.vercel.app/docs/building-blocks/signatures"><strong>Signatures</strong></a>: These are specifications to define input and output behaviour of a DSPy program. These can be defined using <em>short-hand</em> notation (like “question -&gt; answer” where the framework automatically understands question is the input while answer is the output) or using <em>declarative specification </em>using python classes (more on this in later sections)</li><li><a href="https://dspy-docs.vercel.app/docs/building-blocks/modules"><strong>Modules</strong></a>: These are layers of predefined components for powerful concepts like <em>Chain of Thought</em>, <em>ReAct</em> or even the simple text completion (Predict). These modules abstract underlying brittle prompts while still providing extensibility through custom components.</li><li><a href="https://dspy-docs.vercel.app/docs/building-blocks/optimizers"><strong>Optimizers</strong></a>: These are unique to DSPy framework and draw inspiration from PyTorch itself. These optimizers make use of annotated datasets and evaluation metrics to help tune/optimize our LLM-powered DSPy programs.</li><li><strong>Data</strong>, <strong>Metrics</strong>, <a href="https://dspy-docs.vercel.app/docs/building-blocks/assertions"><strong>Assertions</strong></a> and <strong>Trackers</strong> are some of the other components of this framework which act as glue and work behind the scenes to enrich this overall framework.</li></ul><p>To build an app/program using DSPy, we go through a modular yet step by step approach (as shown in <em>figure 1 (right)</em>). We first define our <em>task</em> to help us clearly define our program’s signature (input and output specifications). This is followed by building a <em>pipeline</em> program which makes use of one or more abstracted prompt modules, language model module as well as retrieval model modules. One we have all of this in place, we then proceed to have some <em>examples</em> along with required metrics to <em>evaluate</em> our setup which are used by <em>optimizers</em> and <em>assertion</em> components<em> </em>to <em>compile</em> a powerful app.</p><h3>Gaining LLM Insights with Langfuse</h3><p>Langfuse is an LLM Engineering platform designed to empower developers in building, managing, and optimizing LLM-powered applications. While it offers both managed and self-hosting solutions, we’ll focus on the self-hosting option in this post, providing you with complete control over your LLM infrastructure.</p><h4><strong>Key Highlights of Langfuse Setup</strong></h4><p>Langfuse equips you with a suite of powerful tools to streamline the LLM development workflow:</p><ul><li><strong>Prompt Management:</strong> Effortlessly version and retrieve prompts, ensuring reproducibility and facilitating experimentation.</li><li><strong>Tracing:</strong> Gain deep visibility into your LLM applications with detailed traces, enabling efficient debugging and troubleshooting. The intuitive UI out of the box enables teams to annotate model interactions to develop and evaluate training datasets.</li><li><strong>Metrics:</strong> Track crucial metrics such as cost, latency, and token usage, empowering you to optimize performance and control expenses.</li><li><strong>Evaluation:</strong> Capture user feedback, annotate LLM responses, and even set up evaluation functions to continuously assess and improve your models.</li><li><strong>Datasets:</strong> Manage and organize datasets derived from your LLM applications, facilitating further fine-tuning and model enhancement.</li></ul><h4><strong>Effortless Setup</strong></h4><p>Langfuse’s self-hosting solution is remarkably easy to set up, leveraging a <em>docker</em>-based architecture that you can quickly spin up using <em>docker compose</em>. This streamlined approach minimizes deployment complexities and allows you to focus on building your LLM applications.</p><h4><strong>Framework Compatibility</strong></h4><p>Langfuse seamlessly integrates with popular LLM frameworks like <a href="https://www.langchain.com/">LangChain</a>, <a href="https://www.llamaindex.ai/">LlamaIndex</a>, and, of course, DSPy, making it a versatile tool for a wide range of LLM development frameworks.</p><h3>The Power of DSPY + Langfuse</h3><p>By integrating Langfuse into your DSPy applications, you unlock a wealth of observability capabilities that enable you to monitor, analyze, and optimize your models in real time.</p><h4><strong>Integrating Langfuse into Your DSPy App</strong></h4><p>The integration process is straightforward and involves instrumenting your DSPy code with Langfuse’s SDK.</p><pre>import dspy<br>from dsp.trackers.langfuse_tracker import LangfuseTracker<br><br># configure tracker <br>langfuse = LangfuseTracker()<br><br># instantiate openai client<br>openai = dspy.OpenAI(<br>                      model=&#39;gpt-4o-mini&#39;, <br>                      temperature=0.5, <br>                      max_tokens=1500<br>          )<br><br># dspy predict supercharged with automatic langfuse trackers <br>openai(&quot;What is DSPy?&quot;)</pre><h4><strong>Gaining Insights with Langfuse</strong></h4><p>Once integrated, Langfuse provides a number of actionable insights into your DSPy application’s behavior:</p><ul><li><strong>Trace-Based Debugging:</strong> Follow the execution flow of your DSPY programs, pinpoint bottlenecks, and identify areas for improvement.</li><li><strong>Performance Monitoring:</strong> Track key metrics like latency and token usage to ensure optimal performance and cost-efficiency.</li><li><strong>User Interaction Analysis:</strong> Understand how users interact with your LLM app, identify common queries, and opportunities for enhancement.</li><li><strong>Data Collection &amp; Fine-Tuning:</strong> Collect and annotate LLM responses, building valuable datasets for further fine-tuning and model refinement.</li></ul><h4><strong>Use Cases Amplified</strong></h4><p>The combination of DSPy and Langfuse is particularly important in the following scenarios:</p><ul><li><strong>Complex Pipelines:</strong> When dealing with complex DSPy pipelines involving multiple modules, Langfuse’s tracing capabilities become indispensable for debugging and understanding the flow of information.</li><li><strong>Production Environments:</strong> In production settings, Langfuse’s monitoring features ensure your LLM app runs smoothly, providing early warnings of potential issues while keeping an eye on costs involved.</li><li><strong>Iterative Development:</strong> Langfuse’s evaluation and dataset management tools facilitate data-driven iteration, allowing you to continuously refine your LLM app based on real-world usage.</li></ul><h3>The Meta Use Case: Q&amp;A Bot for my Workshop</h3><p>To truly showcase the power and versatility of DSPy combined with amazing monitoring capabilities of langfuse, I’ve recently applied them to a unique dataset: my recent <a href="https://github.com/raghavbali/llm_workshop">LLM workshop GitHub repository</a>. This recent full day workshop contains a lot of material to get you started with LLMs. The aim of this Q&amp;A bot was to assist participants during and after the workshop with answers to a host NLP and LLM related topics covered in the workshop. This “meta” use case not only demonstrates the practical application of these tools but also adds a touch of self-reflection to our exploration.</p><h4><strong>The Task: Building a Q&amp;A System</strong></h4><p>For this exercise, we’ll leverage DSPy to build a Q&amp;A system capable of answering questions about the content of my workshop (notebooks, markdown files, etc.). This task highlights DSPy’s ability to process and extract information from textual data, a crucial capability for a wide range of LLM applications. Imagine having a personal AI assistant (or co-pilot) that can help you recall details from your past weeks, identify patterns in your work, or even surface forgotten insights! It also presents a strong case of how such a modular setup can be easily extended to any other textual dataset with little to no effort.</p><p>Let us begin by setting up the required objects for our program.</p><pre>import os<br>import dspy<br>from dsp.trackers.langfuse_tracker import LangfuseTracker<br><br>config = {<br>    &#39;LANGFUSE_PUBLIC_KEY&#39;: &#39;XXXXXX&#39;,<br>    &#39;LANGFUSE_SECRET_KEY&#39;: &#39;XXXXXX&#39;,<br>    &#39;LANGFUSE_HOST&#39;: &#39;http://localhost:3000&#39;,<br>    &#39;OPENAI_API_KEY&#39;: &#39;XXXXXX&#39;,<br>    &#39;OPENAI_BASE_URL&#39;: &#39;XXXXXX&#39;,<br>    &#39;OPENAI_PROVIDER&#39;: &#39;XXXXXX&#39;,<br>    &#39;CHROMA_DB_PATH&#39;: &#39;./chromadb/&#39;,<br>    &#39;CHROMA_COLLECTION_NAME&#39;:&quot;supercharged_workshop_collection&quot;,<br>    &#39;CHROMA_EMB_MODEL&#39;: &#39;all-MiniLM-L6-v2&#39;<br>}<br><br># setting config<br>os.environ[&quot;LANGFUSE_PUBLIC_KEY&quot;] = config.get(&#39;LANGFUSE_PUBLIC_KEY&#39;)<br>os.environ[&quot;LANGFUSE_SECRET_KEY&quot;] = config.get(&#39;LANGFUSE_SECRET_KEY&#39;)<br>os.environ[&quot;LANGFUSE_HOST&quot;] = config.get(&#39;LANGFUSE_HOST&#39;)<br>os.environ[&quot;OPENAI_API_KEY&quot;] = config.get(&#39;OPENAI_API_KEY&#39;)<br><br># setup Langfuse tracker<br>langfuse_tracker = LangfuseTracker(session_id=&#39;supercharger001&#39;)<br><br># instantiate language-model for DSPY<br>llm_model = dspy.OpenAI(<br>    api_key=config.get(&#39;OPENAI_API_KEY&#39;),<br>    model=&#39;gpt-4o-mini&#39;<br>)<br><br># instantiate chromadb client<br>chroma_emb_fn = embedding_functions.\<br>                    SentenceTransformerEmbeddingFunction(<br>                        model_name=config.get(<br>                            &#39;CHROMA_EMB_MODEL&#39;<br>                        )<br>                    )<br>client = chromadb.HttpClient()<br><br><br># setup chromadb collection<br>collection = client.create_collection(<br>    config.get(&#39;CHROMA_COLLECTION_NAME&#39;),<br>    embedding_function=chroma_emb_fn,<br>    metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;}<br>)</pre><p>Once we have these clients and trackers in place, let us quickly add some documents to our collection (refer to this <a href="https://github.com/raghavbali/llm_workshop/blob/main/module_04/06_supercharge_llm_apps.ipynb">notebook</a> for a detailed walk through of how I prepared this dataset in the first place).</p><pre># Add to collection<br>collection.add(<br>    documents=[v for _,v in nb_scraper.notebook_md_dict.items()], <br>    ids=doc_ids, # must be unique for each doc<br>)</pre><p>The next step is to simply connect our chromadb retriever to the DSPy framework. The following snippet created a RM object and tests if the retrieval works as intended.</p><pre>retriever_model = ChromadbRM(<br>    config.get(&#39;CHROMA_COLLECTION_NAME&#39;),<br>    config.get(&#39;CHROMA_DB_PATH&#39;),<br>    embedding_function=chroma_emb_fn,<br>    client=client,<br>    k=5<br>)<br><br># Test Retrieval<br>results = retriever_model(&quot;RLHF&quot;)<br>for result in results:<br>    display(Markdown(f&quot;__Document__::{result.long_text[:100]}... \n&quot;))<br>    display(Markdown(f&quot;&gt;- __Document id__::{result.id} \n&gt;- __Document score__::{result.score}&quot;))</pre><p>The output looks promising given that without any intervention, Chromadb is able to fetch the most relevant documents.</p><pre>Document::# Quick Overview of RLFH<br><br>The performance of Language Models until GPT-3 was kind of amazing as-is. ...<br><br>- Document id::6_module_03_03_RLHF_phi2<br>- Document score::0.6174977412306334<br><br>Document::# Getting Started : Text Representation Image<br><br>The NLP domain ...<br><br>- Document id::2_module_01_02_getting_started<br>- Document score::0.8062083377747705<br><br>Document::# Text Generation &lt;a target=&quot;_blank&quot; href=&quot;https://colab.research.google.com/github/raghavbali/llm_w&quot; &gt; ...<br><br>- Document id::3_module_02_02_simple_text_generator<br>- Document score::0.8826038964887366<br><br>Document::# Image DSPy: Beyond Prompting<br>&lt;img src= &quot;./assets/dspy_b&quot; &gt; ...<br><br>- Document id::12_module_04_05_dspy_demo<br>- Document score::0.9200280698248913</pre><p>The final step is to piece all of this together in preparing a DSPy program. For our simple Q&amp;A use-case we make prepare a standard RAG program leveraging Chromadb as our retriever and Langfuse as our tracker. The following snippet presents the pytorch-like approach of developing LLM based apps without worrying about brittle prompts!</p><pre># RAG Signature<br>class GenerateAnswer(dspy.Signature):<br>    &quot;&quot;&quot;Answer questions with short factoid answers.&quot;&quot;&quot;<br><br>    context = dspy.InputField(desc=&quot;may contain relevant facts&quot;)<br>    question = dspy.InputField()<br>    answer = dspy.OutputField(desc=&quot;often less than 50 words&quot;)<br><br># RAG Program<br>class RAG(dspy.Module):<br>    def __init__(self, num_passages=3):<br>        super().__init__()<br><br>        self.retrieve = dspy.Retrieve(k=num_passages)<br>        self.generate_answer = dspy.ChainOfThought(GenerateAnswer)<br>    <br>    def forward(self, question):<br>        context = self.retrieve(question).passages<br>        prediction = self.generate_answer(context=context, question=question)<br>        return dspy.Prediction(context=context, answer=prediction.answer)<br><br><br># compile a RAG<br># note: we are not using any optimizers for this example<br>compiled_rag = RAG()</pre><p>Phew! Wasn’t that quick and simple to do? Let us now put this into action using a few sample questions.</p><pre>my_questions = [<br>    &quot;List the models covered in module03&quot;,<br>    &quot;Brief summary of module02&quot;,<br>    &quot;What is LLaMA?&quot;<br>]<br><br>for question in my_questions:<br>    # Get the prediction. This contains `pred.context` and `pred.answer`.<br>    pred = compiled_rag(question)<br>    <br>    display(Markdown(f&quot;__Question__: {question}&quot;))<br>    display(Markdown(f&quot;__Predicted Answer__: _{pred.answer}_&quot;))<br>    display(Markdown(&quot;__Retrieved Contexts (truncated):__&quot;))<br>    for idx,cont in enumerate(pred.context):<br>        print(f&quot;{idx+1}. {cont[:200]}...&quot; )<br>        print()<br>    display(Markdown(&#39;---&#39;))</pre><p>The output is indeed quite on point and serves the purpose of being an assistant to this workshop material answering questions and guiding the attendees nicely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXrIsae1iDWPQdr3rtU4ug.png" /><figcaption>Figure 2: Output from the DSPy RAG program. Source: Author</figcaption></figure><h4><strong>The Langfuse Advantage</strong></h4><p>Earlier in this article we discussed how langfuse completes the picture by enabling us to monitor LLM usage and improve upon other aspects of the pipeline. The amazing integration of langfuse as a tracker glues everything behind the scenes with a nice and easy to use interface. For our current setting, the langfuse dashboard presents a quick summary of our LLM usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xs5l0iEp3Y1Fz-VN9w3iHw.png" /><figcaption>Figure 3: Langfuse Dashboard. Source: Author</figcaption></figure><p>The dashboard is complete with metrics such as number of traces, overall costs and even token usage (which is quite handy when it comes to optimize your pipelines).</p><h4><strong>Insights and Benefits</strong></h4><p>Langfuse’s utility does not end with top-level dashboard of metrics. It provides trace level details (as shown in <em>figure 4</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuhQW2MeGMsaXyJ21B0mtQ.png" /><figcaption>Figure 4: Langfuse trace detail complete with cost, token usage, prompt as well as the model response. Source: Author.</figcaption></figure><p>This interface is a gateway to a number of other aspects that are very useful in terms of iterating and improving LLM based apps. The first and foremost capability is to prepare datasets based on real world usage. These datasets can be used for fine-tuning LLMs, optimizing DSPy programs, etc. <em>Figure 5</em> illustrates how simple it is to define a dataset from the web-UI itself and then add traces (input request along with model’s response) as needed to the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Edf9l-vQ_3wm3Y15J3bA5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyWOt3ByEzIME4f1H8Owjw.png" /><figcaption>Figure 5: (left) Create a new dataset from the web UI directly by simply providing the required details such as dataset name and description. (right) traces can be added to datasets at the click of a button. Source: Author</figcaption></figure><p>Similar to dataset creation and adding data points to it, langfuse simplifies creation of metrics and annotating datapoints. <em>Figure 6</em> illustrates how simple it is to do the same at the click of a couple of buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A2qsbyLwqc_0OLrmoM8Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZ-K7lS9Yo_1eXce6m5L5w.png" /><figcaption>Figure 6: Metric creation and annotation in Langfuse. Source: Author</figcaption></figure><p>Once we have a dataset prepared, langfuse provides a straightforward SDK to use it in your language of of preference. The following snippet makes use of get_dataset utility from langfuse to get to a couple of traces we added to the sample dataset. We then use LLaMA 3.1 to power our DSPy RAG program with just one line change (talk about modularity ;) ).</p><pre># get annotated dataset<br>annotated_dataset = langfuse.get_dataset(&quot;llm_workshop_rag&quot;)<br><br># ensure ollama is available in your environment<br>ollama_dspy = dspy.OllamaLocal(model=&#39;llama3.1&#39;,temperature=0.5)<br><br># get langfuse client from the dspy tracker object<br>langfuse =langfuse_tracker.langfuse<br><br># Set up the ollama as LM and RM<br>dspy.settings.configure(lm=ollama_dspy,rm=retriever_model)<br><br># test rag using ollama<br>ollama_rag = RAG()<br><br># iterate through samples from the annotated dataset<br>for item in annotated_dataset.items:<br>    question = item.input[0][&#39;content&#39;].split(&#39;Question: &#39;)[-1].split(&#39;\n&#39;)[0]<br>    answer = item.expected_output[&#39;content&#39;].split(&#39;Answer: &#39;)[-1]<br>    o_pred = ollama_rag(question)<br>    <br>    # add observations to dataset related experiments<br>    with item.observe(<br>        run_name=&#39;ollama_experiment&#39;,<br>        run_description=&#39;compare LLaMA3.1 RAG vs GPT4o-mini RAG &#39;,<br>        run_metadata={&quot;model&quot;: &quot;llama3.1&quot;},<br>    ) as trace_id:<br>        langfuse.score(<br>            name=&quot;visual-eval&quot;,<br>            # any float value<br>            value=1.0,<br>            comment=&quot;LLaMA3.1 is very verbose&quot;,<br>        )<br>    # attach trace with new run<br>    langfuse.trace(input=question,output=o_pred.answer,metadata={&#39;model&#39;:&#39;LLaMA3.1&#39;})<br>    display(Markdown(f&quot;__Question__: {question}&quot;))<br>    display(Markdown(f&quot;__Predicted Answer (LLaMA 3.1)__: {o_pred.answer}&quot;))<br>    display(Markdown(f&quot;&gt;__Annotated Answer (GPT-4o-mini)__: _{answer}_&quot;))</pre><p>As shown in the above snippet, we simply iterate through the datapoints in our dataset and visually compare the output from both models (see <em>figure 7</em>). Using Langfuse SDK we attach experiment observations along with new traces and evaluation scores very easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5N6iXiINW2osygPtZA8B5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyob5ISd2-OPN-LRHg-U8g.png" /><figcaption>Figure 7: Output from LLaMA3.1 powered RAG using datapoints from dataset prepared using Langfuse</figcaption></figure><p>The output presented in figure 7 clearly shows how LLaMA3.1 powered RAG does answer the questions but strays from the instructions of being brief. This can be easily captured using DSPy assertions as well as scores can be tracked using langfuse SDK for further improvements.</p><h3>Conclusion</h3><p>In this rapidly evolving landscape of LLM applications, tools like DSPy and Langfuse emerge as invaluable allies for developers &amp; data scientists. DSPy streamlines the development process, empowering you to build sophisticated LLM applications with ease and efficiency. Meanwhile, Langfuse provides the crucial observability layer, enabling you to gain deep insights into your models’ performance, optimize resource utilization, and continuously improve your applications based on real-world data.</p><p>The combination of DSPY and Langfuse unlocks a world of possibilities, allowing you to harness the full potential of LLMs. Whether you’re building Q&amp;A systems, content generators, or any other LLM-powered application, these tools provide the foundation for creating robust, scalable, and insightful solutions.</p><p>As I’ve demonstrated through the meta usecase of answering questions for my recent LLM-workshop, DSPy and Langfuse can be applied creatively to extract valuable insights from even your own personal data. The possibilities are truly endless.</p><p>I encourage you to explore these tools/frameworks in your own projects. Interested folks can leverage the comprehensive hands-on driven workshop material for more topics on my <a href="https://github.com/raghavbali/llm_workshop">GitHub repository</a>. With these tools at your disposal, you’re well-equipped to <strong><em>supercharge</em></strong> your LLM applications and stay ahead in the ever-evolving world of AI.</p><p><em>Disclaimer: I have no affiliations, financial or otherwise, with any of the tools, products, or companies mentioned in this article. The opinions and insights shared are based solely on personal experience and independent research.</em></p><h3>References</h3><ul><li><a href="https://dspy-docs.vercel.app/">DSPy</a></li><li><a href="https://langfuse.com/">Langfuse</a></li></ul><p><a href="https://github.com/raghavbali/llm_workshop.git">GitHub - raghavbali/llm_workshop: LLM Workshop 2024</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83c02ba96a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/supercharge-your-llm-apps-using-dspy-and-langfuse-f83c02ba96a1">Supercharge Your LLM Apps using DSPy and Langfuse</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Object Detection with SSD and YoLO Models — A Comprehensive Beginner’s Guide (Part 3)]]></title>
            <link>https://medium.com/data-science/efficient-object-detection-with-ssd-and-yolo-models-a-comprehensive-beginners-guide-part-3-2b0c720175d5?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b0c720175d5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 17:46:33 GMT</pubDate>
            <atom:updated>2024-03-08T20:23:38.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Object Detection with SSD and YoLO Models — A Comprehensive Beginner’s Guide (Part 3)</h3><h4>Learn about single stage object detection models and different trade-offs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mx5bOzZojqoTs3zq" /><figcaption>Photo by <a href="https://unsplash.com/@othentikisra?utm_source=medium&amp;utm_medium=referral">israel palacio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this beginner’s guide series on Object Detection models, we have so far covered the <a href="https://medium.com/towards-data-science/object-detection-basics-a-comprehensive-beginners-guide-part-1-f57380c89b78">basics of object detection</a> (part-I) and the <a href="https://medium.com/towards-data-science/exploring-object-detection-with-r-cnn-models-a-comprehensive-beginners-guide-part-2-685bc89775e2">R-CNN family of object detection models</a> (part-II). We will now focus on some of the famous <strong>single-stage object detection</strong> models in this article. These models improve upon the speed of inference drastically over multi-stage detectors but fall short of the mAP and other detection metrics. Let’s get into the details for these models.</p><h3>Single Shot Multi-box Detectors</h3><p>The <a href="https://arxiv.org/abs/1512.02325">Single Shot Multibox Detector (SSD)</a> architecture was presented by Liu et. al. back in 2016 as a highly performant single-stage object detection model. This paper presented a model which was as performant (mAP wise) as Faster R-CNN but faster by a good margin for both training and inference activities.</p><p>The main difference between the R-CNN family and SSDs is the missing region proposal component (RPN). The SSD family of models do not start from a selective search algorithm or an RPN to find ROIs. SSD takes a convolutional approach to work on this task of object detection. It produces a predefined number of bounding boxes and corresponding class scores as its final output. It starts off with a large pre-trained network such as VGG-16 which is truncated before any of the classification layers start. This is termed as the base-network in SSD terminology. The base-network is followed by a unique auxiliary structure to produce the required outputs. The following are the key components:</p><ul><li><strong>Multi-Scale Feature Maps</strong>: the auxiliary structure after the base-network is a sequence of convolutional layers. These layers progressively decrease the scale or resolution of feature maps. This comes in handy to detect objects of different size (relative to the image). The SSD network takes a convolutional approach to define class scores as well as relative offset values for the bounding boxes. For instance, the network uses a 3x3xp filter on a feature map of m x n x p, where p is the number of channels. The model produces an output for each cell of m x n where the filter is applied.</li><li><strong>Default Anchor Boxes</strong>: The network makes use of a set of predefined anchor boxes (at different scales and aspect ratios). For a given feature map of size m x n, k number of such default anchor boxes are applied for each cell. These default anchor boxes are termed as priors in case of SSDs. For each prior in each cell, the model generates c class scores and 4 coordinates for the bounding boxes. Thus, in total for a feature map of size m x n the model generates a total of (c+4)kmn outputs. These outputs are generated from feature maps taken from different depths of the network which is the key to handle multiple sized objects in a single pass.</li></ul><p>Figure 1 depicts the high-level architecture for SSD with the base-network as VGG-16 followed by auxiliary convolutional layers to assist with multi-scale feature maps.</p><figure><img alt="Figure 1: High-level SSD architecture based on VGG-16. The architecture shows extra feature layers added to detect objects of different sizes." src="https://cdn-images-1.medium.com/max/1024/1*m7guK7dBvnDTELHKeHpflA.png" /><figcaption>Figure 1: High-level SSD architecture based on VGG-16. The architecture shows extra feature layers added to detect objects of different sizes. Source: Author</figcaption></figure><p>As shown in figure 1, the model generates a total of 8732 predictions which are then analyzed through Non-Maximum Suppression algorithm for finally getting one bounding box per identified object. In the paper, authors present performance metrics (FPS and mAP) for two variants, SSD-300 and SSD-512, where the number denotes the size of input image. Both variants are faster and equally performant (in terms of mAP) as compared to R-CNNs with SSD-300 achieving way more FPS as compared to SSD-512.</p><p>As we just discussed, SSD produces a very large number of outputs per feature map. This creates a huge imbalance between positive and negative classes (to ensure coverage, the number of false positives is very large). To handle this and a few other nuances, the authors detail techniques such as <em>hard negative mining</em> and <em>data augmentation</em>. I encourage readers to go through this well drafted paper for more details.</p><h3>You Look only Once (YOLO)</h3><p>In the year 2016, another popular single-stage object detection architecture was presented by Redmon et. al. in their paper titled “<a href="https://arxiv.org/abs/1506.02640">You Only Look Once: Unified, Real-time Object Detection</a>”. This architecture came up around the same time as SSD but took a slightly different approach to tackle object detection using a single-stage model. Just like the R-CNN family, the YOLO class of models have also evolved over the years with subsequent versions improving upon the previous one. Let us first understand the key aspects of this work.</p><p>YOLO is inspired by the <em>GoogleNet</em> architecture for image classification. Similar to GoogleNet, YOLO uses 24 convolutional layers pre-trained on the ImageNet dataset. The pretrained network uses training images of size 224x224 but once trained, the model is used with rescaled inputs of size 448x448. This rescaling was done to ensure that the model picks up small and large objects without issues. It starts off by dividing the input image into an S x S grid (paper mentions a grid of 7x7 for PASCAL VOC dataset). Each cell in the grid predicts B bounding boxes, its objectness score along with confidence score for each of the classes. Thus, similar to SSD each cell in case YOLO outputs 4 coordinates of the bounding boxes plus one objectness score followed by C class prediction probabilities. In total, we get S x S x (Bx5 +C) outputs per input image. The number of output bounding boxes is extremely high, similar to SSDs. These are reduced to a single bounding box per object using NMS algorithm. Figure 2 depicts the overall YOLO setup.</p><figure><img alt="Figure 2: High-level YOLO architecture which uses 24 convolutional layers followed by a few fully connected layers for final prediction." src="https://cdn-images-1.medium.com/max/1024/1*4Uuzj2AsL1oGGJGs_5HaxA.png" /><figcaption>Figure 2: High-level YOLO architecture which uses 24 convolutional layers followed by a few fully connected layers for final prediction. Source: Author</figcaption></figure><p>As shown in figure 2, the presence of fully connected layers in YOLO is in contrast with SSD, which is entirely convolutional in design. YOLO is built using an opensource framework called Darknet and boasts of 45FPS inference speed. Its speed comes at the cost of its detection accuracy. Particularly, YOLO has limitations when it comes to identification of smaller objects as well as cases where the objects are overlapping.</p><p><strong>YOLOv2 or </strong><a href="https://arxiv.org/abs/1612.08242"><strong>YOLO-9000</strong></a> came the very next year (2017) with capability to detect 9000 objects (hence the name) at 45–90 frames per second! One of the minor changes they did was to add an additional step before simply rescaling the inputs to 448x448. Instead, the authors added an additional step where once the original classification model (with input size 224x224) is trained, they rescale the input to 448x448 and fine-tune for a bit more. This enables the model to adapt for larger resolution better and thus improve detection for smaller objects. Also, the convolutional model used is a 30-layer CNN. The second modification was to use anchor boxes and this implementation tries to get the size and number calculated based on the characteristics of the training data (this is in contrast to SSD which simply uses a predefined list of anchor boxes). The final change was to introduce multi-scale training, i.e. instead of just training for a given size the author trained the model at different resolutions to help the model learn features for different sized objects. The changes helped in improving model performance to a good extent (see paper for exact numbers and experiments).</p><p><a href="https://arxiv.org/abs/1804.02767"><strong>YOLOv3</strong></a> was presented in 2018 to overcome the mAP shortfall of YOLOv2. This third iteration of the model used a deeper convolutional network with 53 layers as opposed to 24 in the initial version. Another 53 layers are stacked on top of the pre-trained model for detection task. It also uses residual blocks, skip-connections and up-sampling layers to improve performance in general (note that the time the first two version were released some of these concepts were still not commonly used). To better handle different sized objects, this version makes predictions at different depth of the network. The YOLOv3 architecture is depicted in figure 3 for reference.</p><figure><img alt="Figure 3: YOLOv3 high-level architecture with Darknet-53 and multi-scale prediction branches." src="https://cdn-images-1.medium.com/max/1024/1*z1IYbqvcI9p1jmtMxH68zw.png" /><figcaption>Figure 3: YOLOv3 high-level architecture with Darknet-53 and multi-scale prediction branches. Source: Author</figcaption></figure><p>As shown in figure 3, the model branches off from layer 79 and makes predictions at layers 82, 94 and 106 at scales 13x13, 26x26 and 52x52 for large, medium and small sized objects respectively. The model uses 9 anchor boxes, 3 for each scale to handle different shapes as well. This in-turn increases the total number of predictions the model makes per object. The final step is application of NMS to reduce the output to just one bounding box per object detected. Another key change introduced with YOLOv3 was the use of sigmoid loss for class detection in place of softmax. This change helps in handling scenarios where we have overlapping objects.</p><p>While the original author of the YOLO model, Joseph Redmon, ceased his work on <a href="https://twitter.com/pjreddie/status/1230523827446091776">object detection</a><a href="#_ftn1">[1]</a>, the overall computer vision community did not stop. There was a subsequent release called <a href="https://arxiv.org/abs/2004.10934"><strong>YOLOv4</strong></a> in 2020 followed by another fork titled <a href="https://github.com/ultralytics/yolov5"><strong>YOLOv5</strong></a> a few weeks later (please note that there is no official paper/publication with details of this work). While there are open questions on whether these subsequent releases should carry the YOLO name, it is interesting to see the ideas being refined and carried forward. At the time of writing this article, <strong>YOLOv8</strong> is already available for general use while <a href="https://arxiv.org/abs/2402.13616"><strong>YOLOv9</strong></a> is pushing efficiencies and other benchmarks even further.</p><p>This concludes our brief on different object detection models, both multi-stage and single stage. We have covered key components and major contributions to better understand these models. There are a number of other implementations such as <em>SPP-Net, RetinaNet</em>, etc. which have a different take on the task of object detection. While different, the ideas still conform to the general framework we discussed in this series. In the next article, let us get our hands dirty with some object detection models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b0c720175d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/efficient-object-detection-with-ssd-and-yolo-models-a-comprehensive-beginners-guide-part-3-2b0c720175d5">Efficient Object Detection with SSD and YoLO Models — A Comprehensive Beginner’s Guide (Part 3)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Object Detection with R-CNN Models — A Comprehensive Beginner’s Guide (Part 2)]]></title>
            <link>https://medium.com/data-science/exploring-object-detection-with-r-cnn-models-a-comprehensive-beginners-guide-part-2-685bc89775e2?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/685bc89775e2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 02:28:26 GMT</pubDate>
            <atom:updated>2024-02-17T02:28:26.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Object Detection with R-CNN Models — A Comprehensive Beginner’s Guide (Part 2)</h3><h4>Object detection models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iS8U_4PDeGERdC7A" /><figcaption>Photo by <a href="https://unsplash.com/@datalore?utm_source=medium&amp;utm_medium=referral">liam siegel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Object Detection Models</h4><p>Object detection is an involved process which helps in localization and classification of objects in a given image. In <a href="https://towardsdatascience.com/object-detection-basics-a-comprehensive-beginners-guide-part-1-f57380c89b78">part 1</a>, we developed an understanding of the basic concepts and the general framework for object detection. In this article, we will briefly cover a number of important object detection models with a focus on understanding their key contributions.</p><p>The general object detection framework highlights the fact that there are a few interim steps to perform object detection. Building on the same thought process, researchers have come up with a number of innovative architectures which solve this task of object detection. One of the ways of segregating such models is in the way they tackle the given task. Object detection models which leverage multiple models and/or steps to solve this task as called as multi-stage object detectors. The Region based CNN (RCNN) family of models are a prime example of <strong>multi-stage object detectors</strong>. Subsequently, a number of improvements led to model architectures that solve this task using a single model itself. Such models are called as <strong>single-stage object detectors</strong>. We will cover single-stage models in a subsequent article. For now, let us now have a look under the hood for some of these multi-stage object detectors.</p><h4>Region Based Convolutional Neural Networks</h4><p>Region based Convolutional Neural Networks (R-CNNs) were initially presented by Girshick et. al. in their paper titled “<a href="https://arxiv.org/abs/1311.2524">Rich feature hierarchies for accurate object detection and semantic segmentation</a>” in 2013. R-CNN is a multi-stage object detection models which became the starting point for faster and more sophisticated variants in following years. Let’s get started with this base idea before we understand the improvements achieved through <strong>Fast R-CNN</strong> and <strong>Faster R-CNN</strong> models.</p><p>The R-CNN model is made up of four main components:</p><ul><li><strong>Region Proposal</strong>: The extraction of regions of interest is the first and foremost step in this pipeline. The R-CNN model makes use of an algorithm called Selective Search for region proposal. Selective Search is a greedy search algorithm proposed by <a href="http://www.huppelen.nl/publications/selectiveSearchDraft.pdf">Uijlings et. al</a>. in 2012. Without going into too many details, selective search makes use of a bottoms-up multi-scale iterative approach to identify ROIs. In every iteration the algorithm groups similar regions until the whole image is a single region. Similarity between regions is calculated based on color, texture, brightness etc. Selective search generates a lot of false positive (background) ROIs but has a high recall. The list of ROIs is passed onto the next step for processing.</li><li><strong>Feature Extraction</strong>: The R-CNN network makes use of pre-trained CNNs such as VGGs or ResNets for extracting features from each of the ROIs identified in the previous step. Before the regions/crops are passed as inputs to the pre-trained network these are reshaped or warped to the required dimensions (each pretrained network requires inputs in specific dimensions only). The pre-trained network is used without the final classification layer. The output of this stage is a long list of tensors, one for each ROI from the previous stage.</li><li><strong>Classification Head</strong>: The original R-CNN paper made use of Support Vector Machines (SVMs) as the classifier to identify the class of object in the ROI. SVM is a traditional supervised algorithm widely used for classification purposes. The output from this step is a classification label for every ROI.</li><li><strong>Regression Head</strong>: This module takes care of the localization aspect of the object detection task. As discussed in the previous section, bounding boxes can be uniquely identified using 4 coordinates (top-left (x, y) coordinates along with width and height of the box). The regressor outputs these 4 values for every ROI.</li></ul><p>This pipeline is visually depicted in figure 1 for reference. As shown in the figure, the network requires multiple independent forward passes (one of each ROI) using the pretrained network. This is one of the primary reasons which slows down the R-CNN model, both for training as well as inference. The authors of the paper mention that it requires 80+ hours to train the network and an immense amount of disk space. The second bottleneck is the selective search algorithm itself.</p><figure><img alt="Figure 1: Components of the R-CNN model. Region proposal component is based on selective search followed by a pre-trained network such as VGG for feature extraction. Classification head makes use of SVMs and a separate regression head" src="https://cdn-images-1.medium.com/max/1024/1*_bYL-bCFWVilXe0DEViGmw.png" /><figcaption>Figure 1: Components of the R-CNN model. Region proposal component is based on selective search followed by a pre-trained network such as VGG for feature extraction. Classification head makes use of SVMs and a separate regression head. Source: Author</figcaption></figure><p>The R-CNN model is a good example of how different ideas can be leveraged as building blocks to solve a complex problem. While we will have a detailed hands-on exercise to see object detection in context of transfer learning, in its original setup itself R-CNN makes use of transfer learning.</p><p>The R-CNN model was slow, but it provided a good base for object detection models to come down the line. The computationally expensive and slow feature extraction step was mainly addressed in the <strong>Fast R-CNN</strong> implementation. The <a href="https://arxiv.org/abs/1504.08083">Fast R-CNN</a> was presented by Ross Grishick in 2015. This implementation boasts of not just faster training and inference but also improved mAP on <a href="http://host.robots.ox.ac.uk/pascal/VOC/voc2012/">PASCAL VOC 2012</a> dataset.</p><p>The key contributions from the <strong>Fast R-CNN</strong> paper can be summarized as follows:</p><ul><li><strong>Region Proposal</strong>: For the base R-CNN model, we discussed how selective search algorithm is applied on the input image to generate thousands of ROIs upon which a pretrained network works to extract features. The Fast R-CNN changes this step to derive maximum impact. Instead of applying the feature extraction step using the pretrained network thousands of times, the Fast R-CNN network does it only once. In other words, we first process the whole input image through the pretrained network just once. The output features are then used as input for the selective search algorithm for identification of ROIs. This change in order of components reduces the computation requirements and performance bottleneck to a good extent.</li><li><strong>ROI Pooling Layer</strong>: The ROIs identified in the previous step can be arbitrary size (as identified by the selective search algorithm). But the fully connected layers after the ROIs have been extracted take only fixed size feature maps as inputs. The ROI pooling layer is thus a fixed size filter (the paper mentions a size of 7x7) which helps transform these arbitrary sized ROIs into fixed size output vectors. This layer works by first dividing the ROI into equal sized sections. It then finds the largest value in each section (similar to Max-Pooling operation). The output is just the max values from each of equal sized sections. The ROI pooling layer speeds up the inference and training times considerably.</li><li><strong>Multi-task Loss</strong>: As opposed to two different components (SVM and bounding box regressor) in R-CNN implementation, Faster R-CNN makes use of a multi-headed network. This setup enables the network to be trained jointly for both the tasks using a multi-task loss function. The multi-task loss is a weighted sum of classification and regression losses for object classification and bounding box regression tasks respectively. The loss function is given as:</li></ul><blockquote>Lₘₜ = Lₒ + 𝛾Lᵣ</blockquote><p>where 𝛾 ≥ 1 if the ROI contains an object (objectness score), 0 otherwise. Classification loss is simply a negative log loss while the regression loss used in the original implementation is the smooth L1 loss.</p><p>The original paper details a number of experiments which highlight performance improvements based on various combinations of hyper-parameters and layers fine-tuned in the pre-trained network. The original implementation made use of pretrained VGG-16 as the feature extraction network. A number of faster and improved implementation such as MobileNet, ResNet, etc. have come up since the Fast R-CNN’s original implementation. These networks can also be swapped in place of VGG-16 to improve the performance further.</p><p><strong>Faster R-CNN</strong> is the final member of this family of multi-stage object detectors. This is by far the most complex and fastest variant of them all. While Fast R-CNN improved training and inference times considerably it was still getting penalized due to the selective search algorithm. The Faster R-CNN model presented in 2016 by Ren et. al. in their paper titled “<a href="https://papers.nips.cc/paper/2015/file/14bfa6bb14875e45bba028a21ed38046-Paper.pdf">Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks</a>” addresses the regional proposal aspect primarily. This network builds on top of Fast R-CNN network by introducing a novel component called <strong>Region Proposal Network (RPN)</strong>. The overall Faster R-CNN network is depicted in figure 2 for reference.</p><figure><img alt="Figure 2: Faster R-CNN is composed of two main components: 1) a Region Proposal Network (RPN) to identify ROIs and 2) a Fast R-CNN like multi-headed network with ROI pooling layer." src="https://cdn-images-1.medium.com/max/1024/1*ONcbBe4mtiEr6Mq4iMkZ8A.png" /><figcaption>Figure 2: Faster R-CNN is composed of two main components: 1) a Region Proposal Network (RPN) to identify ROIs and 2) a Fast R-CNN like multi-headed network with ROI pooling layer. Source: Author</figcaption></figure><p>RPN is a fully convolutional network (FCN) that helps in generating ROIs. As shown in figure 3.12, RPN consists of two layers only. The first being a 3x3 convolutional layer with 512 filters followed by two parallel 1x1 convolutional layers (one each for classification and regression respectively). The 3x3 convolutional filter is applied onto the feature map output of the pre-trained network (the input to which is the original image). Please note that the classification layer in RPN is a binary classification layer for determination of objectness score (not the object class). The bounding box regression is performed using 1x1 convolutional filters on anchor boxes. The proposed setup in the paper uses 9 anchor boxes per window, thus the RPN generates 18 objectness scores (2xK) and 36 location coordinates (4xK), where K=9 is the number of anchor boxes. The use of RPN (instead of selective search) improves the training and inference times by orders of magnitudes.</p><p>The Faster R-CNN network is an end-to-end object detection network. Unlike the base R-CNN and Fast R-CNN models which made use of a number of independent components for training, Faster R-CNN can be trained as a whole.</p><p>This concludes our discussion on the R-CNN family of object detectors. We discussed key contributions to better understand how these networks work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685bc89775e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-object-detection-with-r-cnn-models-a-comprehensive-beginners-guide-part-2-685bc89775e2">Exploring Object Detection with R-CNN Models — A Comprehensive Beginner’s Guide (Part 2)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection Basics — A Comprehensive Beginner’s Guide (Part 1)]]></title>
            <link>https://medium.com/data-science/object-detection-basics-a-comprehensive-beginners-guide-part-1-f57380c89b78?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/f57380c89b78</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 20:08:23 GMT</pubDate>
            <atom:updated>2024-02-06T14:33:57.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Detection Basics — A Comprehensive Beginner’s Guide (Part 1)</h3><h4>Learn the basics of this advanced computer vision task of object detection in an easy to understand multi-part beginner’s guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Vq2m6HJ1OMOW77g" /><figcaption>Photo by <a href="https://unsplash.com/@javigabbo?utm_source=medium&amp;utm_medium=referral">Javier García</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Driving a car nowadays with the latest drive assist technologies for lane detection, blind-spots, traffic signals and so on is pretty common. If we take a step back for a minute to appreciate what is happening behind the scenes, the Data Scientist in us soon realises that the system is not just <em>classifying</em> objects but also <em>locating</em> them in the scene (in real-time).</p><p>Such capabilities are prime examples of an <strong>object detection</strong> system in action. Drive assist technologies, industrial robots and security systems all make use of object detection models to detect objects of interest. <strong>Object detection</strong> is an advanced computer vision task which involves both <em>localisation</em> [of objects] as well as <em>classification</em>.</p><p>In this article, we will dive deeper into the details of the object detection task. We will learn about various concepts associated with it to help us understand novel architectures (covered in subsequent articles). We will cover key aspects and concepts required to understand object detection models from a Transfer Learning standpoint.</p><h3>Key Concepts and Building Blocks</h3><p>Object detection consists of two main sub-tasks, <em>localization</em> and <em>classification</em>. Classification of identified objects is straightforward to understand. But how do we define localization of objects? Let us cover some key concepts:</p><h4>Bounding Boxes</h4><p>For the task of object detection, we identify a given object’s location using a rectangular box. This regular box is termed as a <em>bounding box</em> and used for localization of objects. Typically, the top left corner of the input image is set as origin or (0,0). A rectangular bounding box is defined with the help of its x and y coordinates for the top-left and bottom right vertices. Let us understand this visually. Figure 1(a) depicts a sample image with its origin set at its top left corner.</p><figure><img alt="This image has 3 parts: (a) A sample image with different objects, (b) bounding boxes for each of the objects with top-left and bottom-right vertices annotated, (c ) alternate way of identifying a bounding box is to use its top-left coordinates along with width and height parameters." src="https://cdn-images-1.medium.com/max/652/1*xCxEVI1sEvE43p6Ty0Xm5Q.png" /><figcaption>Figure 1: (a) A sample image with different objects, (b) bounding boxes for each of the objects with top-left and bottom-right vertices annotated,(c.)alternate way of identifying a bounding box is to use its top-left coordinates along with width and height parameters. Source: Author</figcaption></figure><p>Figure 1(b) shows each of the identified objects with their corresponding bounding boxes. It is important to note that a bounding box is annotated with its top-left and bottom-right coordinates which are relative to the image’s origin. With 4 values, we can identify a bounding box uniquely. An alternate method to identify a bounding box is to use top-left coordinates along with its width and height values. Figure 1(c) shows this alternate way of identifying a bounding box. Different solutions may use different methods and it is mostly a matter of preference of one over the other.</p><p>Object detection models require bounding box coordinates for each object per training sample apart from class label. Similarly, an object detection model generates <em>bounding box coordinates</em> along with <em>class labels</em> per identified object during inference stage.</p><h4>Anchor Boxes</h4><p>Every object detection model scans through a large number of possible regions to identify/locate objects for any given image. During the course of training, the model learns to determine which of the scanned regions are of interest and adjust the coordinates of these regions to match the ground truth bounding boxes. Different models may generate these regions of interest differently. Yet, the most popular and widely used method is based on <em>anchor boxes</em>. For every pixel in the given image, multiple bounding boxes of different sizes and aspect ratios (ratio of width to height) are generated. These bounding boxes are termed as anchor boxes. Figure 2 illustrates different anchor boxes for particular pixel in the given image.</p><figure><img alt="Different anchor boxes for a specific pixel (highlighted in red) for the given image." src="https://cdn-images-1.medium.com/max/601/1*ESy4o-6C7tDgEuXR0td4Mw.png" /><figcaption>Figure 2: Different anchor boxes for a specific pixel (highlighted in red) for the given image. Source: Author</figcaption></figure><p>Anchor box dimensions are controlled using two parameters, <em>scale</em> denoted as s 𝜖 (0,1] and <em>aspect ratio</em> denoted as r &gt;0. As shown in figure 2, for an image of height and width h ⨉ w and specific values of s and r, multiple anchor boxes can be generated. Typically, we use the following formulae to get dimensions of the anchor boxes:</p><blockquote><strong>wₐ=w.s√r</strong></blockquote><blockquote><strong>hₐ = h.s / √r</strong></blockquote><p>Where wₐ<strong> </strong>and hₐ<strong> </strong>are the width and height of the anchor box respectively. Number and dimensions of anchor boxes are either predefined or picked up by the model during the course of training itself. To put things in perspective, a model generates a number of anchor boxes per pixel and learns to adjust/match them with ground truth bounding box as the training progresses.</p><p>Bounding boxes and anchor boxes are key concepts to understand the overall object detection task. Before we get into the specifics of how such architectures work, let us first understand the way we evaluate the performance of such models. The following are some of the important evaluation metrics used:</p><h4>Intersection over union (IOU)</h4><p>An object detection model typically generates a number of anchor boxes which are then adjusted to match the ground truth bounding box. But how do we know when the match has happened or how well the match is?</p><p><em>Jaccard Index</em> is a measure used to determine the similarity between two sets. In case of object detection, Jaccard Index is also termed as Intersection Over Union or IOU. It is given as:</p><blockquote><strong>IOU = | Bₜ ∩ Bₚ | / | Bₜ ∪ Bₚ |</strong></blockquote><p>Where Bₜ is the ground truth bounding box and Bₚ is the predicted bounding box. In simple terms it is a score between 0 and 1 determined as the ratio of area of overlap and area of union between predicted and ground truth bounding box. The higher the overlap, the better the score. A score close to 1 depicts near perfect match. Figure 3 showcases different scenarios of overlaps between predicted and ground truth bounding boxes for a sample image.</p><figure><img alt="Intersection Over Union (IOU) is a measure of match between the predicted and ground-truth bounding box. The higher the overlap, the better is the score." src="https://cdn-images-1.medium.com/max/1024/1*yGirS3kwnNBcbNlBwxMkrQ.png" /><figcaption>Figure 3: Intersection Over Union (IOU) is a measure of match between the predicted and ground-truth bounding box. The higher the overlap, the better is the score. Source: Author</figcaption></figure><p>Depending upon the problem statement and complexity of the dataset, different thresholds for IOU are set to determine which predicted bounding boxes should be considered. For instance, an object detection challenge based on <a href="https://arxiv.org/abs/1405.0312v3">MS-COCO</a> uses an IOU threshold of 0.5 to consider a predicted bounding box as true positive.</p><h4>Mean Average Precision (MAP)</h4><p>Precision and Recall are typical metrics used to understand performance of classifiers in machine learning context. The following formulae define these metrics:</p><blockquote><strong>Precision = TP / (TP + FP)</strong></blockquote><blockquote>Recall = TP/ (TP + FN)</blockquote><p>Where, <em>TP, FP and FN</em> stand for <em>True Positive, False Positive </em>and <em>False Negative</em> outcomes respectively. Precision and Recall are typically used together to generate Precision-Recall Curve to get a robust quantification of performance. This is required due to the opposing nature of precision and recall, i.e. as a model’s recall increases its precision starts decreasing. <em>PR curves </em>are used to calculate <em>F1 score</em>, <em>Area Under the Curve (AUC)</em> or <em>average precision (AP)</em> metrics. Average Precision is calculated as the average of precision at different threshold values for recall. Figure 4(a) shows a typical PR curve and figure 4(b) depicts how AP is calculated.</p><figure><img alt="a) A typical PR-curve shows model’s precision at different recall values. This is a downward sloping graph due to opposing nature of precision and recall metrics; (b) PR-Curve is used to calculate aggregated/combined scores such as F1 score, Area Under the Curve (AUC) and Average Precision (AP); © mean Average Precision (mAP) is a robust combined metric to understand model performance across all classes at different thresholds. Each colored line depicts a different PR curve based on specific I" src="https://cdn-images-1.medium.com/max/1024/1*qjG833vhS896L6H09ZbYjA.png" /><figcaption>Figure 4: a) A typical PR-curve shows model’s precision at different recall values. This is a downward sloping graph due to opposing nature of precision and recall metrics; (b) PR-Curve is used to calculate aggregated/combined scores such as F1 score, Area Under the Curve (AUC) and Average Precision (AP); (c.) mean Average Precision (mAP) is a robust combined metric to understand model performance across all classes at different thresholds. Each colored line depicts a different PR curve based on specific IOU threshold for each class. Source: Author</figcaption></figure><p>Figure 4(c) depicts how average precision metric is extended to the object detection task. As shown, we calculate PR-Curve at different thresholds of IOU (this is done for each class). We then take a mean across all average precision values (for each class) to get the final mAP metric. This combined metric is a robust quantification of a given model’s performance. By narrowing down performance to just one quantifiable metric makes it easy to compare different model’s on the same test dataset.</p><p>Another metric used to benchmark object detection models is <strong>frames per second (FPS)</strong>. This metric points to the number of input images or frames the model can analyze for objects per second. This is an important metric for real-time use-cases such as security video surveillance, face detection, etc.</p><p>Equipped with these concepts, we are now ready to understand the general framework for object detection next.</p><h3>Object Detection Framework</h3><p>Object detection is an important and active area of research. Over the years, a number of different yet effective architectures have been developed and used in real-world setting. The task of object detection requires all such architectures to tackle a list of sub-tasks. Let us develop an understanding of the general framework to tackle object detection before we get to the details of how specific models handle them. The general framework comprises of the following steps:</p><ul><li>Region Proposal Network</li><li>Localization and Class Predictions</li><li>Output Optimizations</li></ul><p>Let us now go through each of these steps in some detail.</p><h4>Regional Proposal</h4><p>As the name suggests, the first and foremost step in the object detection framework is to propose <em>regions of interest (ROI)</em>. ROIs are the regions of the input image for which the model believes there is a high likelihood of an object’s presence. The likelihood of an object’s presence or absence is defined using a score called objectness score. Regions which have objectness score greater than a certain threshold are passed onto the next stage while others are reject.</p><p>For example, take a look at figure 5 for different ROIs proposed by the model. It is important to note that a large number of ROIs are generated at this step. Based on the objectness score threshold, the model classifies ROIs as foreground or background and only passes foreground regions for further analysis.</p><figure><img alt="Regional Proposal is the first step in object detection framework. Regions of Interest are highlighted as red rectangular boxes. The model marks regions with high likelihood of an image (high objectness score) as foreground regions and rest as background regions." src="https://cdn-images-1.medium.com/max/1001/1*X9bmyXhLdomPOmHpMw92og.png" /><figcaption>Figure 5: Regional Proposal is the first step in object detection framework. Regions of Interest are highlighted as red rectangular boxes. The model marks regions with high likelihood of an image (high objectness score) as foreground regions and rest as background regions. Source: Author</figcaption></figure><p>There are a number of different ways of generating regions of interest. Earlier models used to make use of selective search and related algorithms to generate ROIs while newer and more complex models make use of deep learning models to do so. We will cover these when we discuss specific architectures in the upcoming articles.</p><h4>Localization And Class Predictions</h4><p>Object detection models are different from the classification models we typically work with. An object detection model generates two outputs for every foreground region from the previous step:</p><ul><li><strong>Object Class</strong>: This is the typical classification objective to assign a class label to every proposed foreground region. Typically, pre-trained networks are used to extract features from the proposed region and then use those features to predict the class. State-of-the-art models such as the ones trained on ImageNet or MS-COCO with a large number of classes are widely adapted/transfer learnt. It is important to note that we generate a class label for every proposed region and not just a single label for the whole image (as compared to a typical classification task)</li><li><strong>Bounding Box Coordinates</strong>: A bounding box is defined a tuple with 4 values for x, y, width and height. At this stage the model generates a tuple for every proposed foreground region as well (along with the object class).</li></ul><h4>Output Optimization</h4><p>As mentioned earlier, an object detection model proposes a large number of ROIs in step one followed by bounding box and class predictions in step two. While there is some level of filtering of ROIs in step one (foreground vs background regions based on objectness score), there are still a large number of regions used for predictions in step two. Generating predictions for such a large number of proposed regions ensures good coverage for various objects in the image. Yet, there are a number of regions with good amount of overlap for the same region. For example, look at the 6 bounding boxes predicted for the same object in figure 6(a). This potentially can lead to difficulty in getting the exact count of different objects in the input image.</p><figure><img alt="Figure 6 (a)Object detection model generating 6 bounding boxes with good overlap for the same object. (b) Output optimized using NMS" src="https://cdn-images-1.medium.com/max/1024/1*ZNLdcOsIbXrTr9F4k3cmbg.png" /><figcaption>Figure 6 (a)Object detection model generating 6 bounding boxes with good overlap for the same object. (b) Output optimized using NMS. Source: Author</figcaption></figure><p>Hence, there is a third step in this framework which concerns the optimization of the output. This optimization step ensures there is only one bounding box and class prediction per object in the input image. There are different ways of performing this optimization. By far, the most popular method is called <strong>Non-Maximum Suppression (NMS)</strong>. As the name suggests, NMS analyzes all bounding boxes for each object to find the one with maximum probability and suppress the rest of them (see figure 6(b) for optimized output after applying NMS).</p><p>This concludes a high-level understanding of a general object detection framework. We discussed about the three major steps involved in localization and classification of objects in a given image. In this next article we will use this understanding to understand specific implementations and their key contributions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f57380c89b78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/object-detection-basics-a-comprehensive-beginners-guide-part-1-f57380c89b78">Object Detection Basics — A Comprehensive Beginner’s Guide (Part 1)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Training of your Deep Learning Models]]></title>
            <link>https://medium.com/data-science/supercharge-training-of-your-deep-learning-models-7168ff81a042?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/7168ff81a042</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 18:04:05 GMT</pubDate>
            <atom:updated>2023-11-22T18:04:05.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharge Training of Your Deep Learning Models</h3><h4>Super convergence with one-cycle learning rates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*moNSSlFZAas_Ju2I" /><figcaption>Photo by <a href="https://unsplash.com/@pjswinburn?utm_source=medium&amp;utm_medium=referral">Philip Swinburn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you come across scenarios when it is easy to get an initial burst in accuracy but once you reach 90%, you have to push really really hard to squeeze out any improvement in performance? Does your model take too long to train?</p><p>In this article, we will look at an interesting technique to supercharge your training setup and get that extra bit of performance you have been looking for and train faster. Essentially, we will work towards dynamically changing the learning rate over epochs using a policy called the <strong><em>One-Cycle Learning Rate</em></strong>.</p><p>Originally mentioned in a paper by Leslie Smith, the <strong>one-cycle learning rate schedule</strong>[<a href="https://arxiv.org/abs/1803.09820">1</a>], [<a href="https://arxiv.org/abs/1708.07120">2</a>] focuses on a unique strategy to dynamically update the learning rate during the training process. Sounds like a mouthful of terms, don’t worry, let’s first start with a typical training setup and then we will gradually understand how we can improve results using one-cycle learning rate.</p><h3>Training a Image Classifier</h3><p>As we are working towards learning a neat trick (cycle-rate) to improve model performance, why not do it while enjoying the classic <strong><em>rock-paper-scissors</em></strong> game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JnfZh_BBsXL1OyK6" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Problem Statement</h4><p><em>The game of rock-paper-scissors is a classic child’s game involving two players using hand gestures (for rock, paper or scissors) competing to over-power their opponent. For instance, the rock gesture wins over scissors but the paper gesture wins over the rock. Interesting, isn’t it?</em></p><p>Our objective here, is to train an image classification model which can detect one of the three gestures. We can then leverage such a trained model to develop an end-to-end game. For the purpose of this article, we will limit the scope towards training a classifier itself, the end-to-end game complete with a deployable model is for another article probably.</p><h4>The Dataset</h4><p>We are lucky that we already have a labelled dataset which we can leverage to train a classification model to great effect. The dataset is hosted on <a href="https://www.tensorflow.org/datasets/catalog/rock_paper_scissors">TensorFlow dataset</a> catalog made available by <a href="https://laurencemoroney.com/datasets.html#rock-paper-scissors-dataset">Laurence Moroney</a> (CC BY 2.0). It has the following attributes:</p><ul><li>Number of data points: 2800</li><li>Number of classes : 3</li><li>Available train-test split: Yes</li><li>Dataset size: 220 MiB</li></ul><p>TensorFlow provides a nice and clean API to access such datasets, the following snippet allows us to download the train and validation splits</p><pre>import tensorflow_datasets as tfds<br><br>DATASET_NAME = &#39;rock_paper_scissors&#39;<br>(dataset_train_raw, dataset_test_raw), dataset_info = tfds.load(<br>    name=DATASET_NAME,<br>    data_dir=&#39;tmp&#39;,<br>    with_info=True,<br>    as_supervised=True,<br>    split=[tfds.Split.TRAIN, tfds.Split.TEST],<br>)<br><br># plot samples from the dataset<br>fig = tfds.show_examples(dataset_train_raw, dataset_info)</pre><p>The following are a few sample images from this dataset itself:</p><figure><img alt="Figure: Sample data points in the Rock Paper Scissors Dataset" src="https://cdn-images-1.medium.com/max/514/1*f7_JT1fKkM8Z86-8ZP14Og.png" /><figcaption>Figure:Sample data points in the Rock Paper Scissors Dataset</figcaption></figure><h4>Learning Rate</h4><p>Learning Rate is one of the key hyper-parameters which can make or break a setup yet it is one which is typically overlooked. The reason it is overlooked is because most libraries/packages come with good enough defaults to begin with. But these defaults can take you only so far.</p><p>Getting the correct learning rate for a bespoke use case such as ours is very important. It is a tricky trade-off to find the optimal value. Go too slow (or small) with the learning rate and your model will hardly learn anything. Go too fast (or large) and it will overshoot the ever so mysterious minima all neural networks aim to find. The same is depicted in the below illustration for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMEMosPj69r2nEsGIjgUjA.png" /><figcaption>Figure:Impact of Learning Rate towards Model’s ability to learn the objective (minima). Souce: Author</figcaption></figure><p><strong>Gradient Descent &amp; Optimizers</strong></p><p>Gradient descent is the standard way to train/optimise neural networks. It works by minimizing the objective function by updating the parameters of the network in the opposite direction of the gradient. Without going into much details, it helps in travelling downhill along the slope of the objective function. A detailed introduction to gradient descent is available <a href="https://cs231n.github.io/optimization-1/">here</a> for reference.</p><p>The deep learning community has come a long way since the initial models were trained with vanilla gradient descent. Over the years a number of improvements have helped train faster and avoid obvious pitfalls. Briefly, some of the notable and most popular ones are:</p><p><strong>AdaGrad<br></strong><a href="https://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf">Adaptive Gradient algorithm</a> is an optimization algorithm which adapts the learning rates of individual parameters based on their historical gradients, allowing for larger updates for infrequent parameters and smaller updates for frequent ones. It is designed to handle sparse data efficiently. It is well-suited when dealing with sparse data.</p><p><strong>RMSProp<br></strong><a href="https://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf">Root Mean Square Propagation</a> optimises the learning by adjusting the learning rates for each parameter individually. It addresses the diminishing learning rates problem in AdaGrad by using a moving average of squared gradients. This helps adaptively scale the learning rates based on recent gradient magnitudes.</p><p><strong>ADAM<br></strong><a href="https://arxiv.org/pdf/1412.6980.pdf">Adaptive Moment Estimation</a> is an optimization algorithm that combines ideas from both RMSProp and momentum methods. It maintains exponentially decaying averages of past gradients and squared gradients, using them to adaptively update parameters. ADAM is known for its efficiency and effectiveness in training deep neural networks.</p><h3>One-Cycle Learning Rate and Super Convergence</h3><p>One-Cycle Learning Rate is a simple two-step process to improvise upon the learning rate and the momentum as the training progresses. It works as follows:</p><ul><li><strong>Step 1</strong>: We start by ramping up the learning rate initially from a lower to a higher value in a linear incremental fashion for a few epochs</li><li><strong>Step 2</strong>: We maintain the highest value of learning rate for a few epochs</li><li><strong>Step 3</strong>: We then go back to a lower learning rate decaying over time</li></ul><p>During these three steps, the momentum is updated in the exact opposite direction, i.e. when the learning rate goes up, the momentum goes down and vice-versa.</p><p><strong>One-Cycle Learning Rate in Action</strong></p><p>Let us first work our way through a simple implementation for one-cycle learning rate and then use it for training our model. We will leverage a ready-to-use implementation for the one-cycle LR schedule from <a href="https://docs.google.com/presentation/d/e/2PACX-1vRqvlSpX5CVRC2oQ_e_nRNahOSPoDVL6I36kdjuPR_4y_tCPb-_k98Du1QXBwx4sBvVrzsCPulmuPn8/pub?slide=id.g50ba8fd3eb_0_0">Martin Gorner’s 2019 talk at <em>TensorFlow World</em></a> as depicted in listing 2.</p><pre>def lr_function(epoch):<br>    # set start, min and max value for learning rate<br>    start_lr = 1e-3; min_lr = 1e-3; max_lr = 2e-3<br><br>    # define the number of epochs to increase <br>    # LR lineary and then the decay factor<br>    rampup_epochs = 6; sustain_epochs = 0; exp_decay = .5<br><br>    # method to update the LR value based on the current epoch<br>    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs,<br>           sustain_epochs, exp_decay):<br>        if epoch &lt; rampup_epochs:<br>            lr = ((max_lr - start_lr) / rampup_epochs<br>                        * epoch + start_lr)<br>        elif epoch &lt; rampup_epochs + sustain_epochs:<br>            lr = max_lr<br>        else:<br>            lr = ((max_lr - min_lr) *<br>                      exp_decay**(epoch - rampup_epochs -<br>                                    sustain_epochs) + min_lr)<br>        return lr<br><br>    return lr(epoch, start_lr, min_lr, max_lr,<br>              rampup_epochs, sustain_epochs, exp_decay)</pre><p>We execute this function(<em>see</em> <em>listing 2)</em> for a fixed number of epochs to showcase how the learning rate changes as per the two steps we discussed earlier. Here we start with an initial learning rate of <strong>1e-3</strong> and ramp it up to <strong>2e-3</strong> in the first few epochs. It is then reduced again back to <strong>1e-3</strong> over the course of the remaining epochs. This dynamic learning rate curve is depicted with a sample run of 24 epochs in following figure.</p><figure><img alt="One-cycle learning rate policy over 50 epochs. Learning rate is ramped up initially, followed by a slow decay over epochs. Image Source: by author" src="https://cdn-images-1.medium.com/max/574/1*auM7dPmwjzkc7cfS4OVbnw.png" /><figcaption>One-cycle learning rate policy over 24 epochs. Learning rate is ramped up linearly , followed by a slow decay over remaining epochs. Image Source: Author</figcaption></figure><p>We will now put our one-cycle learning rate scheduler to the test by applying it when using a MobileNetV2 model as a feature extractor while training a classification head for our current case of rock-paper-scissors. We will then be comparing it against a simple CNN as well as MobileNetV2+classification head with standard Adam optimiser. The complete notebook is available for reference on <a href="https://github.com/raghavbali/python_notebooks/blob/master/supercharge_series/supercharge_learning_lr.ipynb">github</a>. For a quick overview, the following snippet outlines how we use TensorFlow callbacks to plug-in our 1-cycle-rate utility.</p><pre># Set Image Shape <br>INPUT_IMG_SHAPE= (128, 128, 3)<br><br># Get Pretrained MobileNetV2<br>base_model = tf.keras.applications.MobileNetV2(<br>  input_shape=INPUT_IMG_SHAPE,<br>  include_top=False,<br>  weights=&#39;imagenet&#39;,<br>  pooling=&#39;avg&#39;<br>)<br><br># Attach a classification head<br>model_lr = tf.keras.models.Sequential()<br>model_lr.add(base_model)<br>model_lr.add(tf.keras.layers.Dropout(0.5))<br>model_lr.add(tf.keras.layers.Dense(<br>    units=NUM_CLASSES,<br>    activation=tf.keras.activations.softmax,<br>    kernel_regularizer=tf.keras.regularizers.l2(l=0.01)<br>))<br><br># compile the model<br>model_lr.compile(<br>    optimizer=tf.keras.optimizers.Adam(),<br>    loss=tf.keras.losses.sparse_categorical_crossentropy,<br>    metrics=[&#39;accuracy&#39;]<br>)<br><br># set number of epochs<br>initial_epochs = 24<br><br># Set the model for training<br># The LearningRateScheduler callback is where we<br># plug our custom 1-cycle rate function<br>training_history_lr = model_lr.fit(<br>    x=dataset_train_augmented_shuffled.repeat(),<br>    validation_data=dataset_test_shuffled.repeat(),<br>    epochs=initial_epochs,<br>    steps_per_epoch=steps_per_epoch,<br>    validation_steps=validation_steps,<br>    callbacks=[<br>        tf.keras.callbacks.LearningRateScheduler(lambda epoch: \<br>                                             lr_function(epoch),<br>                                             verbose=True)<br>    ],<br>    verbose=1<br>)</pre><p>We train all 3 models for 24 epochs with a batch size of 64. The following figure showcases the impact of 1 cycle learning rate. It is able to assist our model to achieve convergence in just 5 epochs as compared to the other two models. The super-convergence phenomenon is visible for validation dataset as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exhYR-Ld1T4Q4qs2NGupxQ.png" /><figcaption>MobileNetV2 with 1 cycle learning rate (mobileNetV2_lr) outperforms MobileNetV2 and simple CNN architectures by achieving converge is just 5 epochs</figcaption></figure><p>We reach consistent values of validation accuracies ranging between 90–92% within 10 epochs which is so far the best we have seen across all our models. On evaluation the model performance on the test dataset also depicts the same story, i.e. MobileNetV2_lr outperforms the other two very easily.</p><pre># Simple CNN<br>Test loss:  0.7511898279190063<br>Test accuracy:  0.7768816947937012<br><br># MobileNetV2<br>Test loss:  0.24527719616889954<br>Test accuracy:  0.9220430254936218<br><br># MobileNetV2_LR<br>Test loss:  0.27864792943000793<br>Test accuracy:  0.9166666865348816</pre><h3>Conclusion</h3><p>Overcoming the plateau in model performance beyond 90% accuracy and optimizing training time can be achieved through the implementation of the One-Cycle Learning Rate. This technique, introduced by Leslie Smith and team, dynamically adjusts the learning rate during training, offering a strategic approach to supercharging the model performance. By adopting this method, you can efficiently navigate the complexities of training setups and unlock the potential for faster and more effective deep learning models. Embrace the power of One-Cycle Learning Rate to elevate your training experience and achieve superior results!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7168ff81a042" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/supercharge-training-of-your-deep-learning-models-7168ff81a042">Supercharge Training of your Deep Learning Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Take On: How Not to Be Wrong]]></title>
            <link>https://medium.com/@Rghv_Bali/my-take-on-how-not-to-be-wrong-5c1a91d79abc?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1a91d79abc</guid>
            <category><![CDATA[jordan-ellenberg]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 10:41:38 GMT</pubDate>
            <atom:updated>2023-04-29T10:49:53.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEtWfOHrehv-7nI5QOZC0g.jpeg" /><figcaption>How Not to Be Wrong Book Cover with Coffee</figcaption></figure><p>How Not to be Wrong explores the power of mathematical thinking in everyday life. Jordan Ellenberg nicely presents how we knowingly and unknowingly use mathematics to think more clearly and make better decisions in daily aspects of our lives. He provides examples of how mathematical concepts like probability, statistics, and geometry are used in fields such as politics, medicine, finance, law and more.</p><blockquote><strong>TL;DR</strong> mathematics is not just about weird symbols, difficult integrals and long boring proofs.</blockquote><p>Ellenberg delves into topics such as the geometry of error, the paradoxes of voting, and the importance of randomness in the world. He also shows how mathematical thinking can be applied to questions of social justice, such as how to fairly allocate resources or measure the impact of affirmative action policies. These chapters are refreshing, fascinating, and showcase how mathematics can be applied in unexpected ways. Without repeating book’s each chapter heading by heading, here are a few key things that make you wonder how impactful mathematical concepts are:</p><h4>Survivor Bias</h4><p>The tendency to focus only on the successes or survivors of a particular group and ignore the failures or non-survivors is how the book introduces Survivor Bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wio06eOmZ0pVCutR" /><figcaption>Photo by <a href="https://unsplash.com/@museumsvictoria?utm_source=medium&amp;utm_medium=referral">Museums Victoria</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The book uses several examples, such as the story of Abraham Wald and the problem of aircraft damage during World War II, to illustrate how Survivor Bias can lead to incorrect conclusions and flawed decision-making. He demonstrates how understanding this bias can help us make better decisions and avoid falling into the same trap.</p><h4>Laffer’s Curve</h4><p>The first chapter “Less Like Sweden” puts the whole idea in a very easy to understand real life setting.</p><blockquote>“Nonlinear thinking means which way you should go depends on where you already are.”</blockquote><p>Ellenberg just loves the Laffer Curve and rightly so. The curve is named after economist Arthur Laffer, who proposed that there is a point at which increasing tax rates will actually decrease government revenue, as people become discouraged from working or investing.</p><h4>Quirky Headings and Superb Footnotes</h4><p>This book is not just an informative book, but also a fascinating one, thanks to the footnotes. Ellenberg’s footnotes are not just dry academic references; they are often humorous, entertaining, and illuminating in their own right. They provide readers with fascinating tidbits of information about everything from the history of mathematics to the personal lives of famous mathematicians.</p><blockquote>“If you never miss a plane, you’re spending too much time at the airports.”</blockquote><p>They show us how even seemingly obscure details can reveal surprising connections and insights, and they encourage us to look beyond the surface to discover the hidden stories and connections that underlie the world around us.</p><h4>More than a book on just Mathematics</h4><p>Overall, “How Not to be Wrong” is an insightful and entertaining book that shows how mathematics can be a powerful tool for understanding the world and making better decisions.</p><p>It is not a self-help book but certainly not a quick read either. Take your time, let it sync in and enjoy the power of mathematics.</p><blockquote>“Safety warning: never divide by zero unless a licensed mathematician is present.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1a91d79abc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Take on: Shantaram]]></title>
            <link>https://medium.com/@Rghv_Bali/my-take-on-shantaram-ae02d7a6b1a3?source=rss-dff4008c1908------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae02d7a6b1a3</guid>
            <category><![CDATA[review]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[books-and-authors]]></category>
            <dc:creator><![CDATA[Raghav Bali]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 21:45:08 GMT</pubDate>
            <atom:updated>2023-02-20T09:17:32.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*WcX29rT4Vts7bhh75u_Hfw.jpeg" /></figure><p>I might have read a number of books so far, yet it never occured to me to document my thoughts, my feelings, my review….. until Shantaram. Why now? why this book? Well,</p><p>Shantaram is a special book. Special not just because of the story it shares and the life mantra that it preaches, but because this book happened to be in my hands during one of my life’s most precarious yet defining moments. This book was a parting gift to me by my dear grandfather (<em>nana ji</em>) on 28th January 2022. He is quite a reader and someone who loves journaling his life. Yes, he maintains both habits even longer than I have been alive!!! This book had been on my bucket list for quite sometime but its sheer size combined with my laziness and busy schedule kept me from picking it up. Anyhow, finally it <em>landed</em> in my lap and I started reading it as I <em>took off</em> on my maiden flight to Berlin.</p><p>Shantaram is this larger than life story inspired by the life of Gregory David Roberts. Roberts is the author of this very nicely edited book which justifies its size (yes, it is 900+ pages!!!). The book traces his life as he lands in Mumbai on a fake passport. The book details the chaotic yet highly organised essence of the megapolis we call Mumbai. It is amazing to learn how a foreigner (or <em>gora</em> in hindi and referred similarly in the book), befriends a local guide who initiates his new life in this new city. He ends up not just learning Hindi and Marathi but excels through a stint as a villager, as well as a slum dweller and as a makeshift doctor. He ends up making friends from different walks of life, trades and experiences. He becomes a sort of right-hand man of a gangster and even embarks on a mission through Pakistan into Afghanistan to fight the soviets. He survives a number of near-death experiences and even features in a bollywood movie. His journey is full of <a href="https://twitter.com/search?pf=on&amp;q=shantaram%20(from%3Arghv_bali)&amp;src=typed_query">quotable dialogs</a> and deep life lessons on pain, friendship and love. It is a journey of someone who observes the small things in life.</p><blockquote>“Fate always gives you two choices, the one you should take, and the one you do” -Scorpio George</blockquote><p>There are a number of fantastic characters who play critical role in this book. They have been way too carefully detailed for me to write a summary. I would rather just mention the ones who intrigued me to know them a bit more. <em>Prabhakar</em>, the guide, for he initiated Roberts on this magnamious journey. Abdel Khader Khan, the mafia don, for he being this mysterious yet open character who grips not just Roberts but also the readers till the end. <em>Didier</em>, the slapstick tongue in the cheek character whose quotes I just loved. And finally <em>Karla</em>, for all that mystery and green eyes!</p><figure><img alt="shantaram @ ehberge Berlin" src="https://cdn-images-1.medium.com/max/1024/1*phlQYKOjszaY1nST2i0kIQ.jpeg" /></figure><p><strong><em>Disclaimer</em></strong>: I am not a critique nor an avid reader. I am someone who gets engrossed in the books I read yet I tend to forget the finer details as the time goes on. The essence, the gist, the characters remain with me forever. I hope this marks first of many such <em>my takes </em>to help me document the books I read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae02d7a6b1a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>