<?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 Learn AI on Medium]]></title>
        <description><![CDATA[Stories by Learn AI on Medium]]></description>
        <link>https://medium.com/@divakar1591?source=rss-d1d83e7ca52c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3Bmzt3GsoNG5ovKbiaiF4A.png</url>
            <title>Stories by Learn AI on Medium</title>
            <link>https://medium.com/@divakar1591?source=rss-d1d83e7ca52c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:32:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divakar1591/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[Mastering Text Splitting in Langchain]]></title>
            <link>https://medium.com/@divakar1591/mastering-text-splitting-in-langchain-4750716e4090?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4750716e4090</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 05:15:18 GMT</pubDate>
            <atom:updated>2024-10-15T05:15:18.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SA3QLQSPOqvGbdFN.png" /></figure><h3>Introduction:</h3><p>In the rapidly evolving field of Natural Language Processing (NLP), Retrieval-Augmented Generation (RAG) has emerged as a powerful technique for enhancing the accuracy and relevance of AI-generated responses. At the heart of RAG lies a crucial step: “<strong><em>text splitting”</em></strong>. This process involves breaking down large documents into smaller, manageable chunks that can be efficiently processed and retrieved.</p><p>Langchain, a popular framework for developing applications with large language models (LLMs), offers a variety of text splitting techniques. Each method is designed to cater to different types of documents and specific use cases. In this comprehensive guide, we’ll explore the various text splitters available in Langchain, discuss when to use each, and provide code examples to illustrate their implementation.</p><h3>1. CharacterTextSplitter: The Simple Solution</h3><p>The CharacterTextSplitter is the most basic text splitting technique in Langchain. It divides text based on a specified number of characters, making it suitable for simple, uniform text splitting tasks.</p><p><strong>When to use:</strong><br>- For documents with consistent structure and formatting<br>- When you need a straightforward, character-based split<br>- In scenarios where more advanced splitting methods are unnecessary</p><pre>from langchain.text_splitter import CharacterTextSplitter<br>text = &quot;Your long document text here...&quot;<br>splitter = CharacterTextSplitter(<br>    separator=&quot;\n\n&quot;,<br>    chunk_size=1000,<br>    chunk_overlap=200<br>)<br>chunks = splitter.split_text(text) #you can also split documents using split_documents</pre><p>In this example, the splitter divides the text into chunks of 1000 characters, with a 200-character overlap between chunks. The separator “\n\n” is used to avoid splitting in the middle of paragraphs.</p><h3>2. RecursiveCharacterTextSplitter: The Versatile Powerhouse</h3><p>The RecursiveCharacterTextSplitter is Langchain’s most versatile text splitter. It attempts to split text on a list of characters in order, falling back to the next option if the resulting chunks are too large.</p><p><strong>When to use:</strong><br>- As a default choice for most general-purpose text splitting tasks.<br>- When dealing with various document types with different structures.<br>- To maintain semantic coherence in splits as much as possible.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br>text = &quot;Your long document text here...&quot;<br>splitter = RecursiveCharacterTextSplitter(<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;],<br>    chunk_size=1000,<br>    chunk_overlap=200,<br>    length_function=len<br>)<br>chunks = splitter.split_text(text)</pre><p>This splitter tries to split on double newlines first, then single newlines, spaces, and finally individual characters if necessary.</p><h3>3. TokenTextSplitter: Precision for Token-Based Models</h3><p>The TokenTextSplitter is designed to split text based on the number of tokens, which is particularly useful when working with models that have specific token limits, such as GPT-3 or any other models.</p><p><strong>When to use:</strong><br>- When working with token-sensitive models<br>- To ensure that chunks fit within model token limits<br>- For more precise control over input size for language models</p><pre>from langchain.text_splitter import TokenTextSplitter<br><br>text = &quot;Your long document text here...&quot;<br>splitter = TokenTextSplitter(<br>    encoding_name=&quot;cl100k_base&quot;,  # OpenAI&#39;s encoding<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(text)</pre><p>This example uses the “cl100k_base” encoding, which is suitable for newer OpenAI models. Adjust the encoding based on your specific model requirements.</p><h3>4. MarkdownHeaderTextSplitter: Structure-Aware Splitting for Markdown</h3><p>The MarkdownHeaderTextSplitter is specially designed to handle Markdown documents, respecting the header hierarchy and document structure.</p><p><strong>When to use:</strong><br>- Specifically for Markdown documents<br>- To maintain the logical structure of documentation or articles<br>- When header-based organization is crucial for your RAG application</p><pre>from langchain.text_splitter import MarkdownHeaderTextSplitter<br><br>markdown_text = &quot;&quot;&quot;<br># Title<br>## Section 1<br>Content of section 1<br>## Section 2<br>Content of section 2<br>### Subsection 2.1<br>Content of subsection 2.1<br>&quot;&quot;&quot;<br>headers_to_split_on = [<br>    (&quot;#&quot;, &quot;Header 1&quot;),<br>    (&quot;##&quot;, &quot;Header 2&quot;),<br>    (&quot;###&quot;, &quot;Header 3&quot;),<br>]<br>splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on)<br>chunks = splitter.split_text(markdown_text)</pre><p>This splitter creates chunks based on Markdown headers, preserving the document’s hierarchical structure.</p><h3>5. PythonCodeTextSplitter: Tailored for Code Splitting</h3><p>The PythonCodeTextSplitter is designed specifically for splitting Python source code, respecting function and class boundaries.</p><p><strong>When to use:</strong><br>- When working with Python codebases<br>- For code documentation or analysis tasks<br>- To maintain the integrity of code structures in your splits</p><pre>from langchain.text_splitter import PythonCodeTextSplitter<br><br><br>python_code = &quot;&quot;&quot;<br>def function1():<br>    print(&quot;Hello, World!&quot;)<br>class MyClass:<br>    def __init__(self):<br>        self.value = 42<br>    def method1(self):<br>        return self.value<br>&quot;&quot;&quot;<br>splitter = PythonCodeTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(python_code)</pre><p>This splitter attempts to keep functions and classes intact while splitting the code into manageable chunks.</p><h3>6. HTMLTextSplitter: Structured Splitting for Web Content</h3><p>The HTMLTextSplitter is tailored for HTML documents, maintaining the structure and hierarchy of HTML elements.</p><p><strong>When to use:</strong><br>- For processing web pages or HTML-formatted documents<br>- When HTML structure is important for your RAG task<br>- To extract content while preserving HTML context</p><pre>from langchain.text_splitter import HTMLTextSplitter<br><br>html_text = &quot;&quot;&quot;<br>&lt;html&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Main Title&lt;/h1&gt;<br>&lt;p&gt;This is a paragraph.&lt;/p&gt;<br>&lt;div&gt;<br>    &lt;h2&gt;Subsection&lt;/h2&gt;<br>    &lt;p&gt;Another paragraph.&lt;/p&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;<br>splitter = HTMLTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(html_text)</pre><p>This splitter respects HTML tags and attempts to create logical splits based on the document structure.</p><h3>7. NLTKTextSplitter: Linguistic-Based Splitting</h3><p>The NLTKTextSplitter uses the Natural Language Toolkit (NLTK) to split text based on linguistic features, such as sentences or paragraphs.</p><p><strong>When to use:</strong><br>- For more linguistically aware text splitting<br>- When working with well-formatted, natural language text<br>- To maintain sentence or paragraph integrity in your splits</p><pre>from langchain.text_splitter import NLTKTextSplitter<br><br>text = &quot;Your long document text here. It contains multiple sentences. Each sentence will be considered for splitting.&quot;<br>splitter = NLTKTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(text)</pre><p>Note that you’ll need to have NLTK installed and the necessary NLTK data downloaded for this splitter to work.</p><h3>8. SpacyTextSplitter: Advanced Linguistic Splitting</h3><p>The SpacyTextSplitter leverages the spaCy library for more advanced, language-aware text splitting.</p><p><strong>When to use:</strong><br>- For highly accurate, linguistically informed splitting<br>- When working with multiple languages<br>- For tasks requiring deep language understanding</p><pre>from langchain.text_splitter import SpacyTextSplitter<br><br>text = &quot;Your long document text here. It can be in various languages. SpaCy will handle the linguistic nuances.&quot;<br>splitter = SpacyTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(text)</pre><p>Remember to install spaCy and the appropriate language model before using this splitter.</p><h3>9. SentenceTransformersTextSplitter: Semantic-Aware Splitting</h3><p>The SentenceTransformersTextSplitter uses sentence embeddings to create semantically coherent chunks.</p><p><strong>When to use:</strong><br>- For applications requiring semantic understanding<br>- In conjunction with sentence embedding models<br>- When semantic similarity between chunks is crucial</p><pre>from langchain.text_splitter import SentenceTransformersTextSplitter<br><br>text = &quot;Your long document text here. This splitter will attempt to create semantically coherent chunks.&quot;<br>splitter = SentenceTransformersTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(text)</pre><p>This splitter requires the `sentence_transformers` library to be installed.</p><h3>10. LatexTextSplitter: Specialized for LaTeX Documents</h3><p>The LatexTextSplitter is designed to handle LaTeX documents, respecting the unique structure and commands of LaTeX syntax.</p><p><strong>When to use:</strong><br>- Specifically for LaTeX documents<br>- In academic or scientific document processing<br>- To maintain LaTeX formatting and structure in splits</p><pre>from langchain.text_splitter import LatexTextSplitter<br><br>latex_text = r&quot;&quot;&quot;<br>\documentclass{article}<br>\begin{document}<br>\section{Introduction}<br>This is the introduction.<br>\section{Methodology}<br>This is the methodology section.<br>\end{document}<br>&quot;&quot;&quot;<br>splitter = LatexTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20<br>)<br>chunks = splitter.split_text(latex_text)</pre><p>This splitter attempts to maintain the integrity of LaTeX commands and environments while creating chunks.</p><h3>Conclusion:</h3><p>Choosing the right text splitter is crucial for optimizing your RAG pipeline in Langchain. Each splitter offers unique advantages suited to different document types and use cases. The RecursiveCharacterTextSplitter serves as an excellent default choice for general purposes, while specialized splitters like MarkdownHeaderTextSplitter or PythonCodeTextSplitter offer tailored solutions for specific document formats.</p><p>When implementing your RAG system, consider the nature of your documents, the requirements of your downstream tasks, and the specific needs of your language model. Experiment with different splitters and fine-tune their parameters to achieve the best results for your particular use case.</p><p>By mastering these text splitting techniques, you’ll be well-equipped to build more effective and efficient RAG applications, enhancing the capabilities of your AI-powered systems and delivering more accurate and contextually relevant responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4750716e4090" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grad Cam (Storytelling)]]></title>
            <link>https://medium.com/@divakar1591/grad-cam-storytelling-7e55a819f98a?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e55a819f98a</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 07:14:02 GMT</pubDate>
            <atom:updated>2024-07-22T07:14:02.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*oYBcLNGbO8n3teU88_KGmg.png" /></figure><p>Imagine you’re exploring a mystery novel where a brilliant detective, let’s call her Detective CNN, is trying to solve a complex case using clues hidden within a series of detailed photographs. Each photograph holds secrets, and Detective CNN’s job is to uncover the most important parts — the clues — that help her crack the case.</p><p>Now, in the world of machine learning, Detective CNN is like a powerful detective model designed to recognize patterns and make decisions based on images. But here’s the twist: Detective CNN sometimes needs help explaining how she reached her conclusions, especially when the clues are subtle or spread across the entire picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHjkpuZFKX0d5_XL1J2UhQ.png" /></figure><p>That’s where Grad-CAM comes into play — it’s like Detective CNN’s magnifying glass. When Detective CNN looks at a photograph (an input image), she carefully examines it and tries to understand which parts are crucial for her decision-making process. Grad-CAM helps her by highlighting these important regions in the photograph with a vivid heatmap.</p><p>Here’s how Detective CNN and Grad-CAM work together:</p><ol><li><strong>Examining the Photograph</strong>: Detective CNN first studies the photograph, looking for features or patterns that might indicate, say, whether it’s a picture of a cat or a dog.</li><li><strong>Making Sense of Clues</strong>: As Detective CNN analyzes the image, she considers various parts of it. Some parts might be more relevant than others — a wagging tail, a distinctive ear, or a particular texture.</li><li><strong>Using the Magnifying Glass (Grad-CAM)</strong>: To understand exactly where these important clues are located, Detective CNN employs Grad-CAM. This tool uses gradients (a kind of mathematical clues) to pinpoint the specific areas of the image that are most influential in Detective CNN’s decision-making process. It’s like highlighting those crucial clues in bright colors so Detective CNN — and anyone else following along — can see exactly which parts of the photograph are most important for her decision.</li><li><strong>Solving the Case</strong>: With the help of Grad-CAM, Detective CNN can confidently explain why she believes the photograph is of a cat, pointing directly to the whiskers or the shape of the ears that stood out the most.</li></ol><p>In essence, Grad-CAM isn’t just a tool — it’s Detective CNN’s storytelling companion, helping her explain her reasoning with clarity and precision. By revealing the hidden clues that influenced her decision, Grad-CAM ensures that Detective CNN’s deductions are not only accurate but also understandable to everyone involved in the investigation. And just like a great detective novel, this collaboration between Detective CNN and Grad-CAM unveils the fascinating inner workings of artificial intelligence, making complex decisions a little more transparent and a lot more fascinating.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e55a819f98a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grad-CAM (Gradient-weighted Class Activation Mapping)]]></title>
            <link>https://medium.com/@divakar1591/grad-cam-gradient-weighted-class-activation-mapping-8e1aeaf96d94?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e1aeaf96d94</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 06:31:54 GMT</pubDate>
            <atom:updated>2024-07-22T07:20:39.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*JGEibe2CSzEAZr-Qf0b9Uw.png" /></figure><p>Grad-CAM (Gradient-weighted Class Activation Mapping) is a technique in machine learning and computer vision used to understand and visualize the decisions made by a convolutional neural network (CNN). It helps to localize important regions in an input image that contribute to the CNN’s classification decision.</p><p>Here’s how Grad-CAM generally works:</p><ol><li><strong>Input</strong>: An image is fed into a pre-trained CNN.</li><li><strong>Output</strong>: The CNN processes the image and produces a classification (e.g., cat, dog, car).</li><li><strong>Gradient Calculation</strong>: Grad-CAM uses the gradients of a target class (e.g., “cat” class) flowing into the final convolutional layer of the CNN to understand the importance of each neuron for that class.</li><li><strong>Weighted Sum</strong>: It computes a weighted sum of the activations of the final convolutional layer, where the weights are the gradients of the target class with respect to the neuron activations.</li><li><strong>Heatmap Generation</strong>: The weighted sum is then used to generate a heatmap that highlights the regions of the input image that are important for the CNN’s decision about the target class.</li></ol><p>Grad-CAM is effective because it provides a clear visualization of where the model is focusing when making its predictions, which can help in understanding model behavior, debugging models, and improving model interpretability.</p><h3>Key Advantages of Grad-CAM:</h3><ul><li><strong>Localization</strong>: It accurately localizes the relevant parts of the image that influenced the model’s decision.</li><li><strong>Model-Agnostic</strong>: Grad-CAM can be applied to a wide variety of CNN architectures without the need for retraining.</li><li><strong>Interpretability</strong>: It helps in interpreting and explaining CNN predictions, which is crucial in applications where understanding the basis of a decision is important (e.g., medical diagnostics, autonomous driving).</li></ul><h3>Use Cases:</h3><ul><li><strong>Medical Imaging</strong>: Identifying which regions of an X-ray or MRI contributed most to a diagnosis.</li><li><strong>Autonomous Driving</strong>: Understanding where the model is looking on the road to make driving decisions.</li><li><strong>Natural Language Processing</strong>: Visualizing which words or phrases in an input text are most influential in a classification decision.</li></ul><p>In summary, Grad-CAM is a valuable tool for understanding and interpreting the decisions of CNNs by producing visual explanations of where the model is focusing its attention within an image.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e1aeaf96d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down the LangChain ]]></title>
            <link>https://medium.com/@divakar1591/breaking-down-the-langchain-9b3b0dae9847?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b3b0dae9847</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 17:36:41 GMT</pubDate>
            <atom:updated>2024-04-19T17:36:41.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>A high level introduction to the framework that is simplifying the development of AI applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ph6wTCnpqUwvw1Hv.gif" /></figure><h3>Introduction</h3><p>Suppose you have a text book and it’s the night before your big exam and <em>obviously</em> you don’t have notes. How nice it would be if you could just <strong>ask your textbook</strong> to tell you what are the <strong>important</strong> things you should study. LangChain can help you do exactly that!</p><p>LangChain is an <a href="https://github.com/hwchase17/langchain"><strong>open-source framework</strong></a> designed to help build <strong>applications powered by large language models (LLMs)</strong> like ChatGPT, and create more advanced use cases around them by<strong> chaining together</strong> different components from several modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fylhTZDl1bzT_O6G.png" /></figure><p>Increase in the usage of LangChain since the increased usage of ChatGPT</p><p>LangChain aims to assist in the <strong>development of applications</strong> that not only call out to a language model <strong>via an API</strong> but also connect to <strong>other sources of data</strong> (<strong>Integration</strong>)and <strong>interact with their environment (Agency)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OA_g-MclocjRt67u.png" /></figure><h3>Components of LangChain</h3><p>The LangChain framework provides two main value propositions:</p><ul><li><strong>Modular abstractions</strong> for components necessary to work with language models</li><li>Use-case specific <strong>chains</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*VPtJy_Zt9DkYVjYC.jpeg" /></figure><blockquote><em>The following text will have code using the ChatGPT API key, to understand the setup please see </em><a href="https://langchain.readthedocs.io/en/latest/?"><em>here</em></a><em> for full documentation on: </em><strong><em>Getting started</em></strong><em>(installation, setting up the environment, simple examples), </em><strong><em>How-To examples</em></strong><em> (demos, integrations, helper functions), </em><strong><em>Reference</em></strong><em> (full API docs), Resources (high-level explanation of core concepts)</em></blockquote><p>The core components of LangChain include:</p><h3>1. Models (LLM Wrappers) 🦾:</h3><p>LangChain provides a generic interface to various foundation models, such as OpenAI’s GPT-3, Hugging Face’s models etc.</p><p>For example we have the chat messages which usually follow this scheme: Like text, but specified with a message type (System, Human, AI)</p><ul><li><strong>System</strong> — Helpful background context that tell the AI what to do</li><li><strong>Human</strong> — Messages that are intented to represent the user</li><li><strong>AI</strong> — Messages that show what the AI responded with</li></ul><p>For details on how this works, see OpenAI’s <a href="https://platform.openai.com/docs/guides/chat/introduction">documentation</a></p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.schema import HumanMessage, SystemMessage, AIMessage<br></pre><pre>chat = ChatOpenAI(temperature=.7, openai_api_key=openai_api_key) #you have to generate your own private key<br>chat(<br>    [<br>        SystemMessage(content=&quot;You are a nice AI bot that helps a user figure out what to eat in one short sentence&quot;),<br>        HumanMessage(content=&quot;I like tomatoes, what should I eat?&quot;)<br>    ]<br>)</pre><pre>Output: <br>AIMessage(content=&#39;You could eat a caprese salad with fresh mozzarella and basil.&#39;, additional_kwargs={}, example=False)</pre><h3>Prompts 📃:</h3><p>It offers prompt management and optimization, allowing developers to create better prompts for LLMs.</p><h3>Chains 🔗:</h3><p>LLMs can be combined with other components, such as external data sources or other LLMs, to create more <strong>complex applications</strong>.</p><p>A chain is made up of links, which can be either primitives or other chains. Primitives can be either prompts, LLMs, utils, or other chains.</p><p>So a chain is <strong>basically a pipeline</strong> that processes an input by using a specific combination of primitives. Intuitively, it can be thought of as a <strong>‘step’</strong> that performs a certain set of operations on an input and returns the result. Chains are divided in three types: <strong>Utility chains, Generic chains and Combine Documents chains</strong>. For more details, see <a href="https://github.com/pinecone-io/examples/blob/master/generation/langchain/handbook/02-langchain-chains.ipynb">here</a>.</p><p>Lets take an exmple of a simple sequential chain, these are chains where you can use the output of one LLM as the input of another-</p><pre>from langchain.llms import OpenAI<br>from langchain.chains import LLMChain<br>from langchain.prompts import PromptTemplate<br>from langchain.chains import SimpleSequentialChain<br></pre><pre>llm = OpenAI(temperature=1, openai_api_key=openai_api_key)<br>template = &quot;&quot;&quot;Your job is to come up with a classic dish from the area that the users suggests.<br>% USER LOCATION<br>{user_location}</pre><pre>YOUR RESPONSE:<br>&quot;&quot;&quot;<br>prompt_template = PromptTemplate(input_variables=[&quot;user_location&quot;], template=template)<br></pre><pre># Holds the&#39;location&#39; chain<br>location_chain = LLMChain(llm=llm, prompt=prompt_template)<br>template = &quot;&quot;&quot;Given a meal, give a short and simple recipe on how to make that dish at home.<br>% MEAL<br>{user_meal}</pre><pre>YOUR RESPONSE:<br>&quot;&quot;&quot;<br>prompt_template = PromptTemplate(input_variables=[&quot;user_meal&quot;], template=template)</pre><pre># Holds the&#39;meal&#39; chain<br>meal_chain = LLMChain(llm=llm, prompt=prompt_template)<br></pre><pre>overall_chain = SimpleSequentialChain(chains=[location_chain, meal_chain], verbose=True)<br></pre><pre>review = overall_chain.run(&quot;Rome&quot;)</pre><pre>&gt; Entering new SimpleSequentialChain chain...<br>A classic dish from Rome is Spaghetti alla Carbonara. This dish is a creamy pasta made with eggs, cured pork, Pecorino Romano cheese, black pepper, and Olive oil.<br>1. Bring a large pot of salted water to a boil.<br>2. Add about a pound of spaghetti noodles and cook for 8-10 minutes, stirring occasionally.<br>3. Drain noodles and set aside.<br>4. In a separate bowl, whisk together 2 eggs and ½ cup of Pecorino Romano cheese.<br>5. In a large skillet, heat 2 tablespoons of olive oil over medium heat.<br>6. Add 4 ounces of cubed pancetta or guanciale and cook until lightly browned, stirring often.<br>7. Reduce heat to low and add the spaghetti noodles.<br>8. Pour the egg mixture over the noodles and vigorously stir together.<br>9. Remove from heat, stir in a pinch of black pepper and serve.</pre><pre>&gt; Finished chain.</pre><h3>Agents 🤖:</h3><p>LangChain provides a standard interface for agents, which determine which actions to take and in what order, seeing an <strong>Observation</strong>, and <strong>repeating</strong> that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end-to-end agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-J496JrOYFzm1Gls.png" /></figure><h3>Memory 🧠:</h3><p>It offers tools for managing conversational memory, allowing LLMs to remember previous interactions and provide more context-aware responses. There are many types of memories depending on the usecases involved. To check out the details see <a href="https://python.langchain.com/en/latest/modules/memory/how_to_guides.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OhxnrJPOY2j9lOVj.png" /></figure><p>Chatbot Memory with LangChain</p><h3>Indexes 🗂️:</h3><p>LangChain supports retrieval augmentation, enabling more robust AI systems with long-term memory.</p><p>Indexes refer to <strong>ways to structure documents</strong> so that LLMs can <strong>best interact</strong>with them. They contain utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains. For more details, check <a href="https://python.langchain.com/en/latest/modules/indexes.html">here</a>.</p><h3>Conclusion-</h3><p>LangChain is definitely growing towards revoutionizing the NLP game for everyone. With new applications and usecases everyday, the growth trajectory will definitely result into more innovative approaches and useful discoveries. Till then lets keep on experimenting!</p><p>Check out this amazing <a href="https://github.com/gkamradt/langchain-tutorials/blob/main/LangChain%20Cookbook%20Part%201%20-%20Fundamentals.ipynb">notebook</a> by <a href="https://github.com/gkamradt">Greg Kamradt</a>, which breaks down every code in detail for a high level understanding on which you can build your own applications.</p><p>For something extra, here’s a little c<a href="https://github.com/Tor101/LangChain-CheatSheet">heatsheet</a>!! Enjoy :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b3b0dae9847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes 101: A beginner’s guide to container orchestration]]></title>
            <link>https://medium.com/@divakar1591/kubernetes-101-a-beginners-guide-to-container-orchestration-2045e6a2a7d3?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2045e6a2a7d3</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 02:30:55 GMT</pubDate>
            <atom:updated>2024-04-20T12:43:48.686Z</atom:updated>
            <content:encoded><![CDATA[<h4>A high level introduction to Kubernetes and it’s components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*X5MNlNHLEYejUS6e.gif" /></figure><h3>Introduction</h3><p>If you’re new to the world of container management and have ever wondered how leading tech companies <strong>effortlessly deploy and scale their applications</strong>, <strong>Kubernetes </strong>might just be the thing you’re looking for.</p><p>Think of Kubernetes as the <strong><em>traffic controller</em></strong> for your containerized applications. It ensures they <strong>run harmoniously</strong>, <strong>scaling</strong> up when needed and <strong>self-healing</strong> when things go awry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hYUSJT-I05RTT7_V.png" /></figure><p>Kubernetes(or <strong>K8s</strong>) was developed by Google and now maintained by the <strong>Cloud Native Computing Foundation (CNCF), </strong>it<strong> </strong>has become the de facto standard for container orchestration due to its robust features and active community support.</p><p>It’s an <strong>open-source container orchestration platform</strong> that simplifies the <strong>deployment, scaling, and management of containerized applications,</strong> which basically means that kubernetes helps you <strong>manage applications</strong> that are made up of hundreds or maybe thousands of <strong>containers</strong> and it helps you manage them in <strong>different environments</strong> like <strong>physical machines, virtual machines</strong> or <strong>cloud</strong> environments or even hybrid deployment environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*WAXQ08VXdzM_ssmY.png" /></figure><h3>What problems does Kubernetes solve?</h3><p>The rise of <strong>microservices</strong> in almost every domain has also increased the usage of <strong>container technology</strong> to manage them and actually offer the perfect host for small independent applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mjbiw_8lGqVKlCLQ.png" /></figure><p>Containers are a critical component in microservices architectures. They provide <strong>isolation, portability, and resource efficiency</strong>, allowing each microservice to run in its own <strong>self-contained environment</strong> with <strong>consistent behavior across different stages of development and deployment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*Gzf9jNkANVw6SgzQ.png" /></figure><p>A Containerization illustration using Docker</p><p>Their integration with <strong>orchestration platforms like Kubernetes</strong> further enhances the management of microservices by <strong>automating </strong>deployment and scaling processes.</p><p>Features offered by orchestration tools, in our case Kubernetes:</p><ul><li><strong>High availability</strong>, that simply means there’s no downtime in your application, it’s always available to the user</li><li><strong>Scalability</strong> or high performance based on the load i.e the number of people accessing your application</li><li><strong>Disaster Recovery</strong>, i.e the platform can help backup and restoration of data in case of emergencies. The container can run from the latest state after the recovery without losing information</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*sHO3l5gdJUNkZdl_.png" /></figure><h3>The architecture of Kubernetes</h3><p>To understand the architecture distinctly, lets take a look at different components and how are they interlinked.</p><h3>Nodes:</h3><p>The fundamental unit of Kubernetes is a <strong>node</strong>. A node is basically a <strong>physical or virtual machine</strong>. Therefore a node helps you to understanding a machine as just a CPU and RAM resources that can be utilized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*he164AHH8UviO3Ul.png" /></figure><h3>Cluster:</h3><p>Kubernetes operates in clusters. As the name suggests, a cluster is a <strong>combination of nodes</strong> and as node is the most basic unit, a cluster is made out of <strong>atleast one node.</strong></p><p>What a cluster does is<strong> pools all it’s resources together</strong> and works kind of like a <strong>hivemind</strong>. If there’s a discrepancy in one node, the <strong>cluster</strong> takes care of that and doesn’t let it affect the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*FLjLnBaeKPMRpb7C.png" /></figure><p>As already established, it’s made of atleast one <strong>master node (or control plane)</strong>, and connected to it are the <strong>worker nodes ( or simply nodes)</strong>.<strong> </strong>These consist of a <strong>Kubelet</strong>, which is the <strong>primary node agent</strong>, i.e it helps clusters to <strong>communicate</strong> to each other and <strong>running different application processes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ceukSZytHkkeLHfK.png" /></figure><p>The<strong> worker node</strong> is where all the <strong>applications are deployed</strong> and <strong>actual work happens</strong>. It has a different number of containers deployed and running depending upon how the <strong>workload</strong> is distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Ki7MjweNRJkAyChL.png" /></figure><p><strong><em>So what does the master node do?</em></strong></p><p>The master node runs <strong>several kubernetes processes</strong> that are absolutely necessary to run and manage the cluster properly. These processes are:</p><ul><li><strong>API Server:</strong> The API server is the central component that exposes the Kubernetes API. It handles incoming RESTful API requests, performs <strong>authentication, authorization, validation, and triggers actions accordingly</strong>. Clients interact with the API server to manage resources in the cluster.</li><li><strong>etcd</strong>: It’s a highly available distributed key-value store used as Kubernetes’<strong> backing store for all cluster data,</strong> including configuration settings, object metadata, and current state. It is a crucial component for <strong>maintaining cluster consistency and durability</strong>.</li><li><strong>Controller Manager:</strong> This is responsible for <strong>running controller processes</strong> that regulate the <strong>state</strong> of the system. Controllers include the Replication Controller (for managing replicas of pods), the Node Controller (for monitoring node health) etc.</li><li><strong>Scheduler:</strong> The Scheduler watches for newly created pods with no assigned node and <strong>decides which node they should run on</strong>. It takes factors like resource requirements, node affinity, and other policies into account to make placement decisions.</li></ul><p>Therefore <strong>worker nodes </strong>have a <strong>higher workload</strong> and require<strong> large amount of resources </strong>but control plane nodes (master nodes) are much more important.</p><p>This is the reason that in real life production environments, we generally have atleast <strong>2 master nodes</strong>, so that if one fails, the entire system won’t come crumbling down.</p><h3>Pods:</h3><p>The <strong>smallest unit</strong> of a node in Kubernetes is a pod. Kubernetes <strong>doesn’t run containers directly, </strong>it wraps one or more containers into a <strong>higher-level structure </strong>called a <strong>pod</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MVs0MKpazAlVV4Dt.png" /></figure><p>Any containers in the<strong> same pod</strong> will share the <strong>same resources</strong> and <strong>local network</strong>. Containers can easily <strong>communicate</strong> with other containers in the same pod as though they were on the same machine while maintaining a degree of isolation from others.</p><p>Kubernetes adds this <strong>abstraction layer</strong> so that you can <strong>replace</strong> them if you want to and also so that you <strong>don’t have to directly work with</strong> different containerization technology like docker etc. You only <strong>interact with the Kubernetes layer.</strong></p><p>Pod runs applications container inside of it. Although it can handle multiple containers, the scalability and resources should be kept in mind.</p><p>In cases of <strong>high loads</strong>, to avoid discrepancies,<strong> Pod Replicas</strong> are used to achieve <strong>high availability, load balancing, and scalability</strong> for an application or service running in a Kubernetes cluster. When you create multiple replicas of a pod, you’re essentially creating<strong> multiple instances</strong> of that pod, each running the same set of containers and configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CtKoL8Wn9ZzrNUui.gif" /></figure><p><a href="https://matthewpalmer.net/kubernetes-app-developer/articles/kubernetes-networking-guide-beginners.html">Pods communicating on the same node</a></p><p>The pods communicate with each other through a <strong>virtual network</strong>, where each pod <strong>gets it’s own IP Address</strong>.</p><h3>Service &amp; Ingress</h3><p>As we just established that each pod gets it’s own IP address, it becomes really <strong>inconvenient</strong> where we have to adjust it eveytimes a pod dies and <strong>replaced with a new pod.</strong></p><p>Service solves this problem. It’s kinda like a <strong>permanent IP Address</strong> of each pod. As the lifecycles are not connected in service, even if a pod dies and replaced with a replica, it’ll have the same service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oXUGs5yaA99_Xmax.png" /></figure><p>The endgame of an application is to be able to <strong>accessed through a browser </strong>and for that we use the external service, but if you notice the URL of the external service is not very <strong>practical.</strong> What you have is an <strong>http protocol with a node ip address</strong> <strong>so of the node not the service</strong> and the <strong>port number of the service, </strong>which is okay for checking if your application works but not for the end user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*xvv9xw5qObLo457n.png" /></figure><p>What we want is a <strong>secure protocol and a domain name</strong> and for that there is another component of kubernetes called <strong>Ingress</strong> so <strong>instead of service the request goes first to ingress and it does the forwarding then to the service.</strong></p><h3>ConfigMap and Secret</h3><p>A ConfigMap is a Kubernetes resource used to <strong>store configuration data in the form of key-value pairs</strong>.</p><p>This data can be <strong>used by pods as environment variables or mounted as files in a volume</strong>. ConfigMaps are commonly used for <strong>non-sensitive</strong> configuration information that your application needs to run but doesn’t require encryption or special protection.</p><p>You can have different ConfigMaps for different environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*EGY6p6u8qRcdVNRQ.gif" /></figure><p><a href="https://matthewpalmer.net/kubernetes-app-developer/articles/ultimate-configmap-guide-kubernetes.html">ConfigMaps</a></p><p>A Secret is <strong>similar</strong> to a ConfigMap but is designed to <strong>store sensitive information, such as passwords, API tokens, or TLS certificates.</strong> Secrets are <strong>base64-encoded </strong>and can be mounted as files or used as environment variables in pods. Kubernetes automatically encodes and decodes secrets as needed.</p><h3>Volume</h3><p>A very important aspect when it comes to Kubernetes is the <strong>Data Storage.</strong></p><p>Suppose you have an <strong>application pod </strong>which is connected to a <strong>database</strong> <strong>pod</strong>. If due to some reason your database pod is restarted, the data would be <strong>gone</strong>. This will create a huge problem as <strong>we want our data to be persistent.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*v4kFHbQ0JK1fbItp.png" /></figure><p>This is where <strong>volumes</strong> comes in. It basically attaches a physical storage on a hard drive to your pod and that<strong> storage</strong> could be either on a <strong>local machine</strong> meaning on the<strong> same server node where the pod is running </strong>or it could be on a <strong>remote storage </strong>meaning outside of the kubernetes cluster it could be a <strong>cloud storage</strong> or it could be your own <strong>premise storage</strong> which is not part of the kubernetes cluster.</p><h3>Deployment &amp; StatefulSet</h3><p>We established that pods can have <strong>multiple replicas</strong> in cases of discrepancies, <strong>but how many replicas should be running at a time?</strong></p><p>This is where <strong>deployment</strong> comes in. As pods are an abstraction layer on containers, we can consider <strong>deployment as an abstraction layer over the pods.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GLKXO6Uo8Z2B1zcw.png" /></figure><p><a href="https://medium.com/google-cloud/kubernetes-101-pods-nodes-containers-and-clusters-c1509e409e16">Deployment</a></p><p>In very simpler terms, a deployment allows you to <strong>describe</strong> the desired <strong>state of an application</strong> and <strong>how many replicas of it should be running at any given time.</strong></p><p>Lets take the same previous <strong>example</strong>, suppose we have a <strong>node with an application pod and a database pod</strong>. If the <strong>application pod dies</strong>, it’ll increase the downtime which is really the worst thing in production. In order to keep our application running, <strong>instead of relying on one pod, we replicate everything on multiple servers. </strong>The replica will have the same thing, connected to the same service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*I05Sy2YcT6oOqNWb.png" /></figure><p>For creating the <strong>replic</strong>a of the pods, <strong>we don’t just create a new pod</strong>, <strong>we define a blueprint of how many replicas we want</strong>. <strong>This blueprint is called Deployment</strong>. In practice, we don’t work with pods, we create deployments and they specify the number of replicas that are needed.</p><p>So now if <strong>one of the replicas of the application pod dies</strong> the service will forward the requests to another one so our application would <strong>still be accessible</strong> for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4uILRLW9_4JkplOF.png" /></figure><p>So what about the database pod? Our application will <strong>not be accesible if the database pod dies as well</strong> but the problem is we can’t replicate database using a deployment.</p><p>Database has a <strong><em>state</em></strong> which is <strong>its data, </strong>that is, if we have <strong>clones or replicas of the database</strong> they would <strong>all need to access the same shared data storage</strong> and there you would need some kind of <strong>mechanism</strong> that manages which pods are currently writing to that storage or which pods are reading from the storage in order to avoid data inconsistencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rJamU6PQ7wZOj4M7.png" /></figure><p>This mechanism in addition to replicating feature is offered by another kubernetes component called <strong>StatefulSet</strong> and is meant specifically for applications like databases(mysql, mongodb, elasticsearch etc.)</p><p>Therefore <strong>databases or any other stateful applications should be created using StatefulSets</strong> and not deployments.</p><p>Although StatefulSets should be used for the above, it’s relatively <strong>tedious</strong> and <strong>difficult</strong>. That’s why it’s also a common practice in production to <strong>host database applications outside of the kubernetes cluster and communicate with the external database.</strong></p><h3>Conclusion</h3><p>Hoping that this article has scratched the surface of Kubernetes, my main objective was to make you <strong>familiar</strong> with what Kubernetes actually is and does.</p><p>There’s no denying that this <strong>container orchestration platform</strong> is incredibly <strong>versatile</strong> and can be <strong>customized</strong> to meet the unique needs of different applications and organizations, therefore it’s a <strong>valuable skill to have</strong>. As we’ve covered the <em>WHAT </em>part, we will try and focus on the <em>HOW</em> part in the upcoming articles, so stay tuned!</p><p>learn more — <a href="https://medium.com/google-cloud/kubernetes-101-pods-nodes-containers-and-clusters-c1509e409e16">https://medium.com/google-cloud/kubernetes-101-pods-nodes-containers-and-clusters-c1509e409e16</a></p><p><em>Credit goes to — </em><a href="https://medium.com/@harshitaaa"><em>https://medium.com/@harshitaaa</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2045e6a2a7d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Transfer Learning]]></title>
            <link>https://medium.com/@divakar1591/a-beginners-guide-to-transfer-learning-8b9e690c7f24?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b9e690c7f24</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 18:19:21 GMT</pubDate>
            <atom:updated>2024-04-18T18:25:57.941Z</atom:updated>
            <content:encoded><![CDATA[<h4>Take a look at what transfer learning is with a code along with an example</h4><h3>Introduction</h3><p>We, humans, are very perfect at applying the transfer of knowledge between tasks. This means that whenever we encounter a new problem or a task, we recognize it and apply our relevant knowledge from our previous learning experiences. This makes our work easy and fast to finish. For instance, if you know how to ride a bicycle and if you are asked to ride a motorbike which you have never done before. In such a case, our experience with a bicycle will come into play and handle tasks like balancing the bike, steering, etc. This will make things easier compared to a complete beginner. Such learnings are very useful in real life as they make us more perfect and allow us to earn more experience. Following the same approach, a term was introduced Transfer Learning in the field of machine learning. This approach involves the use of knowledge that was learned in some tasks and applying it to solve the problem in the related target task. While most machine learning is designed to address a single task, the development of algorithms that facilitate transfer learning is a topic of ongoing interest in the machine-learning community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*lhO_l8mdhxxAwtjE.jpeg" /></figure><h3>What is Transfer Learning?</h3><p>Transfer learning is a technique in <a href="https://www.geeksforgeeks.org/machine-learning/">machine learning</a> where a model trained on one task is used as the starting point for a model on a second task. This can be useful when the second task is similar to the first task, or when there is limited data available for the second task. By using the learned features from the first task as a starting point, the model can learn more quickly and effectively on the second task. This can also help to prevent <a href="https://www.geeksforgeeks.org/underfitting-and-overfitting-in-machine-learning/">overfitting</a>, as the model will have already learned general features that are likely to be useful in the second task.</p><h3>Why do we need Transfer Learning?</h3><p>Many deep neural networks trained on images have a curious phenomenon in common: in the early layers of the network, a deep learning model tries to learn a low level of features, like detecting edges, colours, variations of intensities, etc. Such kind of features appear not to be specific to a particular dataset or a task because no matter what type of image we are processing either for detecting a lion or car. In both cases, we have to detect these low-level features. All these features occur regardless of the exact cost function or image dataset. Thus, learning these features in one task of detecting lions can be used in other tasks like detecting humans.</p><h3>The problem with training your own model:</h3><ol><li>For training our own model we need a<strong> lot</strong> of <strong>labelled training data</strong> which is both <strong>labour intensive</strong> and <strong>costly</strong>.</li><li>Training your own model required a <strong>lot</strong> of <strong>computation</strong> <strong>time</strong> which can range upto weeks and normal people don’t have that kind of hardware or time to handle that.</li></ol><p>This is where using a <strong>pre-trained model</strong> comes into play. Models like <strong>VGGNet</strong>, <strong>ResNet</strong>, <strong>Xception</strong> are trained very efficiently on a quite large and labelled data and can be <strong>integrated in our problem</strong> by fine tuning to our specific task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gi4NrZibC4Wqa_Qy.png" /></figure><p>Drivers of ML industrial success by Andrew Ng, 2016 NIPS</p><p>According to Andrew Ng, if we do not consider supervised learning, Transfer learning has the trajectory to be the <strong>next big thing</strong> in the machine learning domain.</p><p>As we have already established, the main idea behind transfer learning is that a pre-trained model has already learnt to extract useful features from a large dataset, which can be useful for <strong>solving </strong>a <strong>similar problem</strong>. By starting with a pre-trained model, we can <strong>reduce</strong> the<strong> amount of training data required</strong>, <strong>speed up</strong> the training process, and<strong> improve</strong> the <strong>accuracy</strong> of the model. Simply,</p><blockquote><strong><em>Do not reinvent the wheel, make vehicles instead.</em></strong></blockquote><h3>How does it work?</h3><p>Transfer learning works by <strong>leveraging</strong> the knowledge learnt from a pre-trained model to solve a related problem. In transfer learning, the pre-trained model is typically <strong>trained</strong> on a <strong>large dataset</strong>, such as <strong>ImageNet</strong>, and has already learnt a set of features that can be used to extract <strong>meaningful information</strong> from an image. These <strong>features </strong>can be used to solve a related problem, such as <strong>object detection or image classification</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aZKiE3Ygrz2W2Zz_.jpeg" /></figure><p>To use transfer learning, we typically follow the following steps:</p><h3>1. Select a pre-trained model:</h3><p>The first step is to select a pre-trained model that has been trained on a large dataset. Popular pre-trained models include <strong>VGG, ResNet, Inception,</strong> and <strong>MobileNet</strong>.</p><h3>2. Remove the final layers:</h3><p>The second step is to remove the final layers of the pre-trained model, which are usually responsible for the <strong>task-specific predictions</strong>. By removing the final layers, we can use the pre-trained model as a feature extractor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Xvw9yQofHV8PF1WX.jpeg" /></figure><p>VGG-16 pre trained model</p><h3>3. Add new layers:</h3><p>The third step is to add new layers on top of the pre-trained model to adapt it to the new task. These layers are usually<strong> responsible</strong> for the <strong>task-specific predictions.</strong></p><h3>4. Fine-tune the model:</h3><p>The final step is to<strong> fine-tune</strong> the model by training the new layers on the new dataset. During fine-tuning, the <strong>weights</strong> of the pre-trained model are <strong>frozen</strong>, and only the weights of the<strong> new layers</strong> are <strong>updated</strong>. The weights of the model is the entire essence of it, therefore by fine-tuning the model, we can adjust the learnt features to <strong>better fit</strong> the new dataset, <strong>improving</strong> the <strong>model’s performance</strong> on the <strong>new task</strong>.</p><p><strong>Let’s understand all we that have learnt with the help of an example and see how to implement it in code.</strong></p><p>In the example below, we are using <strong>VGG-16</strong> which is a <strong>pre-trained CNN model</strong> that was developed by the <strong>Visual Geometry Group</strong> at the University of Oxford. It consists of <strong>16 convolutional layers</strong> and <strong>3 fully connected</strong> layers, with <strong>over 138 million parameters</strong>.</p><pre>#Installing dependencies<br>import numpy as np<br>import pandas as pd<br>import tensorflow as tf<br>from keras.layers import Dense, Flatten, Dropout<br>from keras.models import Sequential<br>from keras.optimizers import Adam<br>from keras.preprocessing.image import ImageDataGenerator<br>from keras.applications.vgg16 import VGG16</pre><p>In this example we are leveraging VGG-16 to make a <strong>dog-vs-cat classifier</strong> and I have used a dataset from kaggle for this. You can check it out <a href="https://www.kaggle.com/datasets/salader/dogs-vs-cats?resource=download"><strong>here</strong></a>.</p><pre># Define paths to the train and validation datasets<br>train_path = &#39;/content/train&#39;<br>valid_path = &#39;/content/test&#39;</pre><pre># Define image size, batch size, and number of classes<br>img_size = 224<br>batch_size = 32<br>num_classes = 2</pre><p>After setting up the data, we create data generators for the training and validation data using the <strong>ImageDataGenerator </strong>class from Keras. These generators apply <strong>data augmentation</strong> and <strong>rescaling</strong> to the images in the datasets, which helps improve the model&#39;s performance.</p><pre># Define data generators for training and validation data<br>train_datagen = ImageDataGenerator(<br>    rescale=1./255,<br>    shear_range=0.2,<br>    zoom_range=0.2,<br>    horizontal_flip=True)<br>train_generator = train_datagen.flow_from_directory(<br>    train_path,<br>    target_size=(img_size, img_size),<br>    batch_size=batch_size,<br>    class_mode=&#39;categorical&#39;)</pre><pre>valid_datagen = ImageDataGenerator(rescale=1./255)<br>valid_generator = valid_datagen.flow_from_directory(<br>    valid_path,<br>    target_size=(img_size, img_size),<br>    batch_size=batch_size,<br>    class_mode=&#39;categorical&#39;)</pre><p>Now that we’re done with the data bit, we can go on and load the VGG-16 model using the <strong>VGG16</strong> function from Keras and<strong> freeze its layers</strong> to <strong>prevent</strong> them from <strong>being trained</strong>. We then add a custom output layer on top of the VGG16 model using the <strong>Sequential</strong> class from Keras.</p><pre># Load the VGG16 model and freeze its layers<br>base_model = VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(img_size, img_size, 3))<br>for layer in base_model.layers:<br>    layer.trainable = False</pre><pre># Add a custom output layer on top of the VGG16 model<br>model = Sequential()<br>model.add(base_model)<br>model.add(Flatten())<br>model.add(Dense(256, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(num_classes, activation=&#39;softmax&#39;))</pre><p>Finally we compile the model using an optimizer, loss function (for better accuracy keeping a low value) and evaluation metric, and then train the model using the <strong>fit </strong>function. We evaluate the model on the validation data using the <strong>evaluate</strong> function.</p><pre># Compile the model with an optimizer, loss function, and evaluation metric<br>model.compile(optimizer=Adam(lr=0.0001), loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><pre># Train the model using the data generators<br>history = model.fit(train_generator, epochs=10, validation_data=valid_generator)</pre><pre># Evaluate the model on the validation data<br>loss, accuracy = model.evaluate(valid_generator)<br>print(f&#39;Validation loss: {loss}, validation accuracy: {accuracy}&#39;)</pre><p>For a better understanding we can also plot loss and accuracy curves to observe the performance of the model.</p><pre>#accuracy plot</pre><pre>import matplotlib.pyplot as plt</pre><pre>plt.plot(history.history[&#39;accuracy&#39;],color=&#39;red&#39;,label=&#39;train&#39;)<br>plt.plot(history.history[&#39;val_accuracy&#39;],color=&#39;blue&#39;,label=&#39;validation&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*gwsiCFZs0isdZDWD.png" /></figure><p>Accuracy Plot</p><pre>#Loss Plot</pre><pre>plt.plot(history.history[&#39;loss&#39;],color=&#39;red&#39;,label=&#39;train&#39;)<br>plt.plot(history.history[&#39;val_loss&#39;],color=&#39;blue&#39;,label=&#39;validation&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*wdxzRkXwPhZbLsXC.png" /></figure><p>Loss Plot</p><p>From the above plots we can see that the train and validation lines are close to each other with a similar trajectory giving us a <strong>better result</strong> and also signifying the room for improvement, after all what is machine learning if not simultaneous <strong>learning</strong> and <strong>improvement</strong>.</p><h3>Conclusion</h3><p>In conclusion, transfer learning is a <strong>powerful technique</strong> in machine learning that can help us <strong>save a lot of time and computational resources</strong> when building new models.</p><p>By leveraging the features learned by pre-trained models on large datasets, we can <strong>improve</strong> the <strong>performance </strong>of our <strong>own models</strong> on smaller datasets.</p><p>This approach has been successfully applied to a wide range of tasks in computer vision, natural language processing, and other fields.</p><p>In this article, we established what transfer learning is and how it can be used to improve the accuracy of our models, by making a simple dog and cat classifier using VGG-16.</p><h3>Final Thoughts and Closing Comments</h3><p>Pre-trained models are very powerful and in order to obtain the best results from them, it’s important to fine tune our model efficiently. This is the most <strong>challenging </strong>step when it comes to <strong>creating models</strong> to <strong>fit our data</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gTz2KGpt_XvJHpws.png" /></figure><p>In the above example, I was able to achieve around 94% accuracy and I am certain we can<strong> tune hyperparameters more</strong> to achieve a better result than this even though it’s quite impressive on its own. I would suggest you all to try <strong>playing around</strong> with the <strong>fine-tuning</strong>, you never know what changes are waiting to happen.</p><p><em>Credit goes to: </em><a href="https://medium.com/@harshitaaa"><em>https://medium.com/@harshitaaa</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b9e690c7f24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning for Beginners: Introduction, Concepts, Algorithms, and Applications]]></title>
            <link>https://medium.com/@divakar1591/reinforcement-learning-for-beginners-introduction-concepts-algorithms-and-applications-d1fe90886dca?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1fe90886dca</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 04:29:27 GMT</pubDate>
            <atom:updated>2024-04-17T04:29:27.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you interested in learning about reinforcement learning but don’t know where to start? Look no further! In this article, I’ll provide an introduction to reinforcement learning (RL), explain its key concepts, and highlight some of its applications.</p><h3>Table of Contents</h3><ol><li>What is Reinforcement Learning?</li></ol><p>2. Key Concepts of Reinforcement Learning</p><ul><li>Agent</li><li>Environment</li><li>State</li><li>Action</li><li>Reward</li><li>Policy</li><li>Value Function</li><li>Q-Function</li><li>Exploration vs Exploitation</li></ul><p>3. Applications of Reinforcement Learning</p><ul><li>Gaming</li><li>Robotics</li><li>Finance</li><li>Healthcare</li></ul><p>4. Reinforcement Learning Algorithms</p><ul><li>Q-Learning</li><li>Deep Q-Network (DQN)</li><li>Policy Gradient</li><li>Actor-Critic</li></ul><p>5. Challenges</p><p>6. Future Directions</p><h3>1. What is Reinforcement Learning?</h3><p>Reinforcement learning (RL) is a branch of machine learning that focuses on enabling an agent to learn and make decisions based on rewards and punishments received from its environment. RL is different from supervised and unsupervised learning, as it doesn’t rely on pre-existing labeled datasets. Instead, the agent interacts with its environment, receives feedback in the form of rewards or punishments, and learns to optimize its actions accordingly.</p><p>RL has found applications in various fields such as gaming, robotics, finance, and healthcare. It has the potential to solve complex problems that are difficult to model mathematically or manually program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*J60yGDnmT2evRsC-.jpeg" /></figure><p>Photo by <a href="https://unsplash.com/@lenin33?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lenin Estrada</a> on <a href="https://unsplash.com/s/photos/robots?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><h3>2. Key Concepts of Reinforcement Learning</h3><p>Before diving into RL algorithms and applications, it’s essential to understand the key concepts that underpin RL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0p2yo0CHm2GK9bMO.png" /></figure><p>Main components of Reinforcement Learning</p><h3>Agent</h3><p>An agent is an intelligent system or program that interacts with an environment in order to learn how to achieve a certain goal. The agent learns by receiving feedback from the environment in the form of rewards or punishments for its actions. The ultimate goal of the agent is to learn a policy, which is a mapping from states of the environment to actions, that maximizes its long-term expected reward.</p><p>The agent typically has three main components: a policy, a value function, and a learning algorithm. The policy is the agent’s strategy for selecting actions based on the current state of the environment. The value function estimates the expected long-term reward that the agent will receive from a particular state and action. The learning algorithm updates the agent’s policy and value function based on the feedback it receives from the environment.</p><p>The agent’s behavior is characterized by the exploration-exploitation tradeoff. The agent must explore the environment to discover the best policy, but it also needs to exploit its current knowledge to maximize its expected reward. This tradeoff is often addressed using an exploration strategy, such as epsilon-greedy or Thompson sampling, that balances exploration and exploitation.</p><p>Overall, the agent is the central component of a reinforcement learning system and is responsible for learning how to interact with and navigate the environment to achieve its goals.</p><h3>Environment</h3><p>In reinforcement learning, the term “environment” refers to the external world or the system in which an agent operates. It is the environment that an agent interacts with and receives feedback from, and the agent’s goal is to learn from these interactions and optimize its behavior to achieve a specific objective.</p><p>The environment in reinforcement learning can be anything from a virtual simulation to a physical system, such as a robot or a game. The environment provides the agent with a set of observations or states, which describe the current state of the system. These observations are used by the agent to make decisions about the actions it should take, and the actions it takes to result in a change in the state of the environment.</p><p>The environment also provides feedback to the agent in the form of rewards or penalties, based on the actions it takes. These rewards serve as signals to the agent to reinforce or discourage certain behaviors, and the agent’s objective is to maximize its cumulative reward over time.</p><p>The environment plays a critical role in the success of reinforcement learning, as the agent’s ability to learn and optimize its behavior is highly dependent on the quality of the environment and the feedback it provides. Therefore, creating an accurate and effective environment is essential in developing successful reinforcement learning systems.</p><h3>State</h3><p>A state refers to the current situation or configuration of the environment that the agent is in. It includes all the relevant information that the agent needs to make decisions and take actions to maximize its rewards.</p><p>The state can be represented in various ways, such as a set of variables or features that describe the current situation, or a complete image or sensory input of the environment. The choice of representation depends on the complexity of the environment and the task at hand.</p><p>The state is important because it determines the actions that the agent can take and the rewards that it will receive. The agent’s goal is to learn a policy, which is a mapping from states to actions that maximizes its cumulative reward over time. Therefore, the state is a crucial part of the reinforcement learning process, as it forms the basis of the agent’s decision-making process.</p><h3>Action</h3><p>An action refers to a decision made by the agent in response to the state of the environment. It is a specific move or behavior that the agent takes in a particular state to transition to the next state. An action can be a choice from a set of available options or a continuous value in a range.</p><p>For example, in a game of chess, an action can be moving a piece to a particular square on the board. In a self-driving car, an action can be accelerating, braking, or turning the steering wheel. In a robotic arm, an action can be moving to a particular position or rotating in a specific direction.</p><p>The choice of action by the agent is crucial because it determines the rewards received from the environment. The goal of the agent is to learn the optimal policy that maximizes the cumulative rewards by selecting the best possible action in each state.</p><h3>Reward</h3><p>A reward is a scalar feedback signal that an agent receives from the environment after taking an action. The purpose of a reward is to indicate how well the agent is doing at achieving its goal, which is typically to maximize a cumulative measure of reward over time.</p><p>Rewards can be positive, negative, or zero, depending on whether the agent’s action led to a desirable, undesirable, or neutral outcome. The agent’s objective is to learn a policy that maximizes the expected sum of future rewards, or the expected return.</p><p>Designing the reward function is an important aspect of reinforcement learning, as it directly affects the behavior of the agent. A well-designed reward function should incentivize the agent to achieve the desired goal while avoiding unintended behaviors. However, designing reward functions that accurately capture the desired behavior can be challenging, and improper reward functions can lead to suboptimal or even undesirable behavior.</p><h3>Policy</h3><p>A policy is a function that maps an agent’s current state to an action to be taken in that state. The policy defines the agent’s behavior or strategy for choosing actions in the environment.</p><p>A policy can be deterministic, meaning that it always chooses the same action for a given state, or stochastic, meaning that it chooses actions probabilistically. In a stochastic policy, the probabilities of taking each action in a given state are specified by the policy.</p><p>The goal of reinforcement learning is often to learn an optimal policy that maximizes the expected cumulative reward over time. This is typically achieved through trial and error, where the agent interacts with the environment, observes the resulting rewards and transitions to new states, and updates its policy based on the observed outcomes.</p><h3>Value Function</h3><p>A value function is a function that estimates the value of a state or state-action pair. It represents how good a particular state or action is in terms of achieving the agent’s goal. The value function is a critical component of many reinforcement learning algorithms because it guides the agent’s decision-making process.</p><p>There are two types of value functions in reinforcement learning: state-value function and action-value function.</p><ul><li>State-value function: It predicts how much reward an agent can expect to receive from a given state. The state-value function is denoted by V(s) and is defined as the expected cumulative reward that an agent can receive starting from a given state s and following the current policy.</li><li>Action-value function: It predicts how much reward an agent can expect to receive by taking a particular action in a given state. The action-value function is denoted by Q(s,a) and is defined as the expected cumulative reward that an agent can receive starting from state s, taking action a, and following the current policy.</li></ul><p>The value function is estimated using past experiences and updated through iterative learning methods, such as temporal difference learning or Monte Carlo methods. Accurate estimation of the value function is essential for the agent to make optimal decisions and maximize its long-term rewards.</p><h3>Q-Function</h3><p>The Q function (also known as the action-value function) is a mathematical function that takes in a state-action pair as input and outputs the expected long-term reward of taking that action in that state and following a given policy thereafter.</p><p>The Q function is a crucial component in many reinforcement learning algorithms, such as Q-learning and SARSA, as it allows the agent to estimate the quality of different actions in different states. By learning the Q function, the agent can then choose actions that maximize the expected long-term reward, which is the goal of many reinforcement learning tasks.</p><p>The Q function is often represented as a table or a function approximator, such as a neural network, that is learned through experience and interaction with the environment. The process of learning the Q function involves iteratively updating the Q values based on the observed rewards and transitions until the estimates converge to the true values.</p><h3>Exploration vs Exploitation</h3><p>Exploration and exploitation are two important concepts in reinforcement learning that deal with how an agent should choose actions to take in an environment.</p><p>Exploration refers to the agent’s behavior of trying out new actions in order to learn more about the environment and potentially find better actions that lead to higher rewards. Exploitation, on the other hand, refers to the agent’s behavior of choosing the actions that have already been tried and proven to lead to high rewards.</p><p>The challenge in reinforcement learning is to balance exploration and exploitation in order to maximize the agent’s long-term reward. If the agent only exploits known good actions, it may miss out on better actions that it hasn’t tried yet. On the other hand, if the agent only explores new actions, it may not accumulate enough reward to perform well in the long run.</p><p>Various exploration strategies have been proposed, such as ε-greedy, softmax, and Upper Confidence Bound (UCB), among others. These strategies use different ways to balance exploration and exploitation, and the choice of strategy depends on the specific problem at hand.</p><h3>3. Applications of Reinforcement Learning</h3><p>Reinforcement learning has found numerous applications in various fields. Here are some examples:</p><h3>Gaming</h3><p>Reinforcement learning has been applied to various games, from classic board games like chess and Go to modern video games like Dota 2 and StarCraft II. In these games, an agent learns to make decisions and compete against human players or other agents.</p><h3>Robotics</h3><p>Reinforcement learning has been used in robotics to enable robots to learn to navigate environments, manipulate objects, and perform complex tasks. In these applications, an agent learns from feedback received through sensors and actuators.</p><h3>Finance</h3><p>Reinforcement learning has found applications in finance, including algorithmic trading, portfolio optimization, and fraud detection. In these applications, an agent learns to make decisions based on market data and financial indicators.</p><h3>Healthcare</h3><p>Reinforcement learning has been used in healthcare to optimize treatment plans and drug dosages. In these applications, an agent learns from patient data and medical records to make decisions that maximize patient outcomes.</p><h3>4. Reinforcement Learning Algorithms</h3><p>There are several algorithms used in reinforcement learning. Here are some of the most commonly used ones:</p><h3>Q-Learning</h3><p>Q-learning is a model-free, off-policy reinforcement learning algorithm used to find the optimal action-selection policy for any given Markov decision process (MDP). In Q-learning, the agent learns an action-value function Q(s,a) that gives the expected utility of taking action a, in state s, and following the optimal policy thereafter.</p><p>The algorithm uses an iterative process to update the Q-values of each state-action pair based on the observed rewards received from the environment. The updates are made using the Bellman equation, which expresses the expected value of the current state as the sum of the immediate reward and the expected value of the next state. By iteratively updating the Q-values, Q-learning converges to the optimal Q-function and thus the optimal policy.</p><p>One of the key advantages of Q-learning is that it can learn optimal policies in environments with large state spaces and stochastic rewards. However, it requires sufficient exploration of the state-action space to avoid getting stuck in suboptimal policies, which can be challenging in some environments. Additionally, Q-learning assumes that the state transition and reward functions are unknown, which may not always be the case in practice.</p><h3>Deep Q-Network (DQN)</h3><p>Deep Q-Network (DQN) is a popular deep reinforcement learning algorithm introduced by DeepMind in 2013. It extends the Q-learning algorithm to work with high-dimensional input spaces by using a deep neural network to approximate the Q-function.</p><p>In DQN, the agent uses a neural network to estimate the Q-values of each possible action in a given state. The network takes the state as input and outputs the estimated Q-values for each possible action. The agent then selects the action with the highest estimated Q-value to take.</p><p>To train the DQN, the agent uses experience replay and a target network. Experience replay is a technique where the agent stores transitions from the environment in a buffer and samples random batches of these transitions to train the neural network. This helps to break the correlation between consecutive samples and improve the stability of the learning process. The target network is a separate network used to generate the Q-value targets for training. The weights of the target network are frozen and only updated periodically with the weights of the main network, which helps to stabilize the learning process.</p><p>DQN has been applied successfully to a variety of tasks, including playing Atari games and controlling robotic systems.</p><h3>Policy Gradient</h3><p>Policy gradient algorithms are a class of reinforcement learning methods that learn a policy function by directly optimizing the objective function that measures the expected cumulative reward obtained by following the policy. The policy function maps states to actions, and the goal of the algorithm is to find the policy that maximizes the expected cumulative reward over a long-term horizon.</p><p>Policy gradient methods use gradient descent to iteratively update the policy parameters to maximize the expected cumulative reward. The policy is typically represented as a neural network, where the input is the state and the output is a probability distribution over the possible actions. The gradient of the objective function is computed with respect to the policy parameters, and the parameters are updated to move in the direction of the gradient.</p><p>One popular policy gradient algorithm is the REINFORCE algorithm, which is a Monte Carlo algorithm that estimates the gradient of the expected reward using samples from the current policy. Another popular algorithm is the Actor-Critic algorithm, which combines policy gradient with value function estimation. The Actor-Critic algorithm uses a neural network to represent the policy and another neural network to represent the value function. The policy network is updated using the policy gradient, while the value network is updated using the temporal difference (TD) error, which is the difference between the predicted and actual rewards.</p><p>Policy gradient methods have several advantages over value-based methods like Q-learning, including the ability to learn stochastic policies, handling of continuous action spaces, and better convergence properties. However, they can also suffer from high variance and slow convergence, especially in high-dimensional state spaces.</p><h3>Actor-Critic</h3><p>Actor-critic algorithms are a type of reinforcement learning algorithm that combine the advantages of both policy-based and value-based methods. The actor-critic algorithm involves two neural networks, an actor network, and a critic network.</p><p>The actor-network is responsible for selecting actions based on the current state of the environment. It uses the policy gradient method to update its parameters and improve its performance. The critic network, on the other hand, evaluates the value of the current state and action pair. It uses the temporal difference learning method to update its parameters and learn from the feedback received from the environment.</p><p>The actor-critic algorithm uses the critic network to estimate the value of an action in a given state and then uses this estimate to update the policy of the actor-network. This allows the algorithm to balance exploration and exploitation in a more efficient manner, and improve the overall performance of the agent.</p><p>Actor-critic algorithms can be further divided into several subtypes, including advantage actor-critic (A2C), asynchronous advantage actor-critic (A3C), and deep deterministic policy gradient (DDPG). These algorithms have been successfully applied to a wide range of tasks, including robotics, game-playing, and natural language processing.</p><h3>5. Challenges</h3><p>Reinforcement learning faces several challenges, including:</p><ol><li>Exploration vs Exploitation: Finding the right balance between exploration and exploitation is one of the fundamental challenges in reinforcement learning. The agent must explore the environment to learn the optimal policy while also exploiting the current knowledge to maximize the expected reward.</li><li>Credit assignment: In some cases, the reward received by the agent may not reflect the quality of the actions taken in the past. This makes it difficult to assign credit to the actions that led to the reward.</li><li>Generalization: Reinforcement learning often requires generalizing learned policies across different environments or tasks. This can be challenging because the agent must be able to adapt to new situations without forgetting what it has already learned.</li><li>Function approximation: In many reinforcement learning problems, the state and action spaces are too large to store in memory or represent exactly. Thus, function approximation techniques are used to estimate value functions or policies. However, these approximations can introduce errors that affect the quality of the learned policies.</li><li>Delayed rewards: The rewards received in reinforcement learning are often delayed, meaning that the agent must learn to associate current actions with future rewards. This can make it challenging to determine the best action to take in the current state.</li><li>Sample inefficiency: Reinforcement learning algorithms typically require a large number of interactions with the environment to learn an optimal policy. This can be time-consuming and costly in some real-world applications where interactions with the environment are limited.</li></ol><h3>6. Future Directions</h3><p>Reinforcement learning is a rapidly evolving field with many exciting developments and future directions. Some of the potential areas of focus for future research and development include:</p><ol><li>Multi-agent reinforcement learning: Many real-world applications of reinforcement learning involve multiple agents interacting with each other, such as in autonomous driving or game theory. Developing algorithms and techniques that can handle these complex interactions is a promising direction for future research.</li><li>Sample efficiency: One of the biggest challenges in reinforcement learning is the amount of data required to train an agent. Developing algorithms that can learn effectively from fewer samples could significantly increase the applicability of reinforcement learning in real-world scenarios.</li><li>Safe and ethical RL: As reinforcement learning is applied to increasingly complex and important tasks, ensuring that agents behave safely and ethically becomes more critical. Future research could focus on developing techniques to ensure that agents behave in a manner consistent with ethical and legal standards.</li><li>Transfer learning: Transfer learning involves leveraging knowledge gained from one task to help an agent learn more efficiently in a new, related task. Developing techniques that allow for effective transfer learning could greatly increase the efficiency and effectiveness of reinforcement learning algorithms.</li><li>Explainability and interpretability: As reinforcement learning is applied in more critical domains, such as healthcare or finance, it becomes more important to understand why agents are making particular decisions. Developing techniques to explain and interpret the decisions of reinforcement learning agents is a promising direction for future research.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1fe90886dca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TensorFlow Hub: Home to 100s of pre-trained models]]></title>
            <link>https://medium.com/@divakar1591/tensorflow-hub-home-to-100s-of-pre-trained-models-566b92d22c52?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/566b92d22c52</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 14:04:17 GMT</pubDate>
            <atom:updated>2024-04-16T14:04:17.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Detailed explanation about TensorFlow Hub, Installation, and Usage with an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OTvbBTh85D3C59eB.jpeg" /></figure><p>Photo by <a href="https://unsplash.com/es/@lhgerona?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lyman Hansel Gerona</a> on <a href="https://unsplash.com/s/photos/artificial-intelligence?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><p><strong>To access TensorFlow Hub click here </strong>— <a href="https://www.tensorflow.org/hub">https://www.tensorflow.org/hub</a></p><h3>Introduction</h3><p><a href="https://www.tensorflow.org/hub">TensorFlow Hub</a> is a library for the publication, discovery, and consumption of reusable models in TensorFlow. It provides a simple way to use pre-trained models for a variety of tasks, such as image classification, text analysis, and more.</p><p>TensorFlow Hub provides a wide range of pre-trained models developed by researchers and engineers from TensorFlow and the broader machine-learning community.</p><p>Here are some examples of the types of models available in TensorFlow Hub:</p><ol><li>Image classification models: These models are trained on large datasets of labeled images and can classify images into various categories. Some popular image classification models in TensorFlow Hub include Inception, MobileNet, ResNet, and VGG.</li><li>Object detection models: These models can detect and localize objects within an image. Some popular object detection models in TensorFlow Hub include Faster R-CNN and YOLO.</li><li>Natural language processing (NLP) models: These models can analyze text and perform tasks such as sentiment analysis, text classification, and language translation. Some popular NLP models in TensorFlow Hub include BERT and ALBERT.</li><li>Speech recognition models: These models can transcribe speech into text. Some popular speech recognition models in TensorFlow Hub include wav2vec2, spice, and yamnet.</li><li>Generative models: These models can generate new content, such as images or text, based on input data. Some popular generative models in TensorFlow Hub include Progressive GAN and BigGAN.</li><li>Transfer learning models: These models are pre-trained on large datasets and can be fine-tuned for a specific task using a smaller dataset. Transfer learning models in TensorFlow Hub can be used for various tasks such as image classification, object detection, segmentation, and text analysis.</li></ol><p>TensorFlow Hub provides a convenient way to access these pre-trained models and use them for various machine-learning tasks. The models are available in various formats, such as TensorFlow SavedModel, Keras models, and TensorFlow.js models, making it easy to integrate them into your machine learning pipeline.</p><h3>Installation and Usage</h3><ol><li>Install TensorFlow and TensorFlow Hub:</li></ol><p>Before using TensorFlow Hub, you need to install both TensorFlow and TensorFlow Hub. You can install them using pip in your command prompt or terminal:</p><pre>pip install tensorflow<br>pip install tensorflow-hub</pre><p>This will install the latest versions of TensorFlow and TensorFlow Hub.</p><p><strong>Load a pre-trained model from TensorFlow Hub:</strong></p><p>You can browse the available models on the TensorFlow Hub website (<a href="https://tfhub.dev/">https://tfhub.dev/</a>).</p><p>To load a pre-trained model, you first need to get its URL from the TensorFlow Hub website. For example, if you want to use an EfficientNet_v2_s model pre-trained on ImageNet 1K dataset for image classification, you can use the following URL:</p><pre>module_url = &quot;https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_s/classification/2&quot;</pre><p>Next, you can create a Keras layer using the hub.KerasLayer class and the URL:</p><pre>import tensorflow as tf<br>import tensorflow_hub as hub</pre><pre>feature_extractor = hub.KerasLayer(module_url, input_shape=(384,384,3))</pre><p>In this example, we are creating a Keras layer that will be used to extract features from images. The input_shape argument specifies the shape of the input images, which in this case is 384x384 pixels with 3 color channels (RGB).</p><ol><li>Use the pre-trained model to perform a task:</li></ol><p>Once you have loaded the pre-trained model, you can use it to perform a specific task. For example, if you take a random image of a tiger, you can do the following:</p><pre>import numpy as np<br>import PIL.Image as Image<br>import matplotlib.pyplot as plt</pre><pre>image = Image.open(&quot;image.jpg&quot;).resize((384,384))<br>plt.imshow(image)<br>plt.show()<br>image_array = np.array(image) / 255.0<br>image_batch = np.expand_dims(image_array, axis=0)</pre><pre>features = feature_extractor(image_batch)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/0*HAF6w6cZTfoaGQEu.png" /></figure><p>In this example, we are loading an image from a file, resizing it to 384x384 pixels, displaying the image, converting it to a NumPy array, and normalizing it to values between 0 and 1. We then add an extra dimension to the array to create a batch of images (as the pre-trained model expects a batch of images as input). Finally, we use the pre-trained EfficientNet_v2_s model to classify the image.</p><pre>labels_file = &quot;https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt&quot;</pre><pre>#download labels and creates a maps<br>downloaded_file = tf.keras.utils.get_file(&quot;labels.txt&quot;, origin=labels_file)</pre><pre>classes = []</pre><pre>with open(downloaded_file) as f:<br>  labels = f.readlines()<br>  classes = [l.strip() for l in labels]</pre><p>This code snippet uses the TensorFlow library to download a text file containing the ImageNet dataset labels from a Google Cloud Storage bucket. The URL for the text file is stored in the labels_filevariable.tf.keras.utils.get_file() the function is then used to download the file from the URL specified labels_file and saves it locally with the name &quot;labels.txt&quot;. The get_file() function caches the file locally, so if the same URL is requested again, the locally cached file will be used instead of downloading the file again.</p><p>After the file is downloaded, the code opens it and reads its contents using open() function. The readlines() function returns a list of strings, with each string representing a line from the file. The code then removes any leading or trailing whitespace from each line using the strip() function and stores the cleaned-up labels in a list called classes.</p><p>The resulting classes list contains the labels for the 1001 classes (1000 main classes + 1 class for ‘background’) of the ImageNet dataset. This list can be used to map the output of a neural network to the corresponding label for display or further analysis.</p><pre>top_5 = tf.argsort(features, axis=-1, direction=&quot;DESCENDING&quot;)[0][:5].numpy()</pre><pre>features_array = np.array(features)<br>features_flatten = features_array.flatten()</pre><pre>for i, item in enumerate(top_5):<br>  class_index = item +1<br>  line = classes[class_index].upper()<br>  prob = round(features_flatten[item]*10,2)<br>  print(f&#39;Predicted class : {line} : with probability : {prob}%&#39;)</pre><p>Output:</p><pre>Predicted class : TIGER : with probability : 90.79%<br>Predicted class : TIGER CAT : with probability : 77.36%<br>Predicted class : JAGUAR : with probability : 37.36%<br>Predicted class : LYNX : with probability : 29.64%<br>Predicted class : LEOPARD : with probability : 25.47%</pre><p>This code snippet uses the TensorFlow library to predict the top 5 most likely ImageNet classes for an input image.</p><p>The variable features contains the output of a neural network model for an input image. The tf.argsort() function is used to sort the output values in descending order and returns the indices of the sorted values. The top 5 indices are selected by slicing the resulting tensor with [0][:5] and then converted to a NumPy array using the .numpy() method.</p><p>The features_array variable is created by converting the features tensor to a NumPy array. The features_flatten variable is created by flattening the features_array into a 1D array.</p><p>A for loop is then used to iterate over the top 5 indices. For each index, the corresponding ImageNet class label is retrieved from the classes list by adding 1 to the index (since the indices are 0-based, but the class labels are 1-based) and converting the label to uppercase.</p><p>Finally, the predicted class label and its corresponding probability are printed to the console using the print() function. The output will show the predicted class and its corresponding probability for each of the top 5 most likely ImageNet classes.</p><p><strong>Fine-tune the pre-trained model (optional):</strong></p><p>If the pre-trained model doesn’t fully meet your requirements, you can fine-tune it by adding new layers or retraining it on a new dataset. Here’s an example of how to fine-tune the EfficientNet_v2_s model for a new classification task:</p><pre>import tensorflow as tf<br>import tensorflow_hub as hub<br>from tensorflow.keras import layers</pre><pre>model_url = &quot;https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_s/feature_vector/2&quot;<br>model = hub.KerasLayer(model_url, trainable=True)</pre><pre>num_classes = 10 #just an example</pre><pre>fine_tuning_model = tf.keras.Sequential([<br>    model,<br>    layers.Dense(num_classes, activation=&#39;softmax&#39;)<br>])</pre><pre>fine_tuning_model.compile(<br>    optimizer=tf.keras.optimizers.Adam(),<br>    loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),<br>    metrics=[tf.keras.metrics.CategoricalAccuracy()]<br>)</pre><pre>epochs = 10<br>batch_size = 32</pre><pre>fine_tuning_model.fit(<br>    train_data,<br>    epochs=epochs,<br>    batch_size=batch_size,<br>    validation_data=val_data<br>)</pre><pre>test_loss, test_acc = fine_tuning_model.evaluate(test_data)<br>print(&#39;Test accuracy:&#39;, test_acc)</pre><p>In this example, we create a new model by adding a new dense layer for classification. We then compile the model with an optimizer, a loss function, and metrics. Finally, we train the model on a new dataset for a specified number of epochs.</p><h3>Conclusion</h3><p>These are the basic steps for the installation and usage of TensorFlow Hub. TensorFlow Hub provides many more features, such as caching, versioning, and more, so be sure to check out the documentation for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566b92d22c52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about ‘Attention’ and ‘Transformers’ — In-depth Understanding — Part 2]]></title>
            <link>https://medium.com/@divakar1591/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-2-b2502abee987?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2502abee987</guid>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 09:13:40 GMT</pubDate>
            <atom:updated>2024-03-26T12:17:14.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>All you need to know about ‘Attention’ and ‘Transformers’ — In-depth Understanding — Part 2</h3><h4>Attention, Self-Attention, Multi-head Attention, Masked Multi-head Attention, Transformers, BERT, and GPT</h4><p>In the previous story, I have explained what is the Attention mechanism, and some important keywords and blocks associated with Transformers, such as Self Attention, Query, Keys and Values, and Multi-head Attention.</p><h4>To understand more about these topics please visit Part 1 of this story — <a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021">All you need to know about ‘Attention’ and ‘Transformers’ — In-depth Understanding — Part 1</a>.</h4><p>In this part, I will explain how these blocks of Attention help create the Transformer network and discuss in detail all the blocks in the network.</p><h3>Contents:</h3><ol><li><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#4c16">Challenges with RNNs and how Transformer models can help overcome those challenges</a> (Covered in Part 1)</li><li><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#8607">The Attention Mechanism</a> — Self Attention, Query, Keys, Values, Multi-Head Attention (Covered in Part 1)</li><li>The Transformer Network</li><li>Basics of GPT (To be covered in Part 3)</li><li>Basics of BERT (To be covered in Part 3)</li></ol><h3>3. The Transformer Network</h3><p>Paper — <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a> (2017)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*jtO7J2GKFaKoA-FS.png" /></figure><p>Figure 1. The Transformer Network (Source: Image from the original paper)</p><p>Figure 1 shows the Transformer network. This network has replaced RNNs as the best model for NLP and even in computer vision (<a href="https://medium.com/towards-data-science/are-transformers-better-than-cnns-at-image-recognition-ced60ccc7c8"><em>Vision Transformers</em></a>).</p><p>The network contains two parts — The encoder and the decoder.</p><p>In machine translation, the encoder is used to encode the initial sentence and the decoder is used to produce a translated sentence. The encoder of the transformer can process the whole sentence in parallel, making it much faster and better than RNNs — which process one word of the sentence at a time.</p><h3>3.1 The Encoder Blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*1RPiVGVw7P58FMAr.png" /></figure><p>Figure 2. The Encoder part of the transformer network (Source: image from the original paper)</p><p>The encoder network begins with the inputs. Here the entire sentence is fed at once. They are then embedded at the ‘<strong>input embedding</strong>’ block. Then a ‘<strong>positional encoding</strong>’ is added to each word in a sentence. This encoding is essential in understanding the position of each word in a sentence. Without positional embedding, the model will treat the entire sentence as just a bag full of words without having any sequence or meaning.</p><p><strong>In detail:</strong></p><p><strong>3.1.1 Input embedding</strong> — The word ‘dog’ in a sentence can use the embedding space to obtain a vector embedding. Embedding is just converting a word in any language to its vector representation. An example is shown in figure 3. In the embedding space, similar words have similar embeddings, for example, the word ‘cat’ and the word ‘kitty’ will fall very close in the embedding space, and the word ‘cat’ and ‘emotion’ will fall further away in the space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*K2S4Oab8N_zJWq1v.png" /></figure><p>Figure 3. Input embedding (Source: image created by author)</p><p><strong>3.1.2 Positional encoding</strong></p><p>A word in different sentences can have different meanings. For example, the word dog in a. I own a cute dog (animal/pet — position 5) and b. What a lazy dog you are! (worthless -position 4), have different meanings. To help with that positional encodings come in. It is a vector that gives information based on the context and position of the word in a sentence.</p><p>In any sentence, the words come one after the other to have a significant meaning. If the words in the sentence are jumbled, then the sentence will have no meaning. But when a transformer loads the sentences, it does not do so in sequential order but loads them in parallel. Since the transformer architecture does not include the order of the words while loading in parallel, we must explicitly define the position of the words in a sentence. This helps the transformer to understand that one word comes after the other in a sentence. This is where positional embeddings come in handy. This is sort of a vector encoding defining the position of a word. This positional embedding is added to the input embedding before going into the attention network. Figure 4 gives an intuitive understanding of the input embedding and the positional embedding before it is fed into the attention network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*u0IhnWjvQJiWfv7h.png" /></figure><p>Figure 4. Intuitive understanding of positional embedding (Source: image created by author)</p><p>There are multiple ways of defining these positional embeddings. For example in the original paper — <a href="https://arxiv.org/abs/1706.03762">Attention is All You Need</a>, the authors used an alternating sine and cosine function to define the embeddings, as shown in figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aQ4yLPsdjat0b2IT.png" /></figure><p>Figure 5. Positional embedding used in the original paper ( Source: image from the original paper)</p><p>Though this embedding works well on text data, this embedding does not work with image data. So there can be multiple ways of embedding the position of an object ( text/image ), and they can be fixed or learned during training. The basic idea is that this embedding allows the transformer architecture to understand the position of the word in a sentence, and not mess up the meaning by jumbling the words.</p><p>After the word/input embedding and positional embedding is complete, the embeddings then flow into the most important part of the encoder which contains the two important blocks — a ‘<strong>multi-head attention</strong>’ block and a ‘<strong>feed-forward</strong>’ network.</p><p><strong>3.1.3 Multi-Head Attention</strong></p><p>This is the main block where the magic happens. To understand Multi-Head Attention please visit this link — <a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#9c93">2.4 Multi-Head Attention</a>.</p><p>As input, this block receives a vector (the sentence) that contains a sub-vector (words in a sentence). The multi-head attention then computes the attention between every position with every other position of the vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*D26zfpWGGTL4UUxU.png" /></figure><p>Figure 6. Scaled Dot-product Attention (Source: image from the original paper)</p><p>The figure above shows scaled dot-product attention. This is exactly the same as self-attention with an addition of two blocks (Scale and Mask). To know in detail about Sef-Attention please go to this link — <a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#62ce">2.1 Self-Attention</a>.</p><p>Scaled Attention, as seen in figure 6, is exactly the same, except it adds a scale after the first matrix multiplication (Matmul).</p><p>The scaling is shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*m2jXgS4G_-Lzczge.png" /></figure><p>The output after scale goes into a Mask layer. This is an optional layer, useful for machine translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KsnRCFVWSrgt-CUC.png" /></figure><p>Figure 7. The Attention block (Source: image created by author)</p><p>Figure 7 shows the neural network representation of an attention block. The word embeddings are first passed into some linear layers. These linear layers do not have a ‘bias’ term, and hence are nothing but matrix multiplications. One of these layers is denoted as ‘keys’, the other as ‘queries’, and the last one as ‘values’. If a matrix multiplication is performed between the keys and the queries and is then normalized, we get the weights. These weights are then multiplied by the values, and summed up, to get the final attention vector. This block can now be used in a neural network and is known as the Attention block. Multiple such attention blocks can be added to provide more context. And the best part is, that we can get a gradient backpropagating to update the attention block (weights of keys, queries, values).</p><p>Multi-head attention takes in multiple keys, queries, and values, feeds it through multiple scaled dot-product attention blocks, and finally concatenates the attention to give us a final output. This is shown in figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*V1qJG9Uos7N58yOV.png" /></figure><p>Figure 8. Multi-Head Attention (source: image created by author)</p><p>A simpler explanation: The main vector (sentence) contains sub-vectors (words) — with each word having a positional embedding. The attention computation treats each word as a ‘<em>query</em>’ and finds some ‘<em>keys</em>’ that correspond to some other words in the sentence, and then take a convex combination of the corresponding ‘<em>values</em>’. In multi-head attention, multiple values, queries, and keys are chosen which provides multiple attention (better word embedding with context). These multiple attentions are concatenated to give a final attention value (combination of context for all the words from all the multiple attentions), which works much better than using a single attention block.</p><p>Insimple words, the idea of multi-head attention is to take a word embedding, combine it with some other word embedding (or multiple words) using attention (or multiple attentions) to produce a better embedding for that word (embedding with a lot more context of the surrounding words).</p><p><em>The idea is to compute multiple attentions per query with different weights.</em></p><p><strong>3.1.4 Add &amp; Norm and Feed-Forward</strong></p><p>The next block is the ‘<strong>Add &amp; Norm</strong>’ which takes in a residual connection of the original word embedding, adds it to the embedding from the multi-head attention, and then normalizes it to have zero mean and variance 1.</p><p>This is fed to a ‘<strong>feed forward</strong>’ block which also has an ‘add &amp; norm’ block at its output.</p><p>The whole multi-head attention and feed-forward blocks are repeated n times (hyperparameters), in the encoder block.</p><h3>3.2 The Decoder Blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*L2f9U99dhdEobFsV.png" /></figure><p>Figure 9. The Decoder part of the Transformer network (Souce: Image from the original paper)</p><p>The output of the encoder is again a sequence of embeddings, one embedding per position, where each position embedding contains not only the embedding of the original word at the position but also information about other words, that it learned using attention.</p><p>This is then fed into the decoder part of the transformer network, as seen in figure 9. The purpose of the decoder is to produce some output. In the paper, Attention is All You Need, this decoder was used for sentence translation (say from English to French). So the encoder will take in the English sentence, and the decoder will translate it to French. In other applications, the decoder part of the network is not necessary, and hence I will not elaborate on it too much.</p><p>Steps in decoder block —</p><ol><li>In sentence translation, the decoder block takes in the French sentence (for English to French translation). Like the encoder, here we add a word embedding and a positional embedding and feed it to the multi-head attention block.</li></ol><p>2. The self-attention block will generate an attention vector for each word in the French sentence, to show how much one word is related to the other in the sentence.</p><p>3. This attention vector from the French sentence is then compared with the attention vectors from the English sentence. This is the part where the English to French word mappings happen.</p><p>4. In the final layers, the decoder predicts the translation of the English word to the best probable French word.</p><p>5. The whole process is repeated multiple times to get a translation of the entire text data.</p><p>The blocks being used for each of the above steps are shown in figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qA_SJtqOMrC7WyK2.png" /></figure><p>Figure 10. The function of different decoder blocks in sentence translation (Source: image created by author)</p><p>There is one block that is new in the decoder — the Masked Multi-head Attention. All the other blocks, we have already seen previously in the encoder.</p><p><strong>3.2.1 Masked Multi-head Attention</strong></p><p>This is a multi-head attention block where some values are masked. The probabilities of the masked values are nullified or not selected.</p><p>For example, while decoding, the output value should only depend on previous outputs and not future outputs. Then we mask the future outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1cQtUWscIEuuQ6M7.png" /></figure><h3>3.3 Results and Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9sZF6Ol_XM5zoXhG.png" /></figure><p>Figure 11. Results (source: image from the original paper)</p><p>In the paper, a comparison was done for language translation between English to German and English to French, with other state-of-the-art language models. BLEU is a measure used in language translation comparison. From figure 11, we see that the big Transformer model obtains a higher BLEU score for both translation tasks. What they also improve on significantly is the training cost.</p><p><em>In summary, a Transformer model can reduce computation costs while still obtaining state-of-the-art results.</em></p><p>In this part, I have explained the encoder and decoder blocks of a Transformer network, and how each block is used in language translation. In the next and final part (Part 3), I will discuss some important Transformer networks that have become extremely famous in recent times, such as BERT (Bidirectional Encoder Representations from Transformers) and GPT (General Purpose Transformer).</p><p><strong>Reference :</strong> <a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-2-bf2403804ada">https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-2-bf2403804ada</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2502abee987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about ‘Attention’ and ‘Transformers’ — In-depth Understanding — Part 1]]></title>
            <link>https://medium.com/@divakar1591/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-c4fb0ee79646?source=rss-d1d83e7ca52c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4fb0ee79646</guid>
            <category><![CDATA[attention-mechanism]]></category>
            <dc:creator><![CDATA[Learn AI]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 18:48:48 GMT</pubDate>
            <atom:updated>2023-04-25T18:48:48.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>All you need to know about ‘Attention’ and ‘Transformers’ — In-depth Understanding — Part 1</h3><h3>Attention, Self-Attention, Multi-head Attention, and Transformers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z2tHztqB66Y1F-Xb.jpeg" /></figure><p>Figure 1. Source: Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arseny Togulev</a> on <a href="https://unsplash.com/s/photos/transformers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><p>This is a long article that talks about almost everything one needs to know about the Attention mechanism including Self-Attention, Query, Keys, Values, Multi-Head Attention, Masked-Multi Head Attention, and Transformers including some details on BERT and GPT. I have hence divided the article into two parts. In this article, I cover all the Attention blocks, and in the next story, I will dive into the Transformer Network architecture.</p><h3>Contents:</h3><ol><li><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#4c16">Challenges with RNNs and how Transformer models can help overcome those challenges</a></li><li><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#8607">The Attention Mechanism</a></li></ol><p><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#62ce">2.1 Self-Attention</a></p><p><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#fb36">2.2 Query, Key, and Values</a></p><p><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#d43e">2.3 Neural network representation of Attention</a></p><p><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021#9c93">2.4 Multi-Head Attention</a></p><p>3. Transformers (Continued in next story)</p><p><strong>Introduction</strong></p><p>The attention mechanism was first used in 2014 in computer vision, to try and understand what a neural network is looking at while making a prediction. This was one of the first steps to try and understand the outputs of Convolutional Neural Networks (CNNs). In 2015, attention was used first in Natural Language Processing (NLP) in Aligned Machine Translation. Finally, in 2017, the attention mechanism was used in Transformer networks for language modeling. Transformers have since surpassed the prediction accuracies of Recurrent Neural Networks (RNNs), to become state-of-the-art for NLP tasks.</p><h3>1. Challenges with RNNs and how Transformer models can help overcome those challenges</h3><p><strong>1.1<em> RNN problem 1 </em></strong>— Suffers issues with long-range dependencies. RNNs do not work well with long text documents.</p><p><strong>Transformer Solution</strong> — Transformer networks almost exclusively use attention blocks. Attention helps to draw connections between any parts of the sequence, so long-range dependencies are not a problem anymore. With transformers, long-range dependencies have the same likelihood of being taken into account as any other short-range dependencies.</p><p><strong>1.2. <em>RNN problem 2 </em></strong>— Suffers from gradient vanishing and gradient explosion.</p><p><strong>Transformer Solution<em> </em></strong>— There is little to no gradient vanishing or explosion problem. In Transformer networks, the entire sequence is trained simultaneously, and to build on that only a few more layers are added. So gradient vanishing or explosion is rarely an issue.</p><p><strong>1.3.<em> RNN problem 3</em></strong> — RNNs need larger training steps to reach a local/global minima. RNNs can be visualized as an unrolled network that is very deep. The size of the network depends on the length of the sequence. This gives rise to many parameters, and most of these parameters are interlinked with one another. As a result, the optimization requires a longer time to train and a lot of steps.</p><p><strong>Transformer Solution </strong>— Requires fewer steps to train than an RNN.</p><p><strong>1.4. <em>RNN problem 4</em> </strong>— RNNs do not allow parallel computation. GPUs help to achieve parallel computation. But RNNs work as sequence models, that is, all the computation in the network occurs sequentially and can not be parallelized.</p><p><strong>Transformer Solution </strong>— No recurrence in the transformer networks allows parallel computation. So computation can be done in parallel for every step.</p><h3>2. The Attention Mechanism</h3><h3>2.1 Self-Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*7R69WTQAU4F7Bpab.png" /></figure><p>Figure 2. Example to explain self-attention (Source: Image created by author)</p><p>Consider the sentence — ”<em> Bark is very cute and he is a dog</em>”. This sentence has 9 words or tokens. If we just consider the word ‘he’ in the sentence, we see that ‘and’ and ‘is’ are the two words in close proximity to it. But these words do not give the word ‘he’ any context. Rather the words ‘Bark’ and ‘dog’ are much more related to ‘he’ in the sentence. From this, we understand that proximity is not always relevant but context is more relevant in a sentence.</p><p>When this sentence is fed to a computer, it considers each word as a token <em>t, </em>and each token has a word embedding<em> V</em>. But these word embeddings have no context. So the idea is to apply some kind of weighing or similarity to obtain final word embedding <em>Y</em>, which has more context than the initial embedding <em>V</em>.</p><p>In an embedding space, similar words appear closer together or have similar embeddings. Such as the word ‘king’ will be more related to the word ‘queen’ and ‘royalty’, than with the word ‘zebra’. Similarly, ‘zebra’ will be more related to ‘horse’ and ‘stripes’, than with the word ‘emotion’. To know more about embedding space, please visit this video by Andrew Ng (<a href="https://www.youtube.com/watch?v=36XuT5c9qvE">NLP and Word Embeddings</a>).</p><p>So, intuitively, if the word ‘king’ appears at the beginning of the sentence, and the word ‘queen’ appears at the end of the sentence, they should provide each other with better context. We use this idea to find the weight vectors <em>W, </em>by multiplying (dot product) the word embeddings together to gain more context. So, in the sentence <em>Bark is very cute and he is a dog, </em>instead of using the word embeddings as it is, we multiply the embedding of each word with one another. Figure 3 should illustrate this better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*tTYpROQLK4r7eW40.png" /></figure><p>Figure 3. Finding weights and Obtaining final embedding (Source: Image created by author)</p><p>As we see in figure 3, we first find the weights by multiplying (dot product) the initial embedding of the first word with the embedding of all other words in the sentence. These weights (W11 to W19) are also normalized to have a sum of 1. Next, these weights are multiplied with the initial embeddings of all the words in the sentence.</p><p><em>W11 V1 + W12 V2 + …. W19 V9 = Y1</em></p><p>W11 to W19 are all weights that have the context of the first word V1. So when we are multiplying these weights to each word, we are essentially reweighing all the other words towards the first word. So in a sense, the word ‘<em>Bark</em>’ is now tending more towards the words ‘<em>dog</em>’ and ‘<em>cute</em>’, rather than the word that comes right after it. And this, in a way gives some context.</p><p>This is repeated for all words so that each word gets some context from every other word in the sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qPsRMhCX836_0EbL.png" /></figure><p>Figure 4. Pictorial representation of the above steps (Source: image created by author)</p><p>Figure 4 gives a better understanding of the above steps to obtain Y1, using a pictorial diagram.</p><p>What is interesting here is that no weights are trained, the order or proximity of the words have no influence on each other. Also, the process has no dependency on the length of the sentence, that is, more or fewer words in a sentence do not matter. This approach of adding some context to the words in a sentence is known as <strong>Self-Attention</strong>.</p><h3>2.2 Query, Key, and Values</h3><p>The issue with Self-Attention is that nothing is being trained. But maybe if we add some trainable parameters, the network can then learn some patterns which give much better context. This trainable parameter can be a matrix whose values are trained. So the idea of Query, Key, and Values was introduced.</p><p>Let’s again consider the previous sentence — ”<em> Bark is very cute and he is a dog</em>”. In Figure 4 in self-attention, we see that the initial word embeddings (<em>V</em>) are used 3 times. 1st as a dot product between the first word embedding and all other words (including itself, 2nd) in the sentence to obtain the weights, and then multiplying them again (3rd time) to the weights, to obtain the final embedding with context. These 3 occurrences of the V’s can be replaced by the three terms <strong>Query</strong>, <strong>Keys</strong>, and <strong>Values</strong>.</p><p>Let’s say we want to make all the words similar with respect to the first word V1. We then send V1 as the Query word. This query word will then do a dot product with all the words in the sentence (V1 to V9) — and these are the Keys. So the combination of the Query and the Keys give us the weights. These weights are then multiplied with all the words again (V1 to V9) which act as Values. There we have it, the Query, Keys, and the Values. If you still have some doubts, figure 5 should be able to clear them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KYfHWx8EUAkoeHau.png" /></figure><p>Figure 5. Denoting the Query, Keys, and the Values (Source: image created by author)</p><p>But wait, we have not added any matrix that can be trained yet. That’s pretty simple. We know, if a 1 x k shaped vector is multiplied with a k x k shaped matrix, we get a 1 x k shaped vector as output. Keeping this in mind let’s just multiply each key from V1 to V10 (each of shape 1 x k), with a matrix Mk (Key matrix) of shape k x k. Similarly, the query vector is multiplied with a matrix Mq (Query matrix)., and the Values vectors are multiplied with Values matrix Mv. All the values in these matrices Mk, Mq, and Mv can now be trained by the neural network, and give much better context than just using self-attention. Again for a better understanding, Figure 6 shows a pictorial representation of what I just explained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*127ATX-o1B9cgWfF.png" /></figure><p>Figure 6. Key Matrix, Query matrix, and Value Matrix (Source: image created by author)</p><p>Now that we know the intuition of Keys, Query, and Values, let’s look at a database analysis and the official steps and formulas behind Attention.</p><p>Let’s try and understand the Attention mechanism, by looking into an example of a database. So, in a database, if we want to retrieve some <strong>value</strong> v<em>i </em>based on a <strong>query</strong> q and <strong>key</strong> k<em>i,</em> some operations can be done where we can use a query to identify a key that corresponds to a certain value. Attention can be thought to be a similar process to this database technique but in a more probabilistic manner. This is demonstrated in the figure below.</p><p>Figure 7, shows the steps of data retrieval in a database. Suppose we send a query into the database, some operations will find out which key in the database is the most similar to the query. Once the key is located, it will send out the value corresponding to that key as an output. In the figure, the operation finds that the Query is most similar to Key 5, and hence gives us the value 5 as output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*W8Kwaq5K7J1K3Wj5.png" /></figure><p>Figure 7. Value retrieval process in a database (Source: image created by Author)</p><p>The Attention mechanism is a neural architecture that mimics this process of retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*UCgynZqa72fY73YS.png" /></figure><ol><li>The attention mechanism measures the similarity between the query q and each key-value k<em>i.</em></li><li>This similarity returns a weight for each key value.</li><li>Finally, it produces an output that is the weighted combination of all the values in our database.</li></ol><p>The only difference between database retrieval and attention in a sense is that in database retrieval we only get one value as input, but here we get a weighted combination of values. In the attention mechanism, if a query is most similar to say, key 1 and key 4, then both these keys will get the most weights, and the output will be a combination of value 1 and value 4.</p><p>Figure 8 shows the steps required to get to the final attention value from the query, keys, and values. Each step is explained in detail below.</p><p>(The key values <em>k</em> are vectors, the Similarity values<em> S</em> are scalars, the weight values (softmax) values <em>a</em> are scalars, and the Values <em>V</em> are vectors)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*64YzAe4t5I2-csXA.png" /></figure><p>Figure 8. Steps to attain the Attention Value (Source: Image created by author)</p><h3>Step 1.</h3><p>Step 1 contains the keys and the query and the respective similarity measures. The query <em>q</em> influences the similarity. What we have are the query and the keys, and we calculate the similarity. The similarity is some function of the query <em>q</em> and the keys <em>k</em>. Both the query and the keys are some embedding vectors. Similarity <em>S</em> can be calculated using various methods as shown in figure 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mc8mklAmYKBa0QYA.png" /></figure><p>Figure 9. Ways to calculate the Similarity (Souce: image created by author)</p><p>Similarity can be a simple dot product of the query and the key. It can be scaled dot product, where the dot product of <em>q</em> and <em>k, </em>is divided by the square root of the dimensionality of each key,<em> d. </em>These are the most commonly used two techniques to find the similarity.</p><p>Often a query is projected into a new space by using a weight matrix <em>W, </em>and then a dot product is made with the key <em>k</em>. Kernel methods can also be used as a similarity.</p><h3>Step 2.</h3><p>Step 2 is finding the weights <em>a</em>. This is done using ‘<em>SoftMax</em>’. The formula is shown below. (exp is exponential)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/0*1iaCR30ZbmtOYTfo.png" /></figure><p>The similarities are connected to the weights like a fully connected layer.</p><h3>Step 3.</h3><p>Step 3 is a weighted combination of the results of the softmax (<em>a</em>) with the corresponding values (<em>V</em>). The 1st value of <em>a</em> is multiplied with the first value of <em>V</em> and is then summed with the product of the 2nd value of <em>a</em> with the 2nd value of Values <em>V</em>, and so on. The final output that we obtain is the resulting attention value that is desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*Dqym7dotoldebeeE.png" /></figure><p><strong>Summary of the three steps:</strong></p><p>W<strong>ith the help of the query <em>q</em> and the keys <em>k</em>, we obtain the attention value, which is a weighted sum/linear combination of the Values <em>V, </em>and the weights come from some sort of similarity between the query and the keys.</strong></p><h3>2.3 Neural network representation of Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*A6LW41b-xllpPahX.png" /></figure><p>Figure 10. Neural network representation of Attention block (Source: image created by author)</p><p>Figure 10 shows the neural network representation of an attention block. The word embeddings are first passed into some linear layers. These linear layers do not have a ‘bias’ term, and hence are nothing but matrix multiplications. One of these layers is denoted as ‘keys’, the other as ‘queries’, and the last one as ‘values’. If a matrix multiplication is performed between the keys and the queries and are then normalized, we get the weights. These weights are then multiplied by the values, and summed up, to get the final attention vector. This block can now be used in a neural network and is known as the Attention block. Multiple such attention blocks can be added to provide more context. And the best part is, we can get a gradient backpropagating to update the attention block (weights of keys, queries, values).</p><h3>2.4 Multi-Head Attention</h3><p>To overcome some of the pitfalls of using single attention, multi-head attention is used. Let’s go back to the sentence — ”<em> Bark is very cute and he is a dog</em>”. Here, if we take the word ‘dog’, grammatically we understand that the words ‘Bark’, ‘cute’, and ‘he’ should have some significance or relevance with the word ‘dog’. These words say that the dog’s name is Bark, it is a male dog, and that he is a cute dog. Just one attention mechanism may not be able to correctly identify these three words as relevant to ‘dog’, and we can say that three attentions are better here to signify the three words with the word ‘dog’. This reduces the load on one attention to find all significant words and also increases the chances of finding more relevant words easily.</p><p>So let’s add more linear layers as the keys, queries, and values. These linear layers are training in parallel, and have independent weights to one another. So now, each of the values, keys, and queries gives us three outputs instead of one. These 3 keys and queries now give three different weights. These three weights then with matrix multiplication with the three values, to give three multiple outputs. These three attention blocks are finally concatenated to give one final attention output. This representation is shown in figure 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*-X1htg94-i94oZDJ.png" /></figure><p>Figure 11. Multi-head attention with 3 linear layers (Source: image created by author)</p><p>But 3 is just a random number we chose. In the actual scenario, these can be any number of linear layers, and these are called heads (<em>h</em>). That is there can be <em>h</em> number of linear layers giving <em>h</em> attention outputs which are then concatenated together. And this is exactly why it is called multi-head attention (multiple heads). The simpler version of figure 11, but with <em>h</em> number of heads is shown in figure 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A51ZuwejFiEwYtVf.png" /></figure><p>Figure 12. Multi-Head attention with ‘h’ layers (Source: Image created by author)</p><p>Now that we understand the mechanism and idea behind Attention, Query, Keys, Values, and Multi-Head attention, we have covered all the important building blocks of a Transformer network. In the next story, I will talk about how all these blocks are stacked together to form the Transformer Network, and also talk about some networks based on Transformers such as BERT and GPT.</p><p>Credit goes to:</p><p><a href="https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021">https://towardsdatascience.com/all-you-need-to-know-about-attention-and-transformers-in-depth-understanding-part-1-552f0b41d021</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4fb0ee79646" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>