<?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 Devesh Surve on Medium]]></title>
        <description><![CDATA[Stories by Devesh Surve on Medium]]></description>
        <link>https://medium.com/@deveshsurve?source=rss-eceecdcfa17e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bHiA94B-pPL_gZLX847Ucg.jpeg</url>
            <title>Stories by Devesh Surve on Medium</title>
            <link>https://medium.com/@deveshsurve?source=rss-eceecdcfa17e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:19:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deveshsurve/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[Redesigning Apple’s Shopping Cart: Can the Best Get Even Better?]]></title>
            <link>https://deveshsurve.medium.com/redesigning-apples-shopping-cart-can-the-best-get-even-better-7bf0d535da55?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf0d535da55</guid>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 17:26:31 GMT</pubDate>
            <atom:updated>2024-09-24T18:44:05.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJoxxthBYb6lm9yW0_hfaA.jpeg" /></figure><h3>Introduction:</h3><p>I recently embarked on a journey to purchase the iPhone 16, and, as always, Apple’s seamless shopping experience lived up to its reputation. With Apple known for its impeccable user experience (UX), I didn’t even realize how many subtle touches made the process feel flawless.</p><p>However, during a course I took recently on UX best practices, I began to notice some of these small details and appreciated them more than ever.</p><p>It led me to wonder: <em>Could Apple’s UX, already one of the best in the industry, be improved even further?</em></p><p>That’s when I started exploring the possible enhancements to an already stellar shopping cart experience. So, join me on this ride as I explore ways to make a great thing even better.</p><h3>Understanding Shopping Cart Challenges:</h3><p>While Apple offers an incredible experience, the general challenges faced by e-commerce websites globally include issues like cart abandonment, hidden costs, and lengthy checkout processes. These common pitfalls detract from an otherwise seamless shopping journey. Understanding these obstacles allows us to see how subtle adjustments to Apple’s cart experience could set a new benchmark for excellence.</p><h3>Issues with E-Commerce Websites:</h3><p>Before diving into redesign strategies, it’s important to recognize some of the most frequent pain points that users encounter when shopping online:</p><ul><li><strong>Hidden costs</strong> (taxes, shipping) only revealed at checkout.</li><li><strong>Complicated checkout processes</strong> that require account creation.</li><li><strong>Poor mobile optimization</strong> leading to friction on smaller screens.</li><li><strong>Abandoned carts</strong> due to a lack of persistent cart options or saved preferences.</li></ul><h3>Strategy Development: Thought Process Behind the Improvements</h3><p>To enhance Apple’s already stellar shopping cart, I focused on reducing friction, adding personalization, and maintaining simplicity.</p><h4>1. Reducing Friction</h4><p>The idea of <strong>Transparent Pricing</strong> emerged to prevent checkout surprises by displaying taxes and shipping costs upfront, reducing cart abandonment and building trust.</p><h4>2. Enhancing Personalization</h4><p><strong>Enhanced Gift Options</strong> and <strong>Promo Code Suggestions</strong> were added to personalize the experience and keep users within the Apple ecosystem, creating a more thoughtful and convenient process.</p><h4>3. Encouraging Larger Purchases</h4><p>To boost sales without cluttering the design, I proposed <strong>Bundle Discounts</strong>, which subtly encourage larger purchases through dynamic recommendations that align with Apple’s minimalist aesthetic.</p><h3>Features to Enhance the Experience:</h3><ul><li><strong>Bundle Discounts:</strong> Provide dynamic discounts for users who purchase related items together, encouraging larger purchases.</li><li><strong>Enhanced Gift Options:</strong> Allow users to visualize gift wrapping and messaging options, making the cart more interactive and personal.</li><li><strong>Promo Code Suggestions:</strong> Automatically suggest available promo codes, eliminating the need for users to search for discounts externally.</li><li><strong>Easy Return Information:</strong> Display clear return policies and options directly within the cart, offering peace of mind to customers and reducing hesitancy.</li><li><strong>Item Availability Notification:</strong> Provide real-time alerts for items that have limited stock or longer shipping times, ensuring transparency throughout the process.</li></ul><h3>Redesign Suggestions for Creativity and Practicality:</h3><p>1. <strong>Zoom In and Out Feature:</strong> Add a zoom-in and zoom-out option for product images, allowing users to closely examine product details directly within the shopping cart without navigating away from the page.</p><blockquote>Before : User can’t zoom in to get a better view of the product</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7cXFBpcrOgPnYib7YZ6aw.png" /></figure><blockquote>After : Zoom in Button provided at the bottom Right</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug3LkQkUThUD9prJ-A7HzQ.png" /></figure><p>2. <strong>Bundle Discounts:</strong> Provide dynamic discounts for users who purchase related items together, encouraging larger purchases.</p><blockquote><strong>Before:</strong> Users only see related products without any incentive to purchase them together.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEnkCR9Zz-NAITbRxj24QA.png" /></figure><blockquote><strong>After:</strong> A dynamic “Bundle &amp; Save” section offers discounts for purchasing related items, encouraging larger orders.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cW-F_x0ty0_DLDK-V7RvQA.png" /></figure><p>3. <strong>Visual Product Previews:</strong> Enhance product pages with high-quality 360-degree views and interactive product demos using AR ( Augmented Reality ) and VR ( Virtual Reality ). This lets users explore details directly on the page without needing to leave the cart.</p><blockquote>Before : No option to get a better viewing experience</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnNivZXU_i7Cl9_YsYFR_g.png" /></figure><blockquote>After : Button on the right to view product in 360 Degrees and AR/VR</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQT6i4y8p8DHhsbOlJbNjQ.png" /></figure><p>4. <strong>Transparent Pricing:</strong> Customers should know the total cost (including taxes and shipping) as soon as they start adding items to the cart. This eliminates the element of surprise during checkout, making customers more likely to complete their purchase.</p><blockquote>Before : Price not mentioned for the product</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XezrdNN21UAAwugHXLDAdw.png" /></figure><blockquote>After: Here we add the price to remove any suprises user may face later</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZTEkmcp-vhUht1aNyZZJg.png" /></figure><p>5. <strong>Enhanced Gift Options:</strong> Allow users to visualize gift wrapping and messaging options, making the cart more interactive and personal.</p><blockquote><strong>Before:</strong> No option to customize gift wrapping or messaging.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gF6f_XUWa6rMQsK_VBkp7A.png" /></figure><blockquote><strong>After:</strong> Users can personalize their purchase with gift wrap and a custom message, with a preview option in the cart.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iC7lSzdd2RLxZA4Zf4G-zQ.png" /></figure><p>6. <strong>Easy Return Information:</strong> Display clear return policies and options directly within the cart, offering peace of mind to customers and reducing hesitancy.</p><blockquote><strong>Before:</strong> Return policies are unclear and buried in the terms section.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dxb9-IfwuxJHvMyYIZNKEA.png" /></figure><blockquote><strong>After:</strong> A clear “Returns Policy” button are visible directly in the cart, reassuring users during checkout.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKEVl0-VsUHk0xCaio5INA.png" /></figure><h3>Conclusion:</h3><p>The goal of any redesign is to make the user’s journey as intuitive and seamless as possible. Apple already delivers an outstanding shopping experience, but as with any digital product, there’s always room for improvement. These enhancements could reduce cart abandonment rates, improve mobile usability, and ultimately create a more delightful shopping experience. In the end, even the best can get better with thoughtful iteration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf0d535da55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VideoPoet: A New Breakthrough in AI Video Generation ?]]></title>
            <link>https://deveshsurve.medium.com/videopoet-a-new-breakthrough-in-ai-video-generation-4c5ea8270efb?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c5ea8270efb</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 20:31:22 GMT</pubDate>
            <atom:updated>2024-08-07T20:31:22.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>VideoPoet: A New Breakthrough in AI Video Generation ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqpDhlH1QphqmwJvcJiZrg.png" /></figure><h3>Introduction:</h3><p>Recently I read that one of the ICML’24 Best Paper Award ( <a href="https://icml.cc/virtual/2024/awards_detail">https://icml.cc/virtual/2024/awards_detail</a> ) was given to <strong>VideoPoet</strong>: A large language model for zero-shot video generation. Intrigued since getting the best paper award in any of the top tier conferences is very very difficult. The paper was quite interesting, since Google Research has introduced VideoPoet, an AI model that can generate, edit, and manipulate videos in ways that were once thought to be the exclusive domain of human creativity. But what makes VideoPoet special, and how does it work? So in this blog post, we’ll dive deep into the technology behind VideoPoet, explaining it in terms that (hopefully) won’t require an advanced degree in computer science to understand.</p><h3>The Evolution of AI-Generated Content:</h3><p>To appreciate the significance of VideoPoet, it’s helpful to understand the journey of AI-generated content:</p><ol><li><strong>Text Generation</strong>: AI started with generating text. Models like GPT (Generative Pre-trained Transformer) can produce human-like text based on prompts.</li><li><strong>Image Generation</strong>: The next frontier was creating images from text descriptions. Models like DALL-E and Midjourney made this possible.</li><li><strong>Video Generation</strong>: This is where we are now. Generating coherent, high-quality videos from text or other inputs is the latest challenge AI is tackling.</li></ol><h3>So What is VideoPoet?</h3><p>VideoPoet is an AI model developed by Google Research that can perform a variety of video-related tasks:</p><ul><li>Generate videos from text descriptions</li><li>Create videos from still images</li><li>Edit existing videos</li><li>Change the style of videos (e.g., make them look like cartoons)</li><li>Generate matching audio for videos</li></ul><p>What makes VideoPoet unique is its approach. Instead of using the currently popular method for video generation (which we’ll discuss next), it adapts techniques from language models to work with video.</p><h3>The Current Approach: Diffusion Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FNHaK44cBu4MlCpA" /></figure><p>Before we dive into how VideoPoet works, let’s understand the current popular method for AI video generation: diffusion models.</p><p>Diffusion models work on a principle inspired by thermodynamics. Here’s a simplified explanation:</p><ol><li><strong>Start with Noise</strong>: Begin with a completely random, noisy image or video.</li><li><strong>Gradual Denoising</strong>: The AI learns to gradually remove noise, step by step, until a clear image or video emerges.</li><li><strong>Guided Process</strong>: The text description or other input guides this denoising process, influencing what appears in the final output.</li></ol><p>Think of it like slowly developing a photograph, where the image becomes clearer over time.</p><p>While diffusion models have produced impressive results, they have some limitations:</p><ul><li>They can be slow, especially for longer videos.</li><li>It can be challenging to maintain consistency across frames.</li><li>Adding new capabilities often requires significant changes to the model.</li></ul><h3>VideoPoet’s Approach: Language Model for Video</h3><p>VideoPoet takes a different approach, inspired by large language models like GPT. But how can a language model, designed for text, work with videos? This is where the innovation begins.</p><h4>Key Concept: Tokenization</h4><p>The fundamental idea behind VideoPoet is to represent everything — text, images, video frames, and audio — as sequences of “tokens.”</p><p>What are tokens?</p><ul><li>In language models, tokens are usually parts of words or individual characters.</li><li>For VideoPoet, tokens represent small pieces of visual or audio information.</li></ul><p>This unified representation allows the AI to process all these different types of data in the same way it processes text.</p><h3>The Architecture of VideoPoet:</h3><p>Now, please bare with me and this complex diagram :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WczYKdhGScYS9mFh.png" /></figure><h4>Tokenizers:</h4><ul><li>Image and Video Tokenizer: Converts visual data into tokens.</li><li>Audio Tokenizer: Converts audio into tokens.</li><li>Text Embeddings: Converts text into a format the model can understand.</li></ul><h4>Language Model Backbone:</h4><ul><li>A large neural network similar to those used for text generation.</li><li>Trained to predict the next token in a sequence, whether it’s a word, part of an image, or a snippet of audio.</li></ul><h4>Super-Resolution Module:</h4><ul><li>Increases the resolution and quality of the generated videos.</li></ul><h3>How VideoPoet Works:</h3><h4>Input Processing:</h4><ul><li>Text is converted into embeddings.</li><li>Images, videos, or audio (if present) are converted into tokens.</li></ul><h4>Token Generation:</h4><ul><li>The language model predicts tokens one by one, building up the video frame by frame.</li><li>This process is guided by the input (text description, image, etc.).</li></ul><h4>Super-Resolution:</h4><ul><li>The generated low-resolution video is then enhanced to create the final high-quality output.</li></ul><h3>Training Process:</h3><p>VideoPoet’s training happens in two main stages:</p><ol><li><strong>Pretraining:</strong></li></ol><ul><li>The model is exposed to a massive amount of data: videos, images, text, and audio.</li><li>It learns general patterns and relationships between these different types of data.</li><li>This is like giving the AI a broad education about the visual and auditory world.</li></ul><p>2.<strong> Task Adaptation:</strong></p><ul><li>The pretrained model is then fine-tuned for specific tasks.</li><li>This improves its performance on particular types of video generation or editing.</li></ul><p>3. <strong>Multi-Task Training:</strong></p><p>A key innovation in VideoPoet is its multi-task training approach. Instead of creating separate models for different tasks, VideoPoet is trained on many tasks simultaneously:</p><ul><li>Text-to-Video: Generating videos from text descriptions.</li><li>Image-to-Video: Animating still images.</li><li>Video Editing: Filling in missing parts of videos or extending them.</li><li>Video Stylization: Changing the visual style of videos.</li><li>Audio Generation: Creating matching audio for videos.</li></ul><p>This multi-task approach has several benefits:</p><ol><li><strong>Flexibility</strong>: The model can handle many different tasks without major changes.</li><li><strong>Generalization</strong>: It learns more general skills that can be applied to new, unseen tasks.</li><li><strong>Efficiency</strong>: A single model can do the work of many specialized models.</li></ol><h4>Key Innovations and Capabilities:</h4><ol><li>Zero-Shot Performance: “Zero-shot” refers to the ability to perform tasks the AI wasn’t explicitly trained on. VideoPoet shows impressive zero-shot capabilities, able to handle new types of prompts or combine its skills in novel ways.</li><li>Long-form Generation: VideoPoet can create coherent videos up to 10 seconds long. This is challenging because the AI needs to maintain consistency and logical progression over many frames.</li><li>3D Understanding: Interestingly, even though VideoPoet wasn’t specifically trained on 3D data, it shows an understanding of three-dimensional space. It can generate videos that appear to rotate around objects or show different angles of a scene.</li><li>Camera Movements: The model can simulate various camera movements (like panning or zooming) based on text descriptions. This adds a layer of cinematographic control to the generation process.</li><li>Style Transfer: VideoPoet can apply various artistic styles to videos, such as making them look like watercolor paintings or cartoons.</li><li>Task Chaining: One of the most impressive capabilities is VideoPoet’s ability to chain different tasks together. For example, it can animate a still image, then apply a style transfer, and finally add appropriate audio — all in one seamless process.</li></ol><h3>So How Well Does It Perform?</h3><p>The researchers evaluated VideoPoet in two main ways:</p><ol><li><strong>Objective Metrics</strong>: They used standard benchmarks in the field of video generation, comparing VideoPoet to other state-of-the-art models. VideoPoet performed exceptionally well, often outperforming other models in measures of video quality and how well the videos matched the text descriptions.</li><li><strong>Human Evaluation</strong>: Perhaps more importantly, they had human raters compare videos generated by VideoPoet with those from other top models. People consistently preferred VideoPoet’s outputs, especially in terms of:</li></ol><ul><li>Text Fidelity: How well the video matched the text description.</li><li>Video Quality: The overall visual quality of the video.</li><li>Motion Interestingness: How engaging and dynamic the movements in the video were.</li><li>Motion Realism: How natural and believable the motions appeared.</li></ul><p>VideoPoet particularly excelled in generating videos with complex and interesting motions, an area where many other models struggle.</p><h3>Challenges and Limitations:</h3><p>While VideoPoet represents a significant advancement, it’s not without its challenges:</p><ol><li>Temporal Consistency: In longer videos, there can sometimes be slight inconsistencies between frames. Objects might subtly change appearance or position in ways that don’t make sense.</li><li>Text Rendering: The model struggles with generating readable text within videos. This is a common challenge in AI video generation.</li><li>Computational Requirements: As a large and complex AI model, VideoPoet requires significant computational power to run. This could limit its immediate accessibility for everyday users.</li><li>Ethical Considerations: As with any powerful AI tool, there are concerns about potential misuse, such as creating misleading or fake videos. The researchers acknowledge the importance of developing and using this technology responsibly.</li></ol><h3>Why VideoPoet Matters:</h3><p>The significance of VideoPoet extends beyond just creating cool videos:</p><ol><li>Unified Approach: By adapting language model techniques to video, VideoPoet demonstrates a more unified approach to AI that could lead to more flexible and capable systems in the future.</li><li>Creative Tool: For artists, filmmakers, and content creators, tools like VideoPoet could dramatically lower the barriers to creating complex visual content.</li><li>Advancements in AI Understanding: The model’s ability to handle 3D concepts and camera movements suggests that AI is developing a more sophisticated understanding of the visual world.</li><li>Potential Applications:</li></ol><ul><li>Film and TV Production: Quickly visualizing scenes or creating rough animations.</li><li>Advertising: Generating video content more efficiently.</li><li>Education: Creating educational videos and simulations.</li><li>Game Development: Assisting in creating cutscenes or concept videos.</li><li>Virtual and Augmented Reality: Potentially generating dynamic content for immersive experiences.</li></ul><h3>Future Directions:</h3><p>The researchers behind VideoPoet suggest several areas for future improvement and exploration:</p><ol><li>Scaling Up: Increasing the model’s size and training data could potentially lead to even better performance and new capabilities.</li><li>Improved Temporal Consistency: Developing techniques to ensure better consistency across longer videos.</li><li>Text Rendering: Finding ways to generate readable and coherent text within videos.</li><li>Ethical AI: Continuing to develop safeguards and guidelines for responsible use of this technology.</li></ol><h3>Conclusion:</h3><p>VideoPoet represents a significant leap forward in the field of AI-generated video content. By adapting techniques from language models to the domain of video, the researchers at Google have created a flexible, powerful system capable of handling a wide range of video-related tasks.</p><p>While there’s still room for improvement, VideoPoet opens up exciting possibilities for the future of content creation. It suggests a world where complex visual stories could be brought to life with just a few words, where editing and manipulating video becomes as easy as editing text.</p><p>As this technology continues to evolve, it will be fascinating to see how it impacts fields like entertainment, education, and communication. At the same time, it will be crucial to consider the ethical implications and work towards ensuring that such powerful tools are used responsibly.</p><p>VideoPoet is not just a step forward in AI video generation; it’s a glimpse into a future where the boundaries between human and machine creativity continue to blur and expand in exciting new ways.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c5ea8270efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Compression — Hands on Guide for LLM Lingua-2]]></title>
            <link>https://deveshsurve.medium.com/prompt-compression-hands-on-guide-for-llm-lingua-2-2baac53800d6?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2baac53800d6</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prompt]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 19:39:37 GMT</pubDate>
            <atom:updated>2024-08-05T19:39:37.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prompt Compression — Hands on Guide for LLM Lingua-2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J615IZfwbXK8HiVNlq6Nsw.png" /></figure><p>So a really interesting paper I read about was in the domain of LLMs, specifically about Prompt compression ( <a href="https://arxiv.org/abs/2403.12968">https://arxiv.org/abs/2403.1296 )</a> and I was quite fancinated by it, so I decided to write a simple explanation and tutorial on it since I didn’t find any good ones online.</p><p>And Ofcourse, like any normal person your question would be :</p><h3>What is Prompt Compression ?</h3><p>So in simple words, As LLMs grow more powerful and complex, the length and intricacy of prompts used to query them have also increased. Now this has led to significant computational demands and higher costs.</p><p><strong>Prompt compression is the process of reducing the length of input prompts to LLMs while retaining essential information.</strong></p><h4>Why Does Prompt Compression Matter at Scale?</h4><p>Now This technique is crucial because:</p><ul><li><strong>Efficiency</strong>: Shorter prompts lead to faster inference times, reducing the time it takes for an LLM to generate a response.</li><li><strong>Cost Savings</strong>: Many LLM services, such as those provided by OpenAI, charge users based on the number of tokens processed. Compressing prompts can significantly lower these costs.</li><li><strong>Improved Performance</strong>: In some cases, long prompts can overwhelm LLMs, causing them to lose contextual accuracy. Compressed prompts can help maintain or even enhance the model’s performance by focusing on the most relevant information.</li></ul><h3><strong>Okay, So What is this LLM Lingua?</strong></h3><p>Now you’re asking the right questions. So LLM Lingua is a framework developed by researchers at Tsinghua University and Microsoft aimed at improving the efficiency of prompt compression. <strong><em>LLMLingua utilizes a compact, well-trained language model (e.g., GPT2-small, LLaMA-7B) to identify and remove non-essential tokens in prompts. This approach enables efficient inference with large language models (LLMs), and they promise up to 20x compression with minimal performance loss</em></strong>. The latest version, LLMLingua-2, introduces a task-agnostic approach that is faster and more efficient than previous methods.</p><h4>Key Features of LLMLingua-2:</h4><ul><li><strong>Task-Agnostic Compression</strong>: Unlike task-aware methods that tailor compression to specific tasks, LLMLingua-2 can be applied broadly across various applications.</li><li><strong>Bidirectional Transformer Encoder</strong>: Uses a lightweight bidirectional transformer model to capture essential information from both directions of the text.</li><li><strong>Lower Latency</strong>: Designed to be computationally efficient, resulting in lower latency during inference.</li></ul><p>So I decided to write a small hands-on guide about it after reffering their documentation.</p><p>I have also created a colab notebook on the same, Here’s the link to that : <a href="https://colab.research.google.com/drive/1jwtJ0p_qrRNY9lOy48lybYEcx6TkJD31?usp=sharing">https://colab.research.google.com/drive/1jwtJ0p_qrRNY9lOy48lybYEcx6TkJD31?usp=sharing</a></p><p>Here are some of the key code snippets :</p><h4><strong>How to Use LLMLingua-2: A Demo</strong></h4><p>To demonstrate the use of LLMLingua-2, let’s go through a step-by-step guide on setting it up and applying it to both in-domain and out-of-domain datasets.</p><h3>Step 1: Installation and Setup</h3><p>First, ensure you have the necessary libraries installed. You can install the LLMLingua package and OpenAI’s API as follows:</p><pre>!pip install llmlingua openai datasets</pre><h3>Step 2: Initializing the Prompt Compressor</h3><p>There are 2 variations of this available on Hugging Face as well as a hosted space for you to use. Do check those out:</p><p><a href="https://huggingface.co/microsoft?search_models=llml">LLMLingua models on Hugging Face</a></p><pre>from llmlingua import PromptCompressor</pre><pre>llm_lingua = PromptCompressor(<br>    model_name=&quot;microsoft/llmlingua-2-xlm-roberta-large-meetingbank&quot;,<br>    use_llmlingua2=True,<br>)</pre><h3>Step 3: Loading a Dataset</h3><p>Next, we load a test dataset using the Hugging Face datasets library.</p><pre>from datasets import load_dataset<br><br>dataset = load_dataset(&quot;huuuyeah/meetingbank&quot;, split=&quot;test&quot;)<br>context = dataset[0][&quot;transcript&quot;]<br>question = &quot;What is the agenda item three resolution 31669 about?\nAnswer:&quot;<br>prompt = &quot;\n\n&quot;.join([context, question])</pre><pre>len(prompt)</pre><p>As you see, the entire prompt is about 7000 characters.</p><h3>Step 4: Initializing the OpenAI API Client</h3><pre>from openai import OpenAI<br><br>client = OpenAI(api_key=&quot;&lt;Replace with your key&gt;&quot;)<br>chat_completion = client.chat.completions.create(<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: prompt,<br>        }<br>    ],<br>    model=&quot;gpt-3.5-turbo&quot;,<br>    max_tokens=100,<br>    temperature=0,<br>    top_p=1,<br>    n=1<br>)<br>print(chat_completion.choices[0].message.content)</pre><h3>Step 5: Compressing the Prompt Using LLMLingua</h3><ul><li><strong>compressed_prompt</strong> = llm_lingua.compress_prompt(…)</li><li>Purpose: This line compresses the text in the context variable using the llm_lingua library’s compress_prompt method.</li><li><strong>rate</strong>=0.33</li><li>Purpose: Specifies the compression rate. A rate of 0.33 means the function will attempt to reduce the text to 33% of its original size, effectively compressing it by 67%.</li><li><strong>force_tokens</strong>=[“!”, “.”, “?”, “\n”]</li><li>Purpose: Ensures that certain tokens or characters remain in the compressed text.</li><li><strong>drop_consecutive</strong>=True</li><li>Purpose: Specifies that consecutive duplicate tokens should be dropped.</li></ul><pre>compressed_prompt = llm_lingua.compress_prompt(<br>    context,<br>    rate=0.33,<br>    force_tokens=[&quot;!&quot;, &quot;.&quot;, &quot;?&quot;, &quot;\n&quot;],<br>    drop_consecutive=True,<br>)<br>shorter_prompt = &quot;\n\n&quot;.join([compressed_prompt[&quot;compressed_prompt&quot;], question])<br>print(len(shorter_prompt))</pre><p>And you see that suddenly our prompt has been reduced by 67%!</p><pre>chat_completion = client.chat.completions.create(<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: shorter_prompt,<br>        }<br>    ],<br>    model=&quot;gpt-3.5-turbo&quot;,<br>    max_tokens=100,<br>    temperature=0,<br>    top_p=1,<br>    n=1<br>)<br>print(chat_completion.choices[0].message.content)</pre><h4>And yet, the answer remains the same!</h4><h3>Step 6: Loading Another Sample from the LongBench Dataset ( Out-of-Domain Example )</h3><p>We start by defining prompt templates for different datasets and tasks.</p><pre>dataset2prompt = {<br>    &quot;narrativeqa&quot;: &quot;You are given a story, which can be either a novel or a movie script, and a question. Answer the question as concisely as you can, using a single phrase if possible. Do not provide any explanation.\n\nStory: {context}\n\nNow, answer the question based on the story as concisely as you can, using a single phrase if possible. Do not provide any explanation.\n\nQuestion: {input}\n\nAnswer:&quot;,<br>}<br>dataset2maxlen = {<br>    &quot;narrativeqa&quot;: 128,<br>}<br>task = &quot;narrativeqa&quot;<br>dataset = load_dataset(&quot;THUDM/LongBench&quot;, task, split=&quot;test&quot;)<br>sample = dataset[3]<br>context = sample[&quot;context&quot;]<br>prompt_format = dataset2prompt[task]<br>max_gen = int(dataset2maxlen[task])<br>new_prompt = prompt_format.format(**sample)</pre><p>Again, we see that our prompt is quite huge character length-wise.</p><pre>chat_completion = client.chat.completions.create(<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: new_prompt,<br>        }<br>    ],<br>    model=&quot;gpt-3.5-turbo&quot;,<br>    max_tokens=100,<br>    temperature=0,<br>    top_p=1,<br>    n=1<br>)<br>print(chat_completion.choices[0].message.content)</pre><p>And the answer to our prompt is “To persuade Socrates to escape.”</p><h3>Step 7: Compressing with Respect to Target Tokens</h3><p>Here, we see that instead of a compression rate we use target tokens.</p><pre>compressed_prompt = llm_lingua.compress_prompt(<br>    context,<br>    target_token=3000,<br>    force_tokens=[&quot;!&quot;, &quot;.&quot;, &quot;?&quot;, &quot;\n&quot;],<br>    drop_consecutive=True,<br>)</pre><p>Again, we see that our prompt has become a third of what it was!</p><pre>sample[&quot;context&quot;] = compressed_prompt[&quot;compressed_prompt&quot;]<br>new_smaller_prompt = prompt_format.format(**sample)</pre><pre>chat_completion = client.chat.completions.create(<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: new_smaller_prompt,<br>        }<br>    ],<br>    model=&quot;gpt-3.5-turbo&quot;,<br>    max_tokens=100,<br>    temperature=0,<br>    top_p=1,<br>    n=1<br>)<br>print(chat_completion.choices[0].message.content)</pre><h4>And yet, our answer remains correct!</h4><h3>Benefits of Using LLMLingua-2</h3><ul><li><strong>Scalability</strong>: LLMLingua-2’s ability to compress prompts effectively allows for scalable LLM applications.</li><li><strong>Cost Efficiency</strong>: By reducing the number of tokens, LLMLingua-2 helps in lowering the operational costs associated with using LLM services.</li><li><strong>Performance Enhancement</strong>: Compressed prompts can help maintain or improve the accuracy and relevance of LLM responses, especially for models that struggle with long contexts.</li></ul><h3>Limitations and Considerations</h3><p>While LLMLingua-2 is highly effective for general prompt compression, task-specific methods might still outperform it in specialized scenarios. For instance, task-aware compression methods like LongLLMlingua leverage additional context-specific information, which can result in better performance for certain tasks.</p><h3>Conclusion</h3><p>Prompt compression is a critical innovation in optimizing the use of large language models. LLMLingua-2 stands out as a powerful tool that provides significant advantages in terms of speed, efficiency, and cost savings. By incorporating this method into your LLM workflows, you can achieve better performance and scalability, making it an invaluable asset in the era of advanced AI applications.</p><p>For more detailed information and to access the source code for LLMLingua-2, visit the <a href="https://github.com/microsoft/LLMLingua">GitHub repository</a> and the <a href="https://arxiv.org/abs/2403.12968">arXiv paper</a>.</p><p>If you read all the way till, I’d really appreciate if you would give me a clap if you liked the article. Follow for more such content !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2baac53800d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation : A Machine Learning Perspective]]></title>
            <link>https://deveshsurve.medium.com/big-o-notation-a-machine-learning-perspective-a49c46dd8018?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49c46dd8018</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 22:46:18 GMT</pubDate>
            <atom:updated>2024-06-12T22:46:18.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>Big O Notation : A Machine Learning Perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8gkuucfagRDvTB6zpi3WA.png" /></figure><p>A few weeks ago, I had a nice conversation with a software engineer friend of mine about the significance of algorithmic complexity. We delved into how crucial Big O notation is for optimizing code and ensuring efficiency but wasn’t all that important in Machine Learning since we have the libraries ready-made for us. This discussion, however piqued my curiosity about its validity and as I dug deeper, I realized just how importnat Big O notation is in these fields. So, as usual I decided to write about it.</p><p>In this article, we will:</p><ul><li><strong>Explain Big O notation</strong>: Learn what Big O notation is and why it’s important.</li><li><strong>Provide practical use cases</strong>: See Big O notation in action through seven detailed examples relevant to data science and machine learning.</li><li><strong>Highlight real-world impact</strong>: Understand how different algorithms perform and why selecting the right one is essential for scalability and efficiency.</li></ul><h3>Why Big O Notation Matters</h3><p>Big O notation is more than just a theoretical concept; it is a practical tool for anyone working with data and algorithms. It helps you:</p><ul><li><strong>Predict Performance</strong>: Understand how algorithms will perform as your data grows.</li><li><strong>Optimize Resources</strong>: Choose the most efficient algorithms to save time and computational power.</li><li><strong>Improve Scalability</strong>: Ensure your solutions can handle increasing amounts of data without degrading in performance.</li></ul><h3>What You’ll Learn</h3><ol><li><strong>Fundamentals of Big O Notation</strong>: A clear explanation of different complexity classes.</li><li><strong>Detailed Use Cases</strong>: Examples from data cleaning to machine learning algorithms, showcasing the practical application of Big O notation.</li><li><strong>Comparison of Algorithms</strong>: Insights into why certain algorithms are preferred over others in specific scenarios.</li></ol><p>By the end of this article, you will have a solid understanding of Big O notation and how to apply it to your work in data science and machine learning, leading to more efficient and scalable solutions.</p><p>Let’s dive in and demystify Big O notation.</p><h3>Table of Contents</h3><ol><li>Introduction</li><li>What is Big O Notation?</li><li>Common Big O Notations</li><li>Use Case 1: Data Cleaning and Preprocessing</li><li>Use Case 2: K-Nearest Neighbors (KNN) Classifier vs. Decision Trees</li><li>Use Case 3: Principal Component Analysis (PCA) vs. t-SNE</li><li>Use Case 4: Linear Regression vs. Neural Networks</li><li>Use Case 5: Logistic Regression vs. Support Vector Machines (SVM)</li><li>Use Case 6: Random Forest vs. Gradient Boosting</li><li>Conclusion</li><li>References</li></ol><h3>What is Big O Notation?</h3><p>Big O notation is a mathematical concept that describes the upper bound of an algorithm’s running time or space requirements relative to the input size (n). It helps us classify algorithms based on their worst-case or average-case performance, offering insights into their scalability and efficiency.</p><h3>Common Big O Notations Explained Simply</h3><p><strong>1.O(1): Constant Time</strong></p><ul><li><strong>What it means:</strong> The algorithm’s running time doesn’t change, no matter how much data you have.</li><li><strong>Example:</strong> Checking if a light is on. It takes the same time whether you have one light or a hundred lights.</li></ul><p><strong>2. O(log n): Logarithmic Time</strong></p><ul><li><strong>What it means:</strong> The running time increases slowly even if the amount of data increases a lot.</li><li><strong>Example:</strong> Looking up a name in a phone book. Even if the phone book gets much thicker, you can still find the name pretty quickly by halving the section you look at each time.</li></ul><p><strong>3. O(n): Linear Time</strong></p><ul><li><strong>What it means:</strong> The running time increases directly with the amount of data.</li><li><strong>Example:</strong> Reading a list of names. If the list doubles in size, it will take twice as long to read through it.</li></ul><p><strong>4. O(n log n): Linearithmic Time</strong></p><ul><li><strong>What it means:</strong> The running time grows a bit faster than linear time, but not as fast as quadratic time.</li><li><strong>Example:</strong> Sorting a deck of cards. Sorting a larger deck takes longer, but efficient methods make the increase manageable.</li></ul><p><strong>5. O(n²): Quadratic Time</strong></p><ul><li><strong>What it means:</strong> The running time increases much faster as the amount of data grows.</li><li><strong>Example:</strong> Comparing every student with every other student in a class to find the tallest pair. Doubling the number of students makes the task take four times as long.</li></ul><p><strong>6. O(2^n): Exponential Time</strong></p><ul><li><strong>What it means:</strong> The running time doubles with each additional piece of data, which gets very slow, very quickly.</li><li><strong>Example:</strong> Trying every combination of a set of locks. Adding more locks makes the task much more time-consuming.</li></ul><h3>Use Case 1: Data Cleaning and Preprocessing</h3><p><strong>Scenario: Removing duplicates from a dataset</strong></p><p><strong>Naive Approach (O(n²)):</strong> This method involves iterating through each element and comparing it with every other element to find duplicates. While simple to implement, it becomes impractical for large datasets due to its quadratic time complexity.</p><pre>def remove_duplicates_naive(data):<br>    unique_data = []<br>    for item in data:<br>        if item not in unique_data:<br>            unique_data.append(item)<br>    return unique_dat</pre><p><strong>Optimized Approach (O(n)):</strong> Using a set to track unique elements, this approach significantly reduces the time complexity, making it much more efficient for large datasets.</p><pre>def remove_duplicates_optimized(data):<br>    return list(set(data))</pre><p><em>Key Takeaway: Utilizing data structures like sets can drastically improve the efficiency of data cleaning tasks.</em></p><h3>Use Case 2: K-Nearest Neighbors (KNN) Classifier vs. Decision Trees</h3><p><strong>Scenario: Classifying data points using KNN and Decision Trees</strong></p><p><strong>K-Nearest Neighbors (KNN) Classifier (O(n)):</strong> KNN classifies a new data point based on the majority class of its k nearest neighbors in the training set. The time complexity of prediction is linear with respect to the number of training samples.</p><pre>from sklearn.neighbors import KNeighborsClassifier<br>import time<br>import numpy as np<br><br># Generating a random dataset<br>X_train = np.random.rand(1000, 50)<br>y_train = np.random.randint(0, 2, 1000)<br>X_test = np.random.rand(100, 50)<br>start_time = time.time()<br>knn = KNeighborsClassifier(n_neighbors=3)<br>knn.fit(X_train, y_train)<br>knn_predictions = knn.predict(X_test)<br>print(&quot;KNN Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><strong>Decision Trees (O(n log n)):</strong> Decision trees are a non-parametric supervised learning algorithm that uses a tree-like model of decisions based on features. The time complexity of training a decision tree is linearithmic, while the prediction time is logarithmic.</p><pre>from sklearn.tree impo rt DecisionTreeClassifier<br><br>start_time = time.time()<br>decision_tree = DecisionTreeClassifier()<br>decision_tree.fit(X_train, y_train)<br>dt_predictions = decision_tree.predict(X_test)<br>print(&quot;Decision Tree Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><em>Key Takeaway: Decision trees generally offer faster prediction times compared to KNN, making them more suitable for real-time applications.</em></p><h3>Use Case 3: Principal Component Analysis (PCA) vs. t-SNE</h3><p><strong>Scenario: Reducing the dimensionality of a dataset</strong></p><p><strong>Principal Component Analysis (PCA) (O(n³)):</strong> PCA transforms high-dimensional data to a lower-dimensional subspace while preserving the maximum variance. Its cubic time complexity can be prohibitive for large datasets.</p><pre>from sklearn.decomposition import PCA<br><br>start_time = time.time()<br>pca = PCA(n_components=2)<br>pca_transformed = pca.fit_transform(X_train)<br>print(&quot;PCA Transformation Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><strong>t-SNE (O(n²)):</strong> t-SNE is a non-linear dimensionality reduction technique that models each high-dimensional object by a two-dimensional point in such a way that similar objects are modeled by nearby points and dissimilar objects are modeled by distant points.</p><pre>from sklearn.manifold import TSNE<br><br>start_time = time.time()<br>tsne = TSNE(n_components=2)<br>tsne_transformed = tsne.fit_transform(X_train)<br>print(&quot;t-SNE Transformation Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><em>Key Takeaway: While t-SNE is computationally intensive, it is often more effective for visualizing high-dimensional data.</em></p><h3>Use Case 4: Linear Regression vs. Neural Networks</h3><p><strong>Scenario: Predicting a continuous target variable using Linear Regression and Neural Networks</strong></p><p><strong>Linear Regression (O(n³)):</strong> Linear regression models the relationship between a dependent variable and one or more independent variables using a linear equation. The cubic time complexity for training can be a bottleneck for large datasets.</p><pre>from sklearn.linear_model import LinearRegression<br><br>start_time = time.time()<br>linear_regression = LinearRegression()<br>linear_regression.fit(X_train, y_train)<br>lr_predictions = linear_regression.predict(X_test)<br>print(&quot;Linear Regression Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><strong>Neural Networks (O(n²)):</strong> Neural networks can model complex non-linear relationships between inputs and outputs. While their time complexity for training is quadratic, they are more flexible and can handle larger datasets more effectively.</p><pre>from sklearn.neural_network import MLPRegressor<br><br>start_time = time.time()<br>neural_network = MLPRegressor(hidden_layer_sizes=(100,), max_iter=500)<br>neural_network.fit(X_train, y_train)<br>nn_predictions = neural_network.predict(X_test)<br>print(&quot;Neural Network Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><em>Key Takeaway: Neural networks offer greater flexibility for complex datasets, though they require more computational resources.</em></p><h3>Use Case 5: Logistic Regression vs. Support Vector Machines (SVM)</h3><p><strong>Scenario: Classifying data points using Logistic Regression and Support Vector Machines</strong></p><p><strong>Logistic Regression (O(n²)):</strong> Logistic regression models the probability of a binary outcome using a logistic function. It has a quadratic time complexity for training.</p><pre>from sklearn.linear_model import LogisticRegression<br><br>start_time = time.time()<br>logistic_regression = LogisticRegression()<br>logistic_regression.fit(X_train, y_train)<br>lr_predictions = logistic_regression.predict(X_test)<br>print(&quot;Logistic Regression Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><strong>Support Vector Machines (SVM) (O(n²)):</strong> SVMs are powerful classifiers that find the hyperplane that best separates the classes. Their quadratic time complexity can make them less practical for very large datasets.</p><pre>from sklearn.svm import SVC<br><br>start_time = time.time()<br>svm = SVC()<br>svm.fit(X_train, y_train)<br>svm_predictions = svm.predict(X_test)<br>print(&quot;SVM Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><em>Key Takeaway: Both logistic regression and SVMs can be effective for binary classification, but SVMs may become impractical with very large datasets.</em></p><h3>Use Case 6: Random Forest vs. Gradient Boosting</h3><p><strong>Scenario: Enhancing model performance using ensemble methods</strong></p><p><strong>Random Forest (O(m * n log n)):</strong> Random Forests are an ensemble method that uses multiple decision trees to improve predictive accuracy. The time complexity depends on the number of trees (m) and the complexity of each tree (n log n).</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br>start_time = time.time()<br>random_forest = RandomForestClassifier(n_estimators=100)<br>random_forest.fit(X_train, y_train)<br>rf_predictions = random_forest.predict(X_test)<br>print(&quot;Random Forest Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><strong>Gradient Boosting (O(m * n log n)):</strong> Gradient Boosting builds models sequentially, each new model correcting errors made by the previous ones. Its time complexity is similar to Random Forests but often requires more trees (m) to achieve high performance.</p><pre>from sklearn.ensemble import GradientBoostingClassifier<br><br>start_time = time.time()<br>gradient_boosting = GradientBoostingClassifier(n_estimators=100)<br>gradient_boosting.fit(X_train, y_train)<br>gb_predictions = gradient_boosting.predict(X_test)<br>print(&quot;Gradient Boosting Prediction Time: {:.6f} seconds&quot;.format(time.time() - start_time))</pre><p><em>Key Takeaway: Both Random Forest and Gradient Boosting can enhance model performance, with Gradient Boosting often achieving higher accuracy at the cost of increased training time.</em></p><h3>Conclusion</h3><p>Understanding Big O notation and algorithmic complexity is super important for optimizing data science and machine learning workflows. By analyzing the complexity of different approaches, we can make smart decisions that improve efficiency and scalability. The examples we’ve provided show how algorithms can vary a lot in performance, highlighting the importance of choosing the right method for each task.</p><p>Adding Big O analysis to your workflow not only helps you understand algorithms better, but also lets you create solutions that are more efficient and effective for your data science and machine learning projects. And more importantly, it might be asked in your interviews !</p><p>Feel free to reach out with any questions or comments. Happy coding!</p><h3>References</h3><p>Big O Notation: <a href="https://en.wikipedia.org/wiki">Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49c46dd8018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smart Medical Diagnostics: LLM Auto-Prompt & Chaining with DSPy]]></title>
            <link>https://deveshsurve.medium.com/building-smart-medical-diagnostics-llm-auto-prompt-chaining-with-dspy-c760d87be3a6?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c760d87be3a6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[dspy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 23:26:26 GMT</pubDate>
            <atom:updated>2024-06-09T23:26:26.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uPELqtxJefHGHbnokyNtw.png" /></figure><h3>Introduction</h3><p>So I was reading papers on prompting when I came across the paper <a href="https://arxiv.org/pdf/2310.03714">https://arxiv.org/pdf/2310.03714</a> — <strong><em>Compiling declarative language model calls into self-improving pipelines</em>.</strong> The framework piqued my interest because, until a few months ago, prompt engineering was all the rage. The job market was buzzing with roles for prompt engineers. However, this trend has shifted. Prompt engineering was neither an art nor a science but rather akin to the Clever Hans phenomenon — humans providing the necessary context for systems to respond more effectively.</p><p>Books and blogs sprouted, claiming to provide the “Top 50 prompts to get the best out of GPT,” among other grand promises. However, large-scale experiments have shown that there is no single prompt or strategy that works for all problems. Some prompts may seem better in isolation but turn out to be hit-and-miss when analyzed comprehensively.</p><p>So today, we are going to explore DSPy: a framework developed by Stanford for compiling declarative language model calls into self-improving pipelines. This innovative approach treats LLMs as modules optimized by a compiler, similar to the abstractions found in PyTorch.</p><h3>Why a Medical Diagnosis Example?</h3><p>Medical diagnosis is a complex task that requires detailed reasoning and precise decision-making. This makes it an ideal domain to demonstrate the capabilities of DSPy’s Chain-of-Thought (CoT) reasoning. The CoT approach breaks down the diagnostic process into intermediate steps, leading to a final diagnosis. This not only mirrors the logical thought process of medical professionals but also leverages the strengths of LLMs to provide accurate and efficient diagnoses.</p><p>In this guide, we will walk through the steps to create a medical diagnosis application using DSPy. We will cover:</p><ul><li>Setting up the environment</li><li>Defining the task with DSPy signatures</li><li>Creating and optimizing modules for intermediate diagnostic steps and final diagnoses</li><li>Comparing results before and after optimization</li></ul><p>By the end of this tutorial, you will have a comprehensive understanding of how to use DSPy to enhance medical diagnostics through automated reasoning chains.</p><h3>Understanding Prompting Libraries</h3><p>To understand where DSPy fits into the landscape of prompting libraries, it’s helpful to look at the different types of libraries available for working with large language models (LLMs):</p><h4>Prompt Wrappers:</h4><p>These libraries provide a minimal level of abstraction for creating and managing prompts. They typically offer simple tools for string insertion and extraction, allowing users to quickly generate prompts without much overhead.</p><p><em>Example libraries: MiniChain</em></p><h4>Application Development Libraries:</h4><p>These high-level libraries are designed for building applications with LLMs. They come with pre-built modules and tools that help developers quickly configure and integrate LLM capabilities into their applications. These libraries abstract away much of the complexity involved in working with LLM APIs.</p><p><em>Example libraries: LangChain, LlamaIndex</em></p><h4>Generation Control Libraries:</h4><p>These libraries focus on controlling the output of LLMs. They provide tools for implementing control flows, enforcing specific output schemas (such as JSON), and constraining the model’s outputs to match certain patterns or regular expressions.</p><p><em>Example libraries: Guidance, LMQL, RELM, Outlines</em></p><h4>Prompt Generation &amp; Automation:</h4><p>Similar to traditional machine learning, these libraries define inputs and targets along with high-level operators or building blocks. They optimize or generate the specifics for each prompt and stage, automating much of the prompt development process.</p><p><em>Example libraries: DSPy</em></p><h3>The Role of DSPy</h3><p>Prompt development and LLM chaining often require extensive trial and error. This process involves not only developing effective prompts but also composing them into discrete tasks that LLMs can handle efficiently. DSPy simplifies this process by providing a framework for developing higher-level tasks that can self-optimize and evaluate their own performance.</p><p>With DSPy, you can:</p><p><strong>Define complex tasks</strong>: Use DSPy’s signatures and modules to break down complex tasks into manageable sub-tasks.<br><strong>Automate prompt generation</strong>: DSPy can automatically generate and optimize prompts for different stages of a task, reducing the need for manual tweaking.<br><strong>Optimize performance</strong>: DSPy’s teleprompters and compilers work together to improve the performance of your LLM-based applications, ensuring that they adapt and improve over time.</p><p>Now,</p><p>In the following sections, we will walk through the steps to create a medical diagnosis application using DSPy. By the end of this tutorial, you will understand how to use DSPy to build sophisticated AI systems that can handle complex reasoning tasks in the medical field.</p><p>Here’s the link to the Full Colab NB — <a href="https://colab.research.google.com/drive/1I1S8xC46NIadh2nAFdeZWA09Y-B8uSH1?usp=sharing">https://colab.research.google.com/drive/1I1S8xC46NIadh2nAFdeZWA09Y-B8uSH1?usp=sharing</a></p><h4>Let’s go section by section</h4><p>To get started with DSPy, you’ll need to set up your environment.</p><pre>%load_ext autoreload<br>%autoreload 2<br><br>import sys<br>import os<br><br>try: # When on Google Colab, let&#39;s clone the notebook so we download the cache.<br>    import google.colab<br>    repo_path = &#39;dspy&#39;<br>    !git -C $repo_path pull origin || git clone https://github.com/stanfordnlp/dspy $repo_path<br>except:<br>    repo_path = &#39;.&#39;<br><br>if repo_path not in sys.path:<br>    sys.path.append(repo_path)<br><br># Set up the cache for this notebook<br>os.environ[&quot;DSP_NOTEBOOK_CACHEDIR&quot;] = os.path.join(repo_path, &#39;cache&#39;)<br><br>import pkg_resources # Install the package if it&#39;s not installed<br>if not &quot;dspy-ai&quot; in {pkg.key for pkg in pkg_resources.working_set}:<br>    !pip install -U pip<br>    !pip install dspy-ai<br>    !pip install openai~=0.28.1<br><br>import dspy</pre><h4>Configure DSPy:</h4><p>After installing DSPy, configure it for your project. This may include setting up API keys for language models and configuring other environment settings.</p><pre># Configure your OpenAI API key<br>import openai<br>openai.api_key = &#39;your-api-key&#39;<br><br># Import DSPy and configure settings<br>import dspy</pre><h4>Verify Installation:</h4><p>Ensure that DSPy and all dependencies are installed correctly by running a simple test.</p><pre># Verify DSPy installation by running a simple test<br>print(dspy.__version__)</pre><h4>Defining the Task with DSPy</h4><p>In this section, we will define the task of medical diagnosis using DSPy. We will create signatures that specify the inputs and outputs for each step in the Chain-of-Thought (CoT) reasoning process, including intermediate diagnostic steps and the final diagnosis.</p><h4>Creating Signatures</h4><p>Signatures in DSPy define the structure of the tasks, specifying what inputs the language model will receive and what outputs it should produce. For our medical diagnosis example, we will create two main signatures: one for generating intermediate diagnostic steps and one for generating the final diagnosis.</p><pre>class GenerateDiagnosticStep(dspy.Signature):<br>    &quot;&quot;&quot;Generate an intermediate diagnostic step based on symptoms and medical history.&quot;&quot;&quot;<br>    symptoms = dspy.InputField(desc=&quot;patient&#39;s symptoms&quot;)<br>    medical_history = dspy.InputField(desc=&quot;patient&#39;s medical history&quot;)<br>    diagnostic_step = dspy.OutputField(desc=&quot;an intermediate diagnostic step&quot;)<br><br>class GenerateFinalDiagnosis(dspy.Signature):<br>    &quot;&quot;&quot;Generate the final diagnosis using all diagnostic steps.&quot;&quot;&quot;<br>    symptoms = dspy.InputField(desc=&quot;patient&#39;s symptoms&quot;)<br>    medical_history = dspy.InputField(desc=&quot;patient&#39;s medical history&quot;)<br>    diagnostic_steps = dspy.InputField()<br>    final_diagnosis = dspy.OutputField(desc=&quot;the final diagnosis of the patient&quot;)</pre><h4>Developing Modules</h4><p>With the signatures defined, we can now develop the modules that will use these signatures to perform the diagnostic steps and generate the final diagnosis.</p><h4>MedicalDiagnosisQA Module</h4><p>This module will use the GenerateDiagnosticStep and GenerateFinalDiagnosis signatures to implement the CoT reasoning process for medical diagnosis.</p><pre>class MedicalDiagnosisQA(dspy.Module):<br>    def __init__(self, num_steps=3):<br>        super().__init__()<br>        self.generate_step = dspy.ChainOfThought(GenerateDiagnosticStep)<br>        self.generate_final_diagnosis = dspy.ChainOfThought(GenerateFinalDiagnosis)<br>        self.num_steps = num_steps<br>    <br>    def forward(self, symptoms, medical_history):<br>        try:<br>            # Step 1: Generate intermediate diagnostic steps<br>            diagnostic_steps = []<br>            current_context = medical_history<br>            for step_num in range(self.num_steps):<br>                step = self.generate_step(symptoms=symptoms, medical_history=current_context).diagnostic_step<br>                diagnostic_steps.append(step)<br>                current_context += &quot; &quot; + step<br>                logger.info(f&quot;Step {step_num + 1}: {step}&quot;)<br><br>            # Step 2: Generate the final diagnosis using all diagnostic steps<br>            final_diagnosis = self.generate_final_diagnosis(symptoms=symptoms, medical_history=current_context, diagnostic_steps=&quot; &quot;.join(diagnostic_steps)).final_diagnosis<br>            logger.info(f&quot;Final Diagnosis: {final_diagnosis}&quot;)<br><br>            return dspy.Prediction(final_diagnosis=final_diagnosis, diagnostic_steps=diagnostic_steps)<br><br>        except Exception as e:<br>            logger.error(f&quot;An error occurred during diagnosis: {e}&quot;)<br>            raise</pre><h4>Training and Validation</h4><p>To ensure our module performs accurately, we will create a small dataset for training and validation. This dataset will include examples of symptoms, medical history, intermediate diagnostic steps, and final diagnoses.</p><pre># Example training data<br>train_data = [<br>    dspy.Example(symptoms=&quot;fever, cough, fatigue&quot;, medical_history=&quot;patient has a history of asthma&quot;, diagnostic_step=&quot;consider respiratory infections&quot;, final_diagnosis=&quot;influenza&quot;),<br>    dspy.Example(symptoms=&quot;chest pain, shortness of breath&quot;, medical_history=&quot;patient has a history of high blood pressure&quot;, diagnostic_step=&quot;consider cardiovascular issues&quot;, final_diagnosis=&quot;angina&quot;),<br>    dspy.Example(symptoms=&quot;headache, nausea, dizziness&quot;, medical_history=&quot;patient recently suffered a minor head injury&quot;, diagnostic_step=&quot;consider neurological evaluation&quot;, final_diagnosis=&quot;concussion&quot;)<br>]<br><br>def validate_final_diagnosis(example, pred, trace=None):<br>    return example.final_diagnosis.lower() == pred.final_diagnosis.lower()</pre><h4>Comparing Results Before and After Compilation</h4><p>Finally, we will compare the performance of the module before and after compilation using an example case.</p><h4>Before Compilation</h4><pre># Example new symptoms and medical history<br>new_symptoms = &quot;persistent cough, weight loss, night sweats&quot;<br>new_medical_history = &quot;patient has a history of smoking&quot;<br><br># Get the prediction using the uncompiled module<br>uncompiled_medical_diagnosis_qa = MedicalDiagnosisQA()<br>uncompiled_prediction = uncompiled_medical_diagnosis_qa(symptoms=new_symptoms, medical_history=new_medical_history)<br><br># Print the input and the prediction<br>print(f&quot;Symptoms (Uncompiled): {new_symptoms}&quot;)<br>print(f&quot;Medical History (Uncompiled): {new_medical_history}&quot;)<br>print(f&quot;Predicted Final Diagnosis (Uncompiled): {uncompiled_prediction.final_diagnosis}&quot;)<br>print(f&quot;Intermediate Diagnostic Steps (Uncompiled): {uncompiled_prediction.diagnostic_steps}&quot;)</pre><h4>After Compilation</h4><pre># Get the prediction using the compiled module<br>compiled_prediction = compiled_medical_diagnosis_qa(symptoms=new_symptoms, medical_history=new_medical_history)<br><br># Print the input and the prediction<br>print(f&quot;Symptoms (Compiled): {new_symptoms}&quot;)<br>print(f&quot;Medical History (Compiled): {new_medical_history}&quot;)<br>print(f&quot;Predicted Final Diagnosis (Compiled): {compiled_prediction.final_diagnosis}&quot;)<br>print(f&quot;Intermediate Diagnostic Steps (Compiled): {compiled_prediction.diagnostic_steps}&quot;)</pre><h3>Summary and Analysis</h3><p>By following these steps, DSPy helps optimize the language model for complex medical reasoning tasks, resulting in improved accuracy and efficiency. This demonstrates the power of DSPy’s approach to handling sophisticated AI tasks beyond simple prompt-based methods.</p><blockquote>Thanks for reading! If you found this article useful, please leave a comment or a clap.</blockquote><blockquote>Follow me to stay updated on my latest articles</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c760d87be3a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to LLMs: Build a Content Moderation Filter and Learn Advanced Prompting with Free…]]></title>
            <link>https://deveshsurve.medium.com/beginners-guide-to-llms-build-a-content-moderation-filter-and-learn-advanced-prompting-with-free-87f3bad7c0af?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f3bad7c0af</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[content-moderation]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 01:09:26 GMT</pubDate>
            <atom:updated>2024-06-05T01:09:26.232Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginner’s Guide to LLMs: Build a Content Moderation Filter and Learn Advanced Prompting with Free Groq API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWXqZHqqK5Qiq0v_muQ-4g.png" /></figure><h3>Introduction</h3><p>Hey Everyone !</p><p>So one thing I’ve learnt over the years is that best way to build a useful application with an LLM (Large Language Model) often starts with identifying a practical problem. While sentiment analysis ( Checking if some text is positive/negative/neutral ) is a common use case that many people have explored, it only scratches the surface of what LLMs can do. ( And honestly is a bit boring )</p><p>So Recently, I was searching for ways to get a free API to experiment with different LLM promptings and discovered the Groq API. It’s equipped with an API call to one of the best open-source LLMs ( LLAMA-3 ) and is completely free !</p><p>But again, Creating a simple sentiment analysis felt too basic. To push the boundaries further, I decided to build a content moderation filter, integrating techniques like chain-of-thought (CoT) and few-shot prompting to enhance the model’s reasoning capabilities. But don’t worry about these terms yet, this blog will guide you through building such a moderation filter, showcasing an industry-relevant use case step by step.</p><h3>But First, why a Content Moderation Filter?</h3><p>Content moderation is crucial for maintaining safe and respectful online communities. With user-generated content flooding the internet, automated moderation tools are essential to classify and filter harmful or inappropriate content efficiently. By leveraging LLMs, we can create customizable and scalable moderation systems.</p><h4>Real-World Examples of Content Moderation</h4><p>Imagine you’re running a social media platform or a forum. Users post content all the time, and some of it might be harmful or inappropriate. Content moderation tools help automatically identify and filter out this content to keep the community safe.</p><h4>Importance of Automated Moderation Tools</h4><p>With the vast amount of user-generated content online, manual moderation isn’t feasible. Automated tools, powered by LLMs, can efficiently classify and filter content based on predefined rules.</p><h3>Basic Approach</h3><p>The basic approach involves defining the moderation rules and categories directly in the prompt, making it easy to customize and experiment with.</p><h4>What is a Prompt?</h4><p>A prompt is a set of instructions you give to the language model to get the desired output. For content moderation, the prompt includes guidelines for what content should be allowed or blocked.</p><h4>Example Prompt Structure</h4><p>Here’s a simple structure for a content moderation prompt:</p><pre>You are a content moderation expert tasked with categorizing user-generated <br>text based on the following guidelines:<br><br>BLOCK CATEGORY:<br>- [Description or examples of content that should be blocked]<br>ALLOW CATEGORY:<br>- [Description or examples of content that is allowed]<br><br>Here is the user-generated text to categorize:<br><br>&lt;user_text&gt;{{USER_TEXT}}&lt;/user_text&gt;</pre><p>You replace {{USER_TEXT}} with the actual user-generated text to be classified, and then send the prompt to the language model using the appropriate API. The model&#39;s response should be either &quot;ALLOW&quot; or &quot;BLOCK,&quot; indicating how the text should be handled based on your provided guidelines.</p><h3>Getting Your Groq API Key</h3><p>To use the Groq API, you first need to obtain an API key.</p><blockquote><strong>What is an API Key?</strong></blockquote><blockquote>So an API key is a code passed in by computer programs to identify the calling program. The Groq API uses this key to authenticate your requests.</blockquote><h4>Step-by-Step Guide</h4><ol><li><strong>Sign Up</strong>: Go to the Groq API website — <a href="https://console.groq.com/login">https://console.groq.com/login</a> and sign up for an account if you don’t already have one.</li><li><strong>Generate API Key</strong>: Once logged in, navigate to the API section of your dashboard. — <a href="https://console.groq.com/keys">https://console.groq.com/keys</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37x01oMeR5qRZOzmkPAvUQ.png" /></figure><ol><li><strong>Create a New Key</strong>: Click on “Create API Key” and give it a name that you can easily identify.</li><li><strong>Copy the Key</strong>: Once the key is generated, copy it and keep it in a secure place.</li></ol><p>You will use this key in your code to authenticate your requests to the Groq API.</p><p>Here’s the full colab reference notebook — <a href="https://colab.research.google.com/drive/1pUipKwlhCmbSZoZSlkCBlmmJBO2C9UcB?usp=sharing">https://colab.research.google.com/drive/1pUipKwlhCmbSZoZSlkCBlmmJBO2C9UcB?usp=sharing</a></p><h3>Example Usage with Groq API</h3><p>Let’s dive into an example that demonstrates how to use this approach with GPT and the Groq API.</p><h4>Simple Example</h4><h3>Step 1: Configure the Groq API</h3><p>First, set up the Groq API by initializing the client with your API key.</p><pre>import os<br>from groq import Groq<br><br># Configure Groq API<br>groq_api_key = &#39;your GROQ API KEY&#39;<br>os.environ[&quot;GROQ_API_KEY&quot;] = groq_api_key<br><br>client = Groq(api_key=os.environ.get(&quot;GROQ_API_KEY&quot;))</pre><h4>Step 2: Define the Moderation Function</h4><p>Next, define a function moderate_text that takes the user-generated text and the guidelines as inputs.</p><pre>def moderate_text(user_text, guidelines):<br>    prompt_template = &quot;&quot;&quot;<br>    You are a content moderation expert tasked with categorizing user-generated text based on the following guidelines:<br><br>    {guidelines}<br><br>    Here is the user-generated text to categorize:<br>    &lt;user_text&gt;{user_text}&lt;/user_text&gt;<br><br>    Based on the guidelines above, classify this text as either ALLOW or BLOCK. Return nothing else.<br>    &quot;&quot;&quot;</pre><h4>Step 3: Format the Prompt</h4><p>Format the prompt by inserting the user-generated text and the guidelines into the template.</p><pre>    # Format the prompt with the user text<br>    prompt = prompt_template.format(user_text=user_text, guidelines=guidelines)</pre><h4>Step 4: Send the Prompt to Groq API</h4><p>Send the formatted prompt to the Groq API and get the response.</p><pre>    # Send the prompt to Groq API and get the response<br>    chat_completion = client.chat.completions.create(<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>        ],<br>        model=&quot;llama3-8b-8192&quot;<br>    )</pre><h4>Step 5: Return the Response</h4><p>Return the response, which will be either “ALLOW” or “BLOCK.”</p><pre>return chat_completion.choices[0].message.content.strip()</pre><h3>Full Example</h3><p>Here’s how you can use the moderate_text function to moderate an array of user comments:</p><pre># Example guidelines<br>example_guidelines = &#39;&#39;&#39;BLOCK CATEGORY:<br>    - Promoting violence, illegal activities, or hate speech<br>    - Explicit sexual content<br>    - Harmful misinformation or conspiracy theories<br><br>    ALLOW CATEGORY:<br>    - Most other content is allowed, as long as it is not explicitly disallowed<br>&#39;&#39;&#39;<br><br>user_comments = [<br>    &quot;This movie was great, I really enjoyed it. The main actor really killed it!&quot;,<br>    &quot;Delete this post now or you better hide. I am coming after you and your family.&quot;,<br>    &quot;Stay away from the 5G cellphones!! They are using 5G to control you.&quot;,<br>    &quot;Thanks for the helpful information!&quot;,<br>]<br><br>for comment in user_comments:<br>    classification = moderate_text(comment, example_guidelines)<br>    print(f&quot;Comment: {comment}\nClassification: {classification}\n&quot;)</pre><p>Here’s how the output would look</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*E8oJS28BAqlISZIbcWi8OQ.png" /></figure><p><strong><em>Yay ! You just created your first LLM API application !</em></strong></p><h3>Improving the Prompt</h3><p>Now, you can easily customize the moderation rules by modifying the descriptions or examples provided in the prompt for the “BLOCK” and “ALLOW” categories.</p><h4>How to Modify Guidelines</h4><p><strong>Identify the Categories:</strong> Decide what types of content should be blocked or allowed.<br><strong>Write Descriptions:</strong> Write clear and detailed descriptions or examples for each category.<br><strong>Update the Prompt:</strong> Modify the prompt template with your new guidelines.</p><p>For example, if you wanted to moderate a rollercoaster enthusiast forum and ensure posts stay on topic, you could update the guidelines accordingly:</p><pre>rollercoaster_guidelines = &#39;&#39;&#39;BLOCK CATEGORY:<br>- Content that is not related to rollercoasters, theme parks, or the amusement industry<br>- Explicit violence, hate speech, or illegal activities<br>- Spam, advertisements, or self-promotion<br><br>ALLOW CATEGORY:<br>- Discussions about rollercoaster designs, ride experiences, and park reviews<br>- Sharing news, rumors, or updates about new rollercoaster projects<br>- Respectful debates about the best rollercoasters, parks, or ride manufacturers<br>- Some mild profanity or crude language, as long as it is not directed at individuals<br>&#39;&#39;&#39;<br><br>post_titles = [<br>    &quot;Top 10 Wildest Inversions on Steel Coasters&quot;,<br>    &quot;My Review of the New RMC Raptor Coaster at Cedar Point&quot;,<br>    &quot;Best Places to Buy Cheap Hiking Gear&quot;,<br>    &quot;Rumor: Is Six Flags Planning a Giga Coaster for 2025?&quot;,<br>    &quot;My Thoughts on the Latest Marvel Movie&quot;,<br>]<br><br>for title in post_titles:<br>    classification = moderate_text(title, rollercoaster_guidelines)<br>    print(f&quot;Title: {title}\nClassification: {classification}\n&quot;)</pre><h3>Further Improving Performance with Chain of Thought (CoT)</h3><p>To enhance content moderation capabilities, “chain-of-thought” (CoT) prompting encourages the language model to break down its reasoning process into a step-by-step chain of thoughts rather than just providing the final output.</p><h4>What is Chain of Thought (CoT)?</h4><p>Chain of Thought prompting helps the model think through the problem step-by-step, making its reasoning process more transparent and reliable.</p><p>So we take a TASK -&gt; and break it down into TASK 1 -&gt; TASK 2 -&gt; So on</p><p>For this case: We can take this single task :</p><pre>Based on the guidelines above, classify this text as either ALLOW or BLOCK. <br>Return nothing else.</pre><p>And Convert it into a series of actions like :</p><pre>First, inside of &lt;thinking&gt; tags, identify any potentially concerning aspects <br>of the post based on the guidelines below and consider whether those <br>aspects are serious enough to block the post or not. <br><br>Finally, classify this text as either ALLOW or BLOCK inside &lt;output&gt; tags. <br>Return nothing else.<br><br>Given those instructions, here is the post to categorize:</pre><h4>Example of CoT Prompt</h4><p>Here’s how you can modify your prompt to use CoT:</p><pre>cot_prompt = &#39;&#39;&#39;You are a content moderation expert tasked with categorizing <br>user-generated text based on the following guidelines:<br><br>BLOCK CATEGORY:<br>- Content that is not related to rollercoasters, theme parks, or the amusement industry<br>- Explicit violence, hate speech, or illegal activities<br>- Spam, advertisements, or self-promotion<br><br>ALLOW CATEGORY:<br>- Discussions about rollercoaster designs, ride experiences, and park reviews<br>- Sharing news, rumors, or updates about new rollercoaster projects<br>- Respectful debates about the best rollercoasters, parks, or ride manufacturers<br>- Some mild profanity or crude language, as long as it is not directed at individuals<br><br>First, inside of &lt;thinking&gt; tags, identify any potentially concerning aspects <br>of the post based on the guidelines below and consider whether those <br>aspects are serious enough to block the post or not. <br><br>Finally, classify this text as either ALLOW or BLOCK inside &lt;output&gt; tags. <br>Return nothing else.<br><br>Given those instructions, here is the post to categorize:<br><br>&lt;user_post&gt;{user_post}&lt;/user_post&gt;&#39;&#39;&#39;<br><br>post_titles = [<br>    &quot;Top 10 Wildest Inversions on Steel Coasters&quot;,<br>    &quot;My Review of the New RMC Raptor Coaster at Cedar Point&quot;,<br>    &quot;Best Places to Buy Cheap Hiking Gear&quot;,<br>    &quot;Rumor: Is Six Flags Planning a Giga Coaster for 2025?&quot;,<br>    &quot;My Thoughts on the Latest Marvel Movie&quot;,<br>]<br><br>for title in post_titles:<br>    classification = moderate_text(title, rollercoaster_guidelines)<br>    print(f&quot;Title: {title}\nClassification: {classification}\n&quot;)</pre><h3>Conclusion</h3><p>By using the Groq API and leveraging few-shot prompting and chain-of-thought reasoning, you can build a sophisticated and customizable content moderation filter.</p><h4>Key Takeaways</h4><ul><li>Understand LLMs: Learn what LLMs are and their capabilities.</li><li>Practical Applications: See real-world examples of content moderation.</li><li>Hands-On Practice: Follow step-by-step instructions to build and customize your own content moderation filter.</li></ul><h4>Next Steps</h4><p>I would suggest you explore more about LLMs and advanced prompting techniques. Experiment with different use cases like chatbots or recommendation systems. Engage with online forums and communities to learn from others and share your projects or reach out to me for ideas !</p><p><strong>Additional resources:</strong></p><ul><li>Groq API Documentation — <a href="https://docs.api.groq.com/index.html">https://docs.api.groq.com/index.html</a></li><li>Beginner’s Guide to APIs — <a href="https://blog.postman.com/understanding-api-basics-beginners/">https://blog.postman.com/understanding-api-basics-beginners/</a></li><li>Chain of Thought Prompting — <a href="https://www.promptingguide.ai/">https://www.promptingguide.ai/</a></li></ul><blockquote>Thanks for reading! If you found this article useful, please leave a comment or a clap.</blockquote><blockquote>Follow me to stay updated on my latest articles!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f3bad7c0af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents Are All You Need ? Hands-on guide to creating a better code-solving AI Agent with AutoGen]]></title>
            <link>https://deveshsurve.medium.com/ai-agents-are-all-you-need-hands-on-guide-to-creating-a-better-code-solving-ai-agent-with-autogen-18cb8abec53e?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/18cb8abec53e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Sat, 18 May 2024 14:00:38 GMT</pubDate>
            <atom:updated>2024-05-18T14:46:43.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Agents Are All You Need ? Hands-on guide to creating a better code-solving AI Agent with AutoGen</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qIvqjInt73EcwQBM" /></figure><h3>Introduction</h3><p>Hey there! So Lately, there’s been a lot of buzz around AI agents. Intrigued by the hype, I did some reading and stumbled upon AutoGen, a great library for building AI agents. But what exactly are AI agents, and why do they matter? Let’s dive into it.</p><p>LLMs have been around for a few years now, and they are rapidly evolving towards AI Agents and Agentic workflows. Don’t get me wrong, LLMs are great, but they are still not efficient at automating the stuff on their own. LLMs combined with other tools are a really efficient way to utilize the general intelligence LLMs possess, by consuming massive amounts of language data. AI agents are software entities that can perform tasks autonomously, interacting with their environment to make decisions. They are revolutionizing how we approach problems, from customer service chatbots to complex data analysis. Today, I’m excited to show you how to build a simple AI agent using AutoGen.</p><p>Ready? Let’s go!</p><h3>Why AI Agents Matter</h3><p>AI agents bring several benefits to the table:</p><p>Automation: They handle repetitive tasks without human intervention.<br>Efficiency: They process data and perform tasks faster than humans.<br>Scalability: They can operate 24/7, providing services without downtime.<br>Intelligence: They learn and improve from interactions, getting better over time.<br>Given these advantages, AI agents are being adopted across various industries, from healthcare to finance.</p><p>Building a Simple AI Agent with AutoGen<br>Let’s get hands-on and build a basic AI agent using AutoGen. For this demonstration, we’ll solve the “Distribute Coins in a binary tree” problem from LeetCode. This problem is a classic in coding interviews, where you find two numbers in an array that add up to a target.</p><p><strong>Colab Link</strong> — <a href="https://colab.research.google.com/drive/1dbP9XP-_yyAWEPmFqdIzvcn5XU6rlnVk?usp=sharing">https://colab.research.google.com/drive/1dbP9XP-_yyAWEPmFqdIzvcn5XU6rlnVk?usp=sharing</a></p><h3>Step 1: Install AutoGen</h3><p>First, we need to install the AutoGen library. Run the following command in your environment:</p><pre>!pip install pyautogen -q --progress-bar off</pre><h3>Step 2: Set Up Your Environment</h3><p>I’m using Google Colab for this demonstration. Here’s how to set up your environment and load your OpenAI API key securely:</p><pre>import os<br>import autogen<br>from google.colab import userdata<br><br># Load your OpenAI API key<br>userdata.get(&#39;OPENAI_API_KEY&#39;)<br><br>llm_config = {<br>    &quot;config_list&quot;: [{&quot;model&quot;: &quot;gpt-3.5-turbo&quot;, &quot;api_key&quot;: userdata.get(&#39;OPENAI_API_KEY&#39;)}],<br>    &quot;cache_seed&quot;: 0,<br>    &quot;temperature&quot;: 0,<br>}</pre><h3>Step 3: Define the Problem</h3><p>We’ll use the a LC Medium “Distribute Coins in a binary tree” problem from LeetCode.</p><pre>LEETCODE_QUESTION = &quot;&quot;&quot;<br>Title : Distribute Coins in a binary tree<br><br>You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.<br><br>In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.<br><br>Return the minimum number of moves required to make every node have exactly one coin.<br><br> <br><br>Example 1:<br><br><br>Input: root = [3,0,0]<br>Output: 2<br>Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.<br>Example 2:<br><br><br>Input: root = [0,3,0]<br>Output: 3<br>Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.<br><br>Follow-up: Can you come up with an algorithm that has a better time complexity?<br>&quot;&quot;&quot;</pre><h3>Step 4: Set Up the Agents</h3><p>AutoGen uses two types of agents: the AssistantAgent and the UserProxyAgent. The AssistantAgent suggests code solutions, while the UserProxyAgent executes the code and checks if it works correctly.</p><pre>SYSTEM_MESSAGE = &quot;&quot;&quot;You are a helpful AI assistant. Solve tasks using your coding and language skills...&quot;&quot;&quot;<br><br>assistant = autogen.AssistantAgent(<br>    name=&quot;assistant&quot;,<br>    llm_config=llm_config,<br>    system_message=SYSTEM_MESSAGE<br>)<br><br>user_proxy = autogen.UserProxyAgent(<br>    name=&quot;user_proxy&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    max_consecutive_auto_reply=4,<br>    is_termination_msg=lambda x: x.get(&quot;content&quot;, &quot;&quot;).rstrip().endswith(&quot;TERMINATE&quot;),<br>    code_execution_config={<br>        &quot;work_dir&quot;: &quot;coding&quot;,<br>        &quot;use_docker&quot;: False,<br>    },<br>)</pre><p>The human_input_mode is set to &quot;NEVER&quot; because we don’t plan to provide any input ourselves, and max_consecutive_auto_reply limits the conversation turns.</p><h3>Step 5: Initiate the Conversation</h3><p>We’ll start the conversation by sending a message from our UserProxyAgent to our Assistant.</p><pre>with autogen.Cache.disk(cache_seed=7) as cache:<br>  chat_res = user_proxy.initiate_chat(<br>      assistant,<br>      message=&quot;&quot;&quot;Solve the following LeetCode problem and also comment on its time and space complexity:\n\n&quot;&quot;&quot; + LEETCODE_QUESTION<br>  )</pre><h4>Output</h4><p>Here’s a snippet of the conversation that follows:</p><p>User Proxy: Solve the following LeetCode problem and also comment on its time and space complexity…</p><p>Assistant: To solve this problem efficiently, we can use a dictionary to store the elements we have seen so far along with their indices. Here’s the Python code…</p><pre>user_proxy (to assistant):<br><br>Solve the following LeetCode problem and also comment on its time and space complexity:<br><br><br>Title : Distribute Coins in a binary tree<br><br>You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.<br><br>In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.<br><br>Return the minimum number of moves required to make every node have exactly one coin.<br><br> <br><br>Example 1:<br><br><br>Input: root = [3,0,0]<br>Output: 2<br>Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.<br>Example 2:<br><br><br>Input: root = [0,3,0]<br>Output: 3<br>Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.<br><br>Follow-up: Can you come up with an algorithm that has a better time complexity?<br><br><br>--------------------------------------------------------------------------------<br>assistant (to user_proxy):<br><br>To solve this problem, we can perform a depth-first search (DFS) traversal of the binary tree and calculate the excess coins at each node. The excess coins at a node can be calculated as the sum of coins at the node and the excess coins from its left and right children, minus 1 (since the node itself should have 1 coin).<br><br>Here is the Python code to solve the problem:<br><br>```python<br>class Solution:<br>    def distributeCoins(self, root: TreeNode) -&gt; int:<br>        self.moves = 0<br>        <br>        def dfs(node):<br>            if not node:<br>                return 0<br>            <br>            left_excess = dfs(node.left)<br>            right_excess = dfs(node.right)<br>            <br>            self.moves += abs(left_excess) + abs(right_excess)<br>            <br>            return node.val + left_excess + right_excess - 1<br>        <br>        dfs(root)<br>        <br>        return self.moves<br>```<br><br>Time complexity analysis:<br>- The DFS traversal visits each node once, so the time complexity is O(n), where n is the number of nodes in the binary tree.<br><br>Space complexity analysis:<br>- The space complexity is O(h), where h is the height of the binary tree. This is due to the recursive calls in the DFS traversal. In the worst case, the space complexity can be O(n) for a skewed tree.<br><br>To improve the time complexity, we can modify the algorithm to avoid redundant calculations and achieve a linear time complexity. This can be done by returning both the excess coins and the number of moves from the DFS function. This way, we can eliminate the need to traverse the tree twice.<br><br>--------------------------------------------------------------------------------<br><br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; EXECUTING CODE BLOCK 0 (inferred language is python)...<br>user_proxy (to assistant):<br><br>exitcode: 1 (execution failed)<br>Code output: <br>Traceback (most recent call last):<br>  File &quot;&quot;, line 1, in &lt;module&gt;<br>    class Solution:<br>  File &quot;&quot;, line 2, in Solution<br>    def distributeCoins(self, root: TreeNode) -&gt; int:<br>NameError: name &#39;TreeNode&#39; is not defined<br><br></pre><p>Notice how the UserProxyAgent got an error. And it calls back the other agent for its solution.</p><pre>--------------------------------------------------------------------------------<br>assistant (to user_proxy):<br><br>It seems like the code snippet I provided is missing the definition of the `TreeNode` class. Here is an updated version of the code that includes the definition of the `TreeNode` class:<br><br>```python<br># Definition for a binary tree node.<br>class TreeNode:<br>    def __init__(self, val=0, left=None, right=None):<br>        self.val = val<br>        self.left = left<br>        self.right = right<br><br>class Solution:<br>    def distributeCoins(self, root: TreeNode) -&gt; int:<br>        self.moves = 0<br>        <br>        def dfs(node):<br>            if not node:<br>                return 0<br>            <br>            left_excess = dfs(node.left)<br>            right_excess = dfs(node.right)<br>            <br>            self.moves += abs(left_excess) + abs(right_excess)<br>            <br>            return node.val + left_excess + right_excess - 1<br>        <br>        dfs(root)<br>        <br>        return self.moves<br>```<br><br>You can now use this updated code to solve the LeetCode problem &quot;Distribute Coins in a binary tree&quot;.<br><br>--------------------------------------------------------------------------------<br><br>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; EXECUTING CODE BLOCK 0 (inferred language is python)...<br>user_proxy (to assistant):<br><br>exitcode: 0 (execution succeeded)<br>Code output: <br><br><br>--------------------------------------------------------------------------------<br>assistant (to user_proxy):<br><br>Great! I&#39;m glad to hear that the code executed successfully. If you have any more questions or need further assistance, feel free to ask!<br><br>--------------------------------------------------------------------------------<br>user_proxy (to assistant):<br><br><br><br>--------------------------------------------------------------------------------<br>assistant (to user_proxy):<br><br>If you have any more questions or need help with anything else, feel free to ask. I&#39;m here to help!<br><br>--------------------------------------------------------------------------------<br>user_proxy (to assistant):<br><br><br><br>--------------------------------------------------------------------------------<br>assistant (to user_proxy):<br><br>If you have any questions in the future or need assistance, don&#39;t hesitate to ask. Have a great day!<br><br>--------------------------------------------------------------------------------</pre><h3>Conclusion</h3><p>By using AutoGen’s conversable agents, we:</p><ul><li>Automatically verified that the Python code suggested by the LLM works.</li><li>Created a framework where the LLM can respond to syntax or logical errors by reading the console output.</li></ul><blockquote>Thanks for reading! If you found this article useful, please leave a comment or a clap.</blockquote><blockquote>Follow me to stay updated on my latest articles!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18cb8abec53e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to serve an LLM as a Streamlit app on Google Colab — Step by Step Guide]]></title>
            <link>https://deveshsurve.medium.com/how-to-serve-an-llm-as-a-streamlit-app-on-google-colab-step-by-step-guide-b6d9dc45427d?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d9dc45427d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Thu, 09 May 2024 19:07:07 GMT</pubDate>
            <atom:updated>2024-05-09T19:07:07.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to serve an LLM as a Streamlit app on Google Colab</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XundXyIO2yqH42yp" /></figure><h3>Introduction</h3><p>So, a while back, I was working on a college project using an LLM model. Now, as we know platforms like Google Colab and Kaggle are gems for data science enthusiasts. Why? Because they offer free GPU access — although, yes, it’s somewhat limited. But that’s enough to get your feet wet!</p><p>During my project, I realized I needed to make an interface for my model. I chose Streamlit, a popular choice for quick and easy web apps. The catch? I wanted to share my work with others, and that meant deploying it online. Here’s where it gets tricky — I was using Colab, not my local machine.</p><p>I scoured the internet for a straightforward guide on deploying from Colab but found none. So, I decided to write one myself, ensuring it’s simple to follow, with no complex steps.</p><p>Let me take you through how you can do it too, using GPT-2 for text data.</p><h3>Step-by-Step Guide to Deploying Your Streamlit App</h3><h4>Step 1: Install Streamlit &amp; Hugging Face Transformers</h4><p>Before you can deploy your app, you need the right tools. First, ensure that Streamlit is installed in your Colab environment. Streamlit is an open-source app framework that is excellent for turning data scripts into shareable web apps. Alongside, if you’re working with language models like GPT or Llama-3, you’ll need libraries from Hugging Face’s transformers. Here’s how you install both:</p><pre>!pip install streamlit<br>!pip install transformers</pre><p>Run these commands in your Google Colab notebook to get everything set up.</p><h4>Step 2: Prepare Your App for Deployment</h4><p>Now that you have the necessary tools, start preparing your Streamlit app. This involves writing a script that Streamlit will use to run your app. Here’s a simple template you can start with:</p><pre>%%writefile app.py<br>import streamlit as st<br>from transformers import pipeline<br>import time<br><br># Load your model (with caching to improve performance)<br>@st.cache_resource()<br>def load_model():<br>    model = pipeline(&#39;text-generation&#39;, model=&#39;gpt2&#39;)<br>    return model<br><br>model = load_model()<br><br># Set up your web app<br>st.title(&#39;GPT-2 Story Completer&#39;)<br>st.header(&#39;Enter text to complete:&#39;)<br><br>user_input = st.text_area(&#39;Write something to activate the AI:&#39;, height=200)<br>max_length = st.slider(&quot;Select max story length:&quot;, min_value=50, max_value=200, value=100, step=10)<br>num_sequences = st.selectbox(&quot;Select number of stories to generate:&quot;, options=[1, 2, 3], index=0)<br><br>if st.button(&#39;Generate Story&#39;):<br>    with st.spinner(&#39;Generating Story...&#39;):<br>        response = model(user_input, max_length=max_length, num_return_sequences=num_sequences)<br>        for i, summary in enumerate(response):<br>            st.write(f&#39;**Story {i+1}:**&#39;)<br>            st.write(summary[&#39;generated_text&#39;])<br>            st.markdown(&quot;---&quot;)<br><br>st.sidebar.markdown(&quot;## Guide&quot;)<br>st.sidebar.info(&quot;This tool uses GPT-2 to generate a story of your provided text. Adjust the sliders to change the story length and number of stories generated. The model is optimized for short to medium length paragraphs.&quot;)<br>st.sidebar.markdown(&quot;### Examples&quot;)<br>st.sidebar.write(&quot;1. Paste a beginning to see how the AI completes it.&quot;)<br>st.sidebar.write(&quot;2. Try different settings to see how the story changes.&quot;)Note : You may need to add HF_TOKEN in Colab Secrets depending on the LLM. You can access your tokens from https://huggingface.co/settings/tokens </pre><p>This script sets up a basic interface where users can input text, and the model generates a response. Customize this to fit the specifics of your model and what you want your app to do.</p><h4>Step 3: Deploy the App using LocalTunnel</h4><p>Since Google Colab does not allow direct hosting, we’ll use localtunnel to expose your local server to the internet. LocalTunnel allows you to easily share your locally running web server:</p><ol><li><strong>Install LocalTunnel</strong>: Ensure you have Node.js installed ( which colab &amp; kaggle would have by default ), then install localtunnel globally using npm:</li></ol><pre>!npm install -g localtunnel</pre><p>2. <strong>Fetch Your Public IP</strong>: Use the curl command to retrieve your public IP address. We will need this as password to localtunnel.</p><pre># Your public ip is the password to the localtunnel<br>!curl ipv4.icanhazip.com</pre><p>This should an output like :</p><pre>10.111.101.111 # This will be as per your code not the same</pre><p>3. <strong>Expose Your App:</strong> Run your streamlit app</p><pre>!streamlit run app.py &amp;&gt;./logs.txt &amp; npx localtunnel --port 8501</pre><p>This should give an output like this</p><pre>npx: installed 22 in 2.117s<br>your url is: https://rich-rockets-admire.loca.lt</pre><p>Once, you open this. You should get a window like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOwEsPYkDY14Mfk5e5XARg.png" /></figure><p>In Tunnel Password, enter the ip you recieved from above. And you should get something like this !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXn7hm_3Dx0lAWFeNTooyw.png" /></figure><p>Here’s the notebook URL — <a href="https://colab.research.google.com/drive/1Tnif2N5zbsSkIogsNH2BiR4RxvLFnzgC?usp=sharing">https://colab.research.google.com/drive/1Tnif2N5zbsSkIogsNH2BiR4RxvLFnzgC?usp=sharing</a></p><h3>Conclusion</h3><p>There you have it! A fun and accessible way to build and serve your very own LLM-powered image webapp. This link could be now shared with anyone and they can view your work. Thank you so much for reading.</p><p>Now I usually don’t ask for these but, if you read all the way here and you found this article useful, I would really appreciate a comment or a clap!</p><p>Please follow if this type of content interests you !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d9dc45427d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Dall-E ? Step by Step guide on Latent Diffusion in Python]]></title>
            <link>https://deveshsurve.medium.com/make-your-own-dall-e-step-by-step-guide-on-latent-diffusion-in-python-2852925709e8?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2852925709e8</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 15:24:36 GMT</pubDate>
            <atom:updated>2024-04-19T23:04:26.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>Make your own Dall-E ? Step by Step guide on Latent Diffusion in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRtYrH65-worBSeLJQcf3g.jpeg" /></figure><h3>Introduction</h3><p>Have you ever used one of those image-making tools like DALL-E? Ever wonder how these magic machines churn out pictures from a few typed words? Well, I did, and let me tell you, it’s a fascinating process called <strong>Latent diffusion</strong>, a real neat trick in the world of AI.</p><p>It took a while to understand all the complex elements that make up the architecture but unfortunately, I found it way too technical.</p><p>With no good explanations available online to explain all these steps in simple words, I decided to make one myself. So no matter if you’re a beginner in AI or a pro, I really hope you get some value out of this.</p><p>Without further ado, let’s get started !</p><h3>From Noise to … Art ? Diving Into the World of Latent Diffusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FVsrjUTGumoW_3OT.jpg" /></figure><p>So what is this latent diffusion we are talking about ?</p><p>Picture latent diffusion like a highly skilled artist who decides to work smarter, not harder. Instead of painting directly on a huge canvas, this artist sketches on a smaller, more manageable pad, capturing all the essential elements before scaling it up. That’s what latent diffusion does. It operates not on the raw, pixel-packed images but within a compressed, easier-to-handle latent space, making the whole process quicker and less resource-intensive.</p><p>Okay, so the obvious question now becomes .. What is latent diffusion made up to do this rigmarole ?</p><h4>Meet the Team Behind the Magic</h4><p>Now, If you dive into the technical terms, <em>I’ll have explain you that Latent diffusion is made up </em><strong><em>CLIP</em></strong><em> (Contrastive Language–Image Pre-training), Variational Auto Encoder ( </em><strong><em>VAE</em></strong><em> ) and </em><strong><em>UNet</em></strong><em> ( Convolutional Neural Network ) and I’m pretty sure by the time I finish this sentence you’ll probably be fast asleep ..</em></p><p>So let’s try another route. Imagine you’re putting together a superhero team where each member has a unique role that is crucial for the mission.</p><h4><strong>CLIP: The Mind Reader</strong></h4><p>Think of CLIP as the team’s mind reader. It looks at a line of text — your wish for what the image should depict — and understands it like a pro. It’s like a doctor who listens to your symptoms and figures out exactly what you need. CLIP takes these insights and makes sure the image reflects them, acting as a bridge between words and pictures.</p><h4>VAE: The Efficient Packer</h4><p>Next up is the VAE, or Variational Autoencoder, think of it as your packing expert when you’re going on a trip. It knows just how to fold everything neatly so it fits into a smaller suitcase. In our case, the VAE compresses images into a more compact form, a latent space, ensuring all the important details are retained but in a way that’s easier to handle and process.</p><h4>UNet: The Refiner</h4><p>Then there’s UNet, the detail-oriented refiner of the group. It’s like having a meticulous editor who goes through a draft, correcting little errors and polishing it until it’s just right. In the world of latent diffusion, UNet works step-by-step to reduce noise and enhance the image’s quality, refining the visual until it’s a masterpiece.</p><p>Visualize all of them working together like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*e-bndb-RoDI7y7nl6jp_Gw.png" /></figure><ol><li>CLIP: The Insight Gatherer : First, CLIP takes the stage. It’s like the group’s scout, venturing out to understand the lay of the land — or in our case, the text prompt you feed it. It reads your description, like “a sunny day at the beach,” and converts this textual input into a set of digital insights, known as embeddings. These embeddings are rich with the context and nuances of your words, packed into a format that the rest of the team can work with.</li><li>VAE: The Shaper : Enter the VAE, our efficient packer, who takes these insights and transforms them into a more manageable form. It compresses the vast world of possible images into a compact latent space — a smaller, denser representation of potential images. This step is crucial because it reduces the complexity and size of the data, making the next steps faster and more focused.</li><li>UNet: The Sculptor : Finally, UNet steps up. This part of the process is akin to a sculptor refining a block of marble. UNet takes the compressed image from the VAE and begins the meticulous task of denoising. It incrementally adjusts and enhances the image, step by step, removing imperfections and adding details. With each iteration, the image becomes clearer and more detailed, moving closer to the final masterpiece that perfectly matches your initial prompt.</li></ol><h4>Understood the theory ? Ready to make one of your own ?</h4><h3>Well then, what are you waiting for ? Let’s get started.</h3><p>Here’s the complete Kaggle notebook for those who want to try :</p><p><a href="https://www.kaggle.com/code/deveshsurve/step-by-step-guide-to-implement-latent-diffusion">https://www.kaggle.com/code/deveshsurve/step-by-step-guide-to-implement-latent-diffusion</a></p><p>Step by Step Implementation</p><p>We start with installing our required libraries not available by default on kaggle</p><pre>!pip install diffusers</pre><p>Importing Libraries</p><pre>import torch, logging<br><br>## disable warnings<br>logging.disable(logging.WARNING)  <br><br>## Imaging  library<br>from PIL import Image<br>from torchvision import transforms as tfms<br><br>## Basic libraries<br>import numpy as np<br>from tqdm.auto import tqdm<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>from IPython.display import display<br>import shutil<br>import os<br><br>## For video display<br>from IPython.display import HTML<br>from base64 import b64encode<br><br><br>## Import the CLIP artifacts <br>from transformers import CLIPTextModel, CLIPTokenizer<br>from diffusers import AutoencoderKL, UNet2DConditionModel, LMSDiscreteScheduler<br>from IPython.display import display, clear_output<br>import os<br></pre><p>Next, setup GPU support if you can</p><pre>device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)</pre><p>Now, let’s define our helper functions <em>( I’ve added line by line details on kaggle notebook )</em></p><pre>## Helper functions<br>def load_image(p):<br>    &#39;&#39;&#39;<br>    Function to load images from a defined path<br>    &#39;&#39;&#39;<br>    return Image.open(p).convert(&#39;RGB&#39;).resize((512,512))<br><br>def pil_to_latents(image):<br>    &#39;&#39;&#39;<br>    Function to convert image to latents<br>    &#39;&#39;&#39;<br>    init_image = tfms.ToTensor()(image).unsqueeze(0) * 2.0 - 1.0<br>    init_image = init_image.to(device=&quot;cuda&quot;, dtype=torch.float16) <br>    init_latent_dist = vae.encode(init_image).latent_dist.sample() * 0.18215<br>    return init_latent_dist<br><br>def latents_to_pil(latents):<br>    &#39;&#39;&#39;<br>    Function to convert latents to images<br>    &#39;&#39;&#39;<br>    latents = (1 / 0.18215) * latents<br>    with torch.no_grad():<br>        image = vae.decode(latents).sample<br>    image = (image / 2 + 0.5).clamp(0, 1)<br>    image = image.detach().cpu().permute(0, 2, 3, 1).numpy()<br>    images = (image * 255).round().astype(&quot;uint8&quot;)<br>    pil_images = [Image.fromarray(image) for image in images]<br>    return pil_images<br><br><br>def text_enc(prompts, maxlen=None):<br>    &#39;&#39;&#39;<br>    A function to take a texual promt and convert it into embeddings<br>    &#39;&#39;&#39;<br>    if maxlen is None: maxlen = tokenizer.model_max_length<br>    inp = tokenizer(prompts, padding=&quot;max_length&quot;, max_length=maxlen, truncation=True, return_tensors=&quot;pt&quot;) <br>    return text_encoder(inp.input_ids.to(&quot;cuda&quot;))[0].half()<br><br></pre><p>Now, let’s go for the Actual Diffusion Process. A thing to know here is that VAE, UNet, CLIP are Pretrained models. We could theoretically make one of our own, buuuut it will take a ginormously long time.</p><p>So, we just use pretrained ones.</p><pre><br>## Initiating tokenizer and encoder.<br>tokenizer = CLIPTokenizer.from_pretrained(&quot;openai/clip-vit-large-patch14&quot;, torch_dtype=torch.float16)<br>text_encoder = CLIPTextModel.from_pretrained(&quot;openai/clip-vit-large-patch14&quot;, torch_dtype=torch.float16).to(&quot;cuda&quot;)<br><br>## Initiating the VAE<br>vae = AutoencoderKL.from_pretrained(&quot;CompVis/stable-diffusion-v1-4&quot;, subfolder=&quot;vae&quot;, torch_dtype=torch.float16).to(&quot;cuda&quot;)<br><br>## Initializing a scheduler and Setting number of sampling steps<br>scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule=&quot;scaled_linear&quot;, num_train_timesteps=1000)<br>scheduler.set_timesteps(50)<br><br>## Initializing the U-Net model<br>unet = UNet2DConditionModel.from_pretrained(&quot;CompVis/stable-diffusion-v1-4&quot;, subfolder=&quot;unet&quot;, torch_dtype=torch.float16).to(&quot;cuda&quot;)</pre><p>Now comes our loop which will take the noise and turn it into art</p><pre>def prompt_2_img(prompts, g=7.5, seed=100, steps=70, dim=512, save_int=True):<br>    &quot;&quot;&quot;<br>    Diffusion process to convert prompt to image<br>    &quot;&quot;&quot;<br>    <br>    # Defining batch size<br>    bs = len(prompts) <br>    <br>    # Converting textual prompts to embedding<br>    text = text_enc(prompts) <br>    <br>    # Adding an unconditional prompt , helps in the generation process<br>    uncond =  text_enc([&quot;&quot;] * bs, text.shape[1])<br>    emb = torch.cat([uncond, text])<br>    <br>    # Setting the seed<br>    if seed: torch.manual_seed(seed)<br>    <br>    # Initiating random noise<br>    latents = torch.randn((bs, unet.in_channels, dim//8, dim//8))<br>    <br>    # Setting number of steps in scheduler<br>    scheduler.set_timesteps(steps)<br>    <br>    # Adding noise to the latents <br>    latents = latents.to(&quot;cuda&quot;).half() * scheduler.init_noise_sigma<br><br>    print(&quot;Processing text prompts:&quot;, prompts)<br>    # Just before the loop starts:<br>    print(&quot;Visualizing initial latents...&quot;)<br>    latents_norm = torch.norm(latents.view(latents.shape[0], -1), dim=1).mean().item()<br>    print(f&quot;Initial Latents Norm: {latents_norm}&quot;)<br><br>    # Iterating through defined steps<br>    for i,ts in enumerate(tqdm(scheduler.timesteps)):<br>        # We need to scale the i/p latents to match the variance<br>        inp = scheduler.scale_model_input(torch.cat([latents] * 2), ts)<br>        <br>        # Predicting noise residual using U-Net<br>        with torch.no_grad(): u,t = unet(inp, ts, encoder_hidden_states=emb).sample.chunk(2)<br>            <br>        # Performing Guidance<br>        pred = u + g*(t-u)<br>        <br>        # Conditioning  the latents<br>        latents = scheduler.step(pred, ts, latents).prev_sample<br>        <br>        # Inside your loop, after `latents` have been updated:<br>        latents_norm = torch.norm(latents.view(latents.shape[0], -1), dim=1).mean().item()<br>        print(f&quot;Step {i+1}/{steps} Latents Norm: {latents_norm}&quot;)<br>        <br>        from IPython.display import display, clear_output<br>        if save_int and i%13==0: <br>            image_path = f&#39;steps2/la_{i:04d}.jpeg&#39;<br>            latents_to_pil(latents)[0].save(image_path)<br>            display(latents_to_pil(latents)[0])  # Display the new image<br><br>    return latents_to_pil(latents)</pre><p>And now, time for the magic</p><pre>images = prompt_2_img([“A dog wearing a hat”], save_int=True)<br>for img in images:display(img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ozEuFV9uheWkdebDJC_eA.png" /></figure><h3>Conclusion</h3><p>There you have it! A fun and accessible way to understand and build your very own AI-powered image generator. It’s like assembling a dream team of tech wizards, each playing their part to bring your creative visions to life. Why not give it a whirl and see what incredible images you can create?</p><p>Now I usually don’t ask for these but, if you read all the way here and you found this article useful, I would really appreciate a comment or a clap!</p><p>Please follow if this type of content interests you !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2852925709e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNNs : Understanding & Building them with a step by step guide]]></title>
            <link>https://deveshsurve.medium.com/cnns-understanding-building-them-with-a-step-by-step-guide-932c4c3e0531?source=rss-eceecdcfa17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/932c4c3e0531</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Devesh Surve]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 15:05:58 GMT</pubDate>
            <atom:updated>2024-02-01T15:05:58.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>CNNs : Understanding &amp; Building them with a step by step guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*RaR4wQ3MTzDujfvr8n33_Q.png" /></figure><p>Hey Everyone,</p><p>Here’s the topic for today: Not just understanding CNNs, but understanding AND building them. I’ve noticed a lot of resources either skate around the practical aspects or dive too deep into theory.</p><p>So, I’m here to offer a middle ground — a way to not only grasp what CNNs and their components are (think interview gold) but also to provide a step-by-step guide for personal projects. I wanted to understand every line of code I wrote, not just blindly follow instructions. With that said, let’s jump in.</p><p>Here’s a colab link to preview side by side :</p><p><a href="https://colab.research.google.com/drive/1jvB47zoz9c4_WbcXbpjGjL7M36_qGHmG?usp=sharing">Google Colaboratory</a></p><h3><strong>Table of Contents :</strong></h3><ol><li>The CNN Model : An Overview</li><li>Problem with building CNNs : Which Layer does what and how to add and how many ?</li><li>Explaining with an example : CIFAR-10</li><li>Explaining Convolution Layer ?</li><li>Why do we Flatten ?</li><li>So what are Dense Layers again ?</li><li>Let’s build a Baseline Model</li><li>What’s a Pooling layer ?</li><li>What are activation functions?</li><li>What’s Batch Normalization?</li><li>Why drop out/s ?</li><li>What are optimizers &amp; learning rates</li><li>Handling Epochs, Batches &amp; Early Stopping.</li></ol><h3><strong>1. The CNN Model: An Overview</strong></h3><p>Convolutional Neural Networks (CNNs) are the workhorses of image recognition, powering everything from facial recognition to self-driving cars. At their essence, CNNs learn to recognize patterns in images — such as lines, shapes, and textures — automatically identifying features that define an object.</p><p>But here’s the kicker: building a CNN is like stacking Legos. You have different blocks (layers) each with a role, and how you stack them affects what the model sees and learns. It’s not about adding layers until it works; it’s about understanding what each layer does and using them to capture the essence of the images.</p><p>As we proceed, we’ll decode these layers, from the ones spotting edges in an image to those making sense of the overall picture. Ready to build your own CNN that sees the world as we do? Let’s get our hands dirty.</p><h3><strong>2. Problem with Building CNNs: Which Layer Does What and How to Add and Reduce</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SJhH44XEBZpiAsCA.jpg" /></figure><p>Building a CNN can sometimes feel like being a chef in a gourmet kitchen. You have all these ingredients (layers), but knowing how much of each to use and in what order can make the difference between a Michelin-star dish and a kitchen nightmare. The main challenge? Understanding the role of each layer and how it contributes to the overall learning process.</p><p>Let’s break it down:</p><ul><li><strong>Convolutional Layers</strong>: Think of these as your sous-chefs, specialized in chopping and preparing the ingredients. They’re the ones identifying patterns in the image, like edges and textures. But just as having too many sous-chefs can clutter the kitchen, stacking too many convolutional layers without purpose can make your model complex and slow without adding value.</li><li><strong>Pooling Layers</strong>: These are your pot washers, condensing and simplifying what the sous-chefs provide. They reduce the dimensionality of the data, making the model more manageable and focusing on the essential features. However, overdoing it can wash away too much information, leaving your model with too little to learn from.</li><li><strong>Dense (Fully Connected) Layers</strong>: Consider these the head chefs, making the final decisions. They take the simplified, processed inputs and decide what the image represents. But as in any kitchen, too few head chefs might mean not enough insight, while too many can lead to confusion and inefficiency.</li></ul><p>The trick to a well-functioning CNN kitchen? Balance. You need just the right number of each type of layer to work harmoniously together, ensuring your model is efficient, accurate, and capable of learning from the data provided.</p><p>In the next sections, we’ll dive deeper into each type of layer, starting with convolutional layers, and discuss how to strike the perfect balance for your CNN masterpiece.</p><h3>3. Explaining Convolutional Layers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*4Wkmi-lyPqhfLgQz.png" /></figure><p>Imagine you’re looking at a beautiful mosaic, each tile representing a part of a bigger picture. Convolutional layers in a CNN work similarly, examining small pieces of an image to understand the larger scene. These layers are the detectives of the network, using their filters (or kernels) to search for clues in the form of patterns, textures, and shapes across the image.</p><p>Here’s how they do it:</p><ul><li><strong>Filters:</strong> Each filter in a convolutional layer is like a magnifying glass, focusing on specific features like edges or color gradients. As the filter slides over the image (a process called convolution), it creates a map of where those features occur. Think of it as highlighting all the places in a book where your favorite character appears.</li><li><strong>Feature Maps:</strong> The result of applying a filter over the image is a feature map. If our image is a complex scene, the feature map simplifies it into a canvas that emphasizes the detected features, making it easier for the network to understand.</li></ul><p>But why are these layers so crucial? Because they allow the network to see the world in a hierarchical way. The first convolutional layer might catch simple patterns like lines and edges. Layers deeper in the network combine these simple patterns to recognize more complex shapes and eventually whole objects.</p><p>The magic of convolutional layers lies in their ability to learn these filters automatically from the training data. Instead of telling the network to look for specific features, it learns from examples, adjusting its filters to improve accuracy over time.</p><p>By stacking convolutional layers, we build a deep understanding of the visual world, layer by layer, from simple to complex. This is what makes CNNs so powerful for tasks like image recognition.</p><h3><strong>4. Why Do We Flatten?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*Ewh5kxEdcT4ikc-U.png" /></figure><p>After our network has combed through the image with convolutional and pooling layers, identifying and condensing the features, we’re left with a high-level understanding of the visual content. This understanding, however, is still in the form of multi-dimensional arrays (the feature maps). Before we can make a final decision (classification), we need a way to process this information in a fully connected (dense) layer. That’s where flattening comes in.</p><p>Imagine you’ve just completed a jigsaw puzzle, and you need to store it away without losing the big picture. Flattening is like taking that puzzle, carefully aligning all the pieces in a single row so they can be analyzed sequentially. In technical terms, we convert the multi-dimensional array of features into a one-dimensional array.</p><p>This process is crucial because dense layers, which make the final decisions, expect input in a flat, one-dimensional format. By flattening the feature maps, we prepare the data for this last stage of processing, where the network combines all the learned features to make a classification (e.g., identifying the image as a cat, dog, etc.).</p><p>It’s a simple yet vital step, bridging the gap between the spatial hierarchy learned by convolutional layers and the classification logic of dense layers. Without flattening, the transition from recognizing patterns to making predictions wouldn’t be possible.</p><h3>5. So What Are Dense Layers?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*KLizsWLua7E4LB4-xhdyiA.png" /></figure><p>Once we’ve flattened our data, it’s time for the dense layers, also known as fully connected layers, to take the stage. These layers are the brain of our operation, where all the high-level reasoning happens. If convolutional layers are the detectives gathering clues and flattening is like laying out all the clues on a table, dense layers are the judges making the final verdict.</p><p>Dense layers work by taking all the inputs from the previous layer (now a flat, one-dimensional array) and determining the patterns that most strongly suggest a particular classification. Each neuron in a dense layer is connected to every input, which is why it’s called “fully connected.” These neurons then weigh the inputs based on their importance for making a correct prediction, essentially voting on what the image represents.</p><p><strong>Here’s the kicker:</strong> the power of dense layers comes from their ability to learn these weights through training. By adjusting these weights, the network gets better and better at making accurate predictions. It’s a bit like refining your recipe based on feedback until your dish is just right.</p><p><strong>But why are dense layers placed after convolutional and flattening steps?</strong></p><p>Because they require a global understanding of the image, which is only possible after the features have been identified, highlighted, and organized by the preceding layers. Dense layers synthesize all this information, making sense of the patterns to classify the image accurately.</p><p>In essence, dense layers are where all the learned features come together to make a coherent decision. Without them, our CNN would be like a detective gathering clues without ever solving the case.</p><h3>6. What’s a Pooling Layer?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*Ho6Ku1DKzWIKzcS1.jpg" /></figure><p>Pooling layers are the unsung heroes of CNNs, optimizing the network by reducing the dimensions of the feature maps without losing the essential information. Imagine you’re an artist tasked with creating a miniature version of a large painting. You’d want to preserve the painting’s essence, capturing the most important elements in a smaller space. That’s essentially what pooling layers do for CNNs.</p><p>There are two main types of pooling: max pooling and average pooling.</p><ul><li><strong>Max Pooling</strong> is like looking at small sections of the image and only keeping the brightest pixel in each section. This method ensures that the most prominent features are retained while reducing the size of the data being processed. It’s particularly effective at preserving the presence of features detected by the convolutional layers.</li><li><strong>Average Pooling</strong>, on the other hand, takes the average value of pixels in each section. This approach is smoother and less aggressive than max pooling, distributing the focus more evenly across features.</li></ul><p>But why do we need pooling? There are a few reasons:</p><ol><li><strong>Efficiency</strong>: By reducing the size of the data (downsampling), pooling layers make the network faster and reduce computational costs.</li><li><strong>Preventing Overfitting</strong>: Smaller data means there’s less risk of the model memorizing the training data too closely, helping it generalize better to unseen images.</li><li><strong>Feature Preservation</strong>: Pooling helps to make the detection of features in the input images more robust to changes in scale or orientation.</li></ol><p>In essence, pooling layers streamline the network’s learning process, ensuring that it focuses on the most salient features of the data while maintaining efficiency and robustness. They’re a key part of the balance between detail retention and computational efficiency in CNNs.</p><h3>7. What Are Activation Functions?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yeu2VBIr7tHCkygi.png" /></figure><p>Activation functions are the soul of neural networks, including CNNs. They decide whether a neuron should be activated or not, based on the weighted sum of its inputs. Think of each neuron in your network as a gatekeeper, and the activation function is the rule that tells the gatekeeper when to open the gate.</p><p><strong>Why are they important?</strong> Because without activation functions, our network would be a simple linear regression model, incapable of learning complex patterns in data. Activation functions introduce non-linearity into the network, allowing it to tackle problems as complicated as image recognition.</p><p>There are several types of activation functions, but let’s focus on a few commonly used in CNNs:</p><ul><li><strong>ReLU (Rectified Linear Unit)</strong>: This function is simple yet effective, turning all negative values to zero and keeping positive values as is. It’s like saying, “If the information is useful (positive), let it through; otherwise, block it.” ReLU is popular because it reduces training time and prevents the vanishing gradient problem.</li><li><strong>Softmax</strong>: Often used in the final layer of a classification network, the softmax function converts the output scores from neurons into probabilities by dividing the exponential of each output by the sum of all exponentials. This way, you get a probability distribution across classes, making it clear which class the model predicts.</li><li><strong>Sigmoid and Tanh</strong>: These functions were more common in the early days of neural networks. Sigmoid squashes the values between 0 and 1, making it useful for binary classification. Tanh, on the other hand, normalizes values between -1 and 1, offering a centered scaling. However, both can lead to the vanishing gradient problem, where gradients become too small for effective learning.</li></ul><p>Activation functions play a critical role in learning, determining the complexity and versatility of the model. By deciding which signals should pass through, they enable the network to make nuanced decisions based on the learned features from the input data.</p><h3>8. What’s Batch Normalization?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZa9fC99Dy57NUj6.jpeg" /></figure><p>Batch normalization is like the secret ingredient in a recipe that makes everything better. Introduced to address the issues of internal covariate shift (where the distribution of network inputs changes during training, making it harder to train models), batch normalization standardizes the inputs of each layer within the network. This means adjusting the inputs so they have a mean of 0 and a variance of 1, similar to how data is often pre-processed before training.</p><p>Why is this beneficial? Here are a few key reasons:</p><ul><li><strong>Faster Training</strong>: By normalizing the inputs across mini-batches, batch normalization allows the use of higher learning rates, speeding up the training process. It’s like greasing the wheels of your bike, so you can pedal faster without more effort.</li><li><strong>Reduced Overfitting</strong>: Batch normalization has a regularization effect, meaning it helps prevent the model from too closely fitting the noise in the training data. This is partly because the mini-batch statistics add a bit of noise to the signals within the network, making it more robust.</li><li><strong>Eases Initialization</strong>: Choosing the right initialization method for weights can be tricky. Batch normalization helps alleviate this problem by reducing the sensitivity of the network to the initial weights.</li></ul><p>In practice, batch normalization is applied after convolutional layers but before the activation function. This positioning ensures that the scaling effect of batch normalization is taken into account when the activation function is applied, leading to more stable and efficient training.</p><p>By stabilizing the learning process, batch normalization allows the network to learn more effectively, making it a popular choice in many CNN architectures.</p><h3>9. What Are Dropouts?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fzKUY6FMT5liIX75.png" /></figure><p>Imagine you’re working on a group project, and to ensure no one person becomes too crucial (and to prevent over-reliance on any single member), you randomly assign tasks to different people each time you meet. This is akin to what dropout does in a neural network. It randomly “drops out” a subset of neurons (i.e., temporarily removes them from the network) during each training batch, forcing the network to learn more robust features that are not dependent on any small set of neurons.</p><p>Here’s why dropout is so effective:</p><ul><li><strong>Prevents Overfitting</strong>: By randomly removing neurons, dropout prevents the network from memorizing the training data. The network has to be adaptable, learning more generalized patterns that are useful across different data samples, not just the training set.</li><li><strong>Encourages Redundancy</strong>: When different neurons can’t rely on the presence of others, the network develops a more redundant representation of the data. This redundancy means that the network doesn’t depend too heavily on any single feature, enhancing its ability to generalize from the training data to new, unseen data.</li><li><strong>Simple yet Powerful</strong>: Dropout is remarkably straightforward to implement but can lead to significant improvements in model performance, especially in complex networks prone to overfitting.</li></ul><p>Typically, dropout is applied to the fully connected layers of a CNN, where overfitting is most likely to occur due to the large number of parameters. However, it can also be used after convolutional layers, depending on the architecture and specific challenges of the task at hand.</p><p>In essence, dropout introduces a form of training noise, making the model more robust and less prone to the pitfalls of overfitting, ensuring that the network remains adaptable and generalized.</p><h3><strong>10. What Are Optimizers &amp; Learning Rates?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*o5ocmjRNwMGEXtbu" /></figure><p>In the journey of training a neural network, the optimizer is the navigator, guiding the model towards the lowest point of loss, where it makes the most accurate predictions. The learning rate, on the other hand, dictates the size of the steps the model takes on this journey. Too big, and it might overshoot the destination; too small, and the journey becomes tediously long.</p><p>Optimizers are algorithms that adjust the attributes of the neural network, such as weights and learning rate, to reduce losses. They play a crucial role in how quickly and effectively a model learns. Some of the most popular optimizers include:</p><ul><li><strong>SGD (Stochastic Gradient Descent)</strong>: The simplest form of optimizer. It updates the model’s weights using the gradient of the loss function with respect to the weights, multiplied by the learning rate. It’s like navigating through fog with a compass; basic but reliable.</li><li><strong>Momentum</strong>: Improves on SGD by ‘remembering’ the previous updates and applying them to the current update, essentially gaining speed (momentum) to navigate through flat areas of the loss landscape more effectively.</li><li><strong>Adam (Adaptive Moment Estimation)</strong>: Combines the benefits of two other extensions of SGD, AdaGrad and RMSProp, to adjust the learning rate on a per-parameter basis. It’s particularly effective and widely used due to its adaptability across different problems and data types.</li></ul><p>Learning Rate is arguably one of the most important hyperparameters to tune for training a neural network. It controls how much we adjust the weights of our network with respect to the loss gradient. The right learning rate helps the model to learn efficiently.</p><ul><li><strong>Fixed Learning Rate</strong>: Keeps the learning rate constant throughout training. It’s simple but might not be efficient for all problems.</li><li><strong>Adaptive Learning Rate</strong>: Adjusts the learning rate dynamically during training. Techniques like learning rate scheduling (gradually decreasing the learning rate) or optimizers like Adam that adjust the learning rate per parameter fall into this category.</li></ul><p>Choosing the right optimizer and learning rate is crucial for effective model training. It can make the difference between a model that learns quickly and accurately and one that doesn’t learn at all or converges too slowly.</p><h3>11. Handling Epochs, Batches &amp; Early Stopping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fus-IuGJi6TTSWxE.jpeg" /></figure><p>Training a neural network is a balancing act. It involves determining not just how the model learns (via learning rates and optimizers) but also how much it learns at a time (batch size) and how long it keeps learning (number of epochs). Additionally, early stopping serves as a safeguard against overfitting by halting the training process at the right moment. Let’s break these concepts down:</p><ul><li><strong>Epochs</strong>: An epoch represents one full cycle through the entire training dataset. Increasing the number of epochs allows the network more opportunities to learn from the data. However, too many epochs can lead to overfitting, where the model learns the training data too well, including its noise and outliers, at the expense of its ability to generalize to new data.</li><li><strong>Batches</strong>: Instead of feeding the entire dataset into the network at once (which can be memory intensive), we divide it into smaller batches. Batch size affects the model’s learning process; smaller batches mean more updates per epoch, which can lead to faster learning, but too small a batch might increase the noise in each update, making the training process less stable.</li><li><strong>Early Stopping</strong>: This is a form of regularization used to avoid overfitting by stopping the training when the model’s performance on a validation set starts to deteriorate, i.e., when it begins to learn the noise in the training set rather than the signal. It’s like stopping the game when you’re ahead to secure your winnings. By monitoring the model’s performance on a set of data not seen during training (validation set), we can stop the training at the point where performance peaks.</li></ul><p>Implementing early stopping involves setting aside a portion of the training data as a validation set and periodically evaluating the model’s performance on this set. If the model’s performance on the validation set fails to improve for a specified number of epochs, training is halted. This approach helps ensure that the model retains its ability to generalize well to new, unseen data.</p><p>Together, managing epochs, batch size, and implementing early stopping form a triad of strategies that optimize the training process, ensuring that the model learns efficiently and effectively without overfitting or underfitting.</p><h3>Conclusion</h3><p>CNNs are more than just layers and algorithms; they’re a testament to the power of machine learning to mimic and extend human capabilities in image recognition and beyond. As you embark on building your own CNNs, remember:</p><ol><li><strong>Balance is Key</strong>: From layer architecture to learning rates, finding the right balance is crucial for effective model training.</li><li><strong>Understanding Over Memorization</strong>: Grasping what each component does and why it’s used will empower you to design better models, not just replicate existing ones.</li><li><strong>Experimentation Leads to Mastery</strong>: The best way to learn is by doing. Experiment with different configurations, datasets, and challenges to deepen your understanding and discover what works best for your specific needs.</li></ol><p>As we conclude this guide, I encourage you to apply these insights and principles to your projects. Dive into building your own CNNs, experiment with different architectures and settings, and see firsthand how these networks can learn to see the world through data.</p><p>And I don’t usually ask for these but if you read all this way down, I’d really appreciate a clap ! Follow for more such content !</p><p>And if you need anything feel free to reach out ! <a href="https://linkedin.com/in/deveshsurve">https://linkedin.com/in/deveshsurve</a></p><h3>Have a great day !</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=932c4c3e0531" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>