<?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 Vipul Sarode on Medium]]></title>
        <description><![CDATA[Stories by Vipul Sarode on Medium]]></description>
        <link>https://medium.com/@vipul.sarode007?source=rss-a1026127d874------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CVwXuoAGGkFNPe2-lM0VVQ.jpeg</url>
            <title>Stories by Vipul Sarode on Medium</title>
            <link>https://medium.com/@vipul.sarode007?source=rss-a1026127d874------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:33:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vipul.sarode007/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[Quantization for LLMs]]></title>
            <link>https://medium.com/@vipul.sarode007/quantization-for-llms-d121a713f6de?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/d121a713f6de</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 07:26:25 GMT</pubDate>
            <atom:updated>2024-07-04T07:26:25.263Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><blockquote>For many deep learning problems, we’re finally getting to the “make it efficient” stage. We’d been stuck in the first two stages for many decades, where speed and efficiency weren’t nearly as important as getting things to work in the first place. So the question of how precise our calculations need to be — and whether we can manage with lower precision — wasn’t often asked. —<strong> Francois Chollet</strong></blockquote><p>As AI becomes a bigger part of our daily lives, we’re seeing a shift toward using mobile and edge devices more quickly than ever. A great example of this is Siri (or Google Assistant for Android users). These AI models perform a lot of complex calculations to do what they do. However, these calculations need a lot of computational resources, which are often limited on mobile or edge devices. Quantization helps by compressing the model, allowing it to work efficiently with the limited resources available on mobile devices. In this article, we’ll explore how quantization achieves this and how you can use different techniques to quantize your models.</p><h4>What is quantization</h4><p>Quantization is a process that performs computations with tensors and stores them in a lower-precision format. This usually means converting high-precision floating-point numbers into low-precision integers to reduce size and memory usage. As a result, it typically improves inference time by 2–4 times.</p><blockquote>PyTorch supports INT8 quantization compared to typical FP32 models allowing for a 4x reduction in the model size and a 4x reduction in memory bandwidth requirements.</blockquote><p>Even though we lower the precision of tensors, the accuracy of the models is not significantly reduced. Quantization offers the perfect trade-off between accuracy and on-device latency. There are different techniques for quantization, with the most popular being Post-Training Quantization and Quantization-Aware Training. These terms are almost self-explanatory. We will dive deep into these techniques in the next section.</p><h4>Post-Training Quantization</h4><p>Post-Training Quantization (PTQ) is typically used when a model already in use needs to be optimized for edge or mobile devices. As the name suggests, this technique reduces the model’s size to work well with resource-constrained devices without requiring further training. Some methods for PTQ include GPTQ and GGUF/GGML. Let’s see how to quantize a model using the PTQ method with the AutoGPTQ library to achieve the GPTQ format.</p><p>GPTQ is a quantization method designed to make large language models (LLMs) run efficiently on CPUs. It can convert LLMs from 32-bit to lower precision formats, such as 4-bit, 3-bit, or even 2-bit formats. This allows for significant compression of LLMs while minimally impacting their accuracy.</p><p>GPTQ works with a layerwise approach i.e. it takes the weights in batches, quantizes them, and moves on. Let’s see how GPTQ works, one step at a time —</p><ol><li><strong>Arbitrary Order Insight</strong> — GPTQ is inspired by the OBQ (Optimal Brain Quantization) method, which is used to quantize the model in a specific order to minimize the least additional quantization error. However, the creators found out that no matter the order in the quantization appears, the results are the same. This is because even though some weights introduce more error at the initial stage, those are balanced out at by the weights being quantized at the end.</li><li><strong>Lazy Batch Updating</strong> — First, all the model’s weights are converted into matrices of 128 columns. Then the weights are quantized in batches. This process makes sure that we are efficiently using the GPUs available. Once a batch or a block is processed, the algorithm performs global updates of the entire matrices.</li><li><strong>Cholesky Reformulation</strong> — In very layman’s terms, Cholesky Reformulation means that while working on a batch, it shrinks the weights, calculates the error of the new weights with the original weights, and then updates the new weights to minimize the error.</li></ol><p>Although, in some use-cases, the accuracy is significantly lowered when an LLM is quantized with PTQ techniques. This is where Quantization Aware Training steps in.</p><h4>Quantization Aware Training</h4><p>This technique incorporates quantization into the training process. By simulating quantization effects during training, the model can adapt to reduced precision, learning to maintain high performance despite the lower precision. This often results in higher accuracy compared to PTQ.</p><p>This process is a bit complex, but let’s break it down and understand it together.</p><p>In this technique for training a Large Language Model (LLM), we use fake quantization between weights and activations. This means that first, the weights and activations are quantized, then the forward pass is executed, and finally, they are dequantized so that the next layer is unaware of the transformation. This helps the model adapt to lower precision while maintaining high performance. It’s important to note that during the backward pass, the values transferred are not quantized but are full-precision.</p><p>The benefits of this technique include improved accuracy and a greater reduction in model size compared to post-training quantization (PTQ). Since we compress the model as we train, we don’t need a lot of computational resources. However, a downside is that because many operations are happening during training, the training time is increased.</p><h4>AWQ</h4><p>AWQ is a new quantization method that realizes not all weights in a Large Language Model (LLM) are equally important for performance. Unlike traditional quantization techniques that treat all weights the same, AWQ identifies and preserves a small subset of critical weights while aggressively quantizing the rest. The key idea behind AWQ is that only about 1% of weights in an LLM are “salient,” meaning they have a significant impact on the model’s output. By focusing on these crucial weights, AWQ achieves better compression ratios while maintaining model accuracy.</p><p>Let’s see how AWQ works step by step</p><ol><li>It begins by running inference on a small calibration dataset to gather statistics on which weights are most frequently activated during inference and then identifies the weights (Salient Weights)</li><li>These Salient weights are important and hence contribute largely to the accuracy. So, they are kept in their original FP16 float format and the other weights are quantized aggressively to INT3 and INT4.</li></ol><p>This process helps in squeezing more accuracy from the model while shrinking it. Also, as we are quantizing only selected parts of the model, the quantization process finishes faster. Finally, AWQ doesn’t rely on backpropagation or reconstruction, allowing it to preserve the LLM’s ability to generalize across different domains.</p><p>I hope you learned something from the blog. Please reach out to me if you have any questions or if you want to collaborate on something interesting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d121a713f6de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constructing LoRA: Low Rank Adaptation with Mathematical Insights and Practical Implementation from…]]></title>
            <link>https://medium.com/@vipul.sarode007/constructing-lora-low-rank-adaptation-with-mathematical-insights-and-practical-implementation-16ab17b67d5e?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ab17b67d5e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 06:26:51 GMT</pubDate>
            <atom:updated>2024-03-27T06:26:51.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>Constructing LoRA: Low Rank Adaptation with Mathematical Insights and Practical Implementation from Scratch in PyTorch</h3><p>In this article, we will learn what LoRA is, look into the maths that makes LoRA fine-tune large models efficiently, and finally create our own LoRA from scratch and use it to fine-tune our model.</p><h4>How does LoRA work?</h4><p>LLMs or other large models like Stable Diffusion have billions and billions of parameters. It is only possible to fine-tune these models to a specific business use case if they have a big enough budget and heaps of computational resources. Hence, in the paper “<a href="https://arxiv.org/abs/2106.09685">LoRA: Low Rank Adaptation of LLMs</a>”, Microsoft proposed LoRA to help solve the problem.</p><p>Hence, to fine-tune, rather than loading the whole model into the GPU, performing backpropagation on the whole model, and updating all its weights LoRA freezes the initial weights, W, of the model and creates two additional matrices, A and B, on top of it. These matrices, A and B, are created such that when multiplied together, they create a new matrix that has the same dimensions as the initial weight matrix, W. In the training process after calculating the loss, the loss is only backpropagated to the LoRA matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*u-4tGilnCa3OazfAZ56VWA.png" /></figure><p>This is a classic case of matrix decomposition. Utilizing this process, we need to train and save a smaller number of parameters. Fewer parameters mean fewer storage requirements, less computation required, faster backpropagation, and consequently, less training time. Now, let’s look at the maths behind the LoRA to understand how it works.</p><h4>The Maths behind LoRA</h4><p>As mentioned earlier, LoRA works the way it works because of the matrix decomposition. This is the forward pass formula while training with LoRA</p><p>h = W0x + ∆W x = W0x + BAx where h is the hidden layer, W0 is the pre-trained frozen weights of the pre-trained model of shape (d x k), ∆W are the LoRA tracked weights, and B and A are the new matrices created of the dimension (d x r) and (r x k). The B and A matrices are created in such a way that after matrix multiplication, we get a matrix of shape (d x k).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IRiy77e0nX1BSQHipK7TQ.png" /></figure><p>As we can see in the picture, to create a (3x3) matrix with updated weights and 9 parameters, we only need to update 6 parameters, 3 of B and A each. It may not seem a significant number for this specific matrix, but while working with an actual model the number of trainable parameters is decreased drastically.</p><blockquote>There have been recent developments in LoRA such as the LoRA+ which was proposed by Soufiane Hayou, Nikhil Ghosh, and Bin Yu of UC Berkeley. LoRA+ is the same as LoRA but with different learning rates for the B and A matrices.</blockquote><p>Now that we are well-acquainted with LoRA and its internal workings, let’s build one from scratch and deepen our understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNfeQrOMpoejLE8GETzJqA.png" /><figcaption>Initialization of the A and B matrix from the original paper</figcaption></figure><pre>#Let&#39;s create a LoRA class that will add two new matrices A and B to the<br>#original weights and return them such as B x A yields the same dinmensions as W<br><br>class LoRA(nn.Module):<br>  def __init__(self, features_in, features_out, rank, alpha, device = device):<br>    super().__init__()<br>    self.matrix_A = nn.Parameter(torch.zeros((features_out, rank)).to(device))<br>    self.matrix_B = nn.Parameter(torch.zeros((rank, features_in)).to(device))<br>    self.scale = alpha/rank<br>    nn.init.normal_(matrix_A, mean = 0, std = 1)  <br><br>  def forward(self, W):<br>    return W + torch.matmul(self.matrix_B,self.matrix_A).view(W.shape)*self.scale</pre><p>Now that we have created our own LoRA class that will set up the matrices on top of the original Weights, we need to create a function that will replace the original weights in layer with the output of the LoRA class i.e. with the two new matrices added on top of the original weight matrix.</p><pre>#This function takes the layer as the input and sets the features_in.features_out<br>#equal to the shape of the weight matrix. This will help the LoRA class to<br>#initialize the A and B Matrices<br><br>def layer_parametrization(layer, device, rank = 1, lora_alpha = 1):<br>  features_in, features_out = layer.weight.shape<br>  return LoRA(features_in, features_out, rank = rank, alpha = lora_alpha, device)</pre><p>We can easily apply this function to the layer of our model using the Parametrize() function from PyTorch Library. Go <a href="https://pytorch.org/tutorials/intermediate/parametrizations.html">here</a> if you were not aware of this function.</p><p>We have successfully created a LoRA from scratch. The only thing that remains is its practical implementation and hands-on experience with the efficiency of LoRA. For ease, we will train a model to classify the MNIST digits and fine-tune the model on a specific digit. For the full code, please go to my GitHub repository.</p><p><a href="https://github.com/vipulsarode/LoRA-from-Scratch-and-fine-tuning">GitHub - vipulsarode/LoRA-from-Scratch-and-fine-tuning: I built a LoRA from scratch in PyTorch and fine-tuned a classifier for increased accuracy on a specific digit recognition.</a></p><p>The original classifier without any fine-tuning gave the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDPOhblgZfuOSsFYfSpXYg.png" /></figure><pre>import torch.nn.utils.parametrize as parametrize<br><br># Here we apply parametrization such that whenever the model wants to access <br># weights from the original linear layers of the model, <br># it returns the original weights plus LoRA matrices so that we can freeze the<br># original weights and then train the LoRA matrices.<br><br>parametrize.register_parametrization(exp.linear1, &#39;weight&#39;, layer_parametrization(exp.linear1, device))<br>parametrize.register_parametrization(exp.linear2, &#39;weight&#39;, layer_parametrization(exp.linear2, device))<br>parametrize.register_parametrization(exp.linear3, &#39;weight&#39;, layer_parametrization(exp.linear3, device))</pre><p>Just for reference, here is the additional number of parameters introduced by the LoRA. We can see only 0.242% of the parameters have been increased, making fine-tuning with LoRA efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q2jtiUfM91GX2pPlg9GAg.png" /></figure><p>Putting all of the code here is not a very efficient use of time, hence please go to my GitHub for the full code used in this article. I have only attached the main snippets.</p><p>Now, let’s fine-tune the model to increase its accuracy in classifying the digit 7. We will upload the MNIST dataset again where it only contains the digit 7 and train a new model, but with a LoRA this time.</p><pre>#freezing the non-LoRA matrices.<br><br>for name, param in exp.named_parameters():<br>    if &#39;mat&#39; not in name:<br>        print(f&#39;Freezing non-LoRA parameter {name}&#39;)<br>        param.requires_grad = False<br><br>for layer in [exp.linear1, exp.linear2, exp.linear3]:<br>  layer.parametrizations[&quot;weight&quot;][0].requires_grad = True<br><br># Train the network with LoRA only on the digit 7 and only for 100 batches <br>train(train_loader, exp, epochs=1, total_iterations_limits=100)</pre><p>These are the results we get after training the model with LoRA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YyOx5Gc4wsqxtqQrwA2Ww.png" /></figure><p>The wrong counts for the digit 7 went down from 67 to just 5. This is indeed a great improvement with so few additional parameters.</p><p>Thank you for reading! Most of the code is inspired by Umar Jamil’s tutorial, which is a great one and has helped me learn a lot. I have shared this article from the perspective of introducing LoRA to freshers and documenting my learning journey. Also, the best way to learn is through teaching. Please let me know in the comments if you have any questions or feedback. See you in the next one.</p><h4>References</h4><ol><li><a href="https://github.com/microsoft/LoRA">Microsoft GitHub</a></li><li><a href="https://www.youtube.com/watch?v=PXWYUTMt-AU&amp;t=1398s">Umar Jamil</a></li><li><a href="https://arxiv.org/abs/2106.09685">LoRA: Low Rank Adaptation of LLMs</a></li><li><a href="https://pytorch.org/tutorials/intermediate/parametrizations.html">PyTorch Parametrization</a></li><li>Krish Naik</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ab17b67d5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But then what are Vector Databases and how to use them?]]></title>
            <link>https://medium.com/@vipul.sarode007/but-then-what-are-vector-databases-and-how-to-use-them-fdeec7dfe88e?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdeec7dfe88e</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 20:16:35 GMT</pubDate>
            <atom:updated>2024-02-20T20:16:35.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Vector Databases are quite a hot topic these days. In this era of increasing AI influence in our day-to-day lives and an ever-increasing quantity of unstructured data, Data Scientists and Machine Learning Engineers needed a tool to query high-dimensional unstructured data within seconds. This led to a dramatic increase in the jargon like Embeddings, Vector Databases, and Vector Search. To truly understand Vector Databases, let’s start by understanding embeddings first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jG8QkMpuzJn714J-ZLAbA.png" /></figure><h4>Embeddings</h4><p>Most of the SOTA models we use nowadays are trained on either text or image data. Text and image data are human-interpretable but not quite machine-interpretable. It only understands things in numbers. That is when embeddings step in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AokXVm_wH6g15hJTSqwGIw.jpeg" /><figcaption>Image of a Dog on the left, accompanied by its corresponding embeddings on the right (Source: <a href="https://www.activeloop.ai/resources/generate-image-embeddings-using-a-pre-trained-cnn-and-store-them-in-hub/">activeloop.ai</a>)</figcaption></figure><p>Embeddings represent given text, images, or any other objects in a lower dimensional numerical vector that can be read by a machine. They tend to store semantic and contextual information gained from the text or the image. For example, in the multi-dimensional vector space, the embeddings for the words ‘food’ and ‘lasagna’ lie closer to each other than that of the words ‘food’ and ‘engine’. Similarly, embeddings for the images of a brown puppy and a German shepherd lie closer than a brown puppy and a door.</p><p>Hence, embeddings store complex information in a compact and meaningful manner which helps in the efficient and accurate processing of information. This is why any text, image, or object is converted into embeddings before it is stored in the vector database.</p><h4>Vector Database</h4><p>As the name suggests, Vector databases store high-dimensional vectors in the form of text, image, audio, or video embeddings. The dimensions of these embeddings can range from tens to thousands depending on the complexity of the data they represent. These databases have a feature called similarity search which swiftly and precisely matches and retrieves embeddings or vectors within the database similar to the queried external data. Because vector databases work with embeddings, they are not restricted to similar data types. They incorporate multimodularity and hence can also be used to, for example, retrieve images by inputting text.</p><h4>Use cases of Vector Databases</h4><ol><li>Because of their similarity search feature, vector databases are majorly used in recommendation systems to recommend articles, videos, movies, etc based on the user’s past behavior.</li><li>Their ability to store similar things closer, they are especially helpful in search engines, image-to-image search, content moderation etc.</li><li>They can be used to detect anomalies just by comparing the vector distance of the specific activity in question to the normal pattern of activities.</li><li>Being easy to scale and integrate with machine learning systems and having fast response times, they can be used in varied real-time machine learning use cases.</li></ol><p>Now that we have a comprehensive understanding of Vector Databases and how they work, it is time to implement them practically. Some examples of Vector Databases are Apache Cassandra, ChromaDB, Pinecone, Weaviate, Redis, and Milvus. We will look into the practical implementation of one of these databases, the ChromaDB.</p><h4>ChromaDB</h4><p>ChromaDB is a vector database that works with embeddings and is widely used to make AI applications. The highlight of ChromaDB is that it is open source and can be used on your machine locally, even though a cloud-based will be released soon. Let’s see a simple use case of PDF QnA and learn how to use it. We will use ‘<a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a>’ and question it.</p><pre>#Import Dependencies<br>import os<br>import openai<br>import langchain<br>from langchain.document_loaders import PyPDFDirectoryLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br>from langchain.llms import OpenAI<br>from langchain.chains import RetrievalQA<br><br>#Setting up API key to use OpenAI llm<br>os.environ[&#39;OPENAI_API_KEY&#39;] = &#39;&lt;YOUR_API_HERE&gt;&#39;<br><br>#To question a PDF, we will have to load a PDF first<br>#We will use the PyPDF package functions from langchain to import the PDF<br><br>def paper_loader(path):<br>  doc_loader = PyPDFDirectoryLoader(path)<br>  paper = doc_loader.load()<br>  return paper<br><br>paper = paper_loader(&#39;&lt;PATH_TO_YOUR_PDF&gt;&#39;) # I have loaded &#39;Attention is all you need&#39;<br><br>#A PDF can contain practically millions of words (tokens)<br>#But the specific number of tokens an llm can work with is limited<br>#Hence we will divide the PDF content into workable number of token chunks<br>#Generally the max size of a chunk should not be more than 1000<br>#Chunk overlap specifies the number of token from the past chunk <br>#to be included in the next chunk for context.<br><br>def chunking(paper, chunk_size = 1000, chunk_overlap = 75):<br>  splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)<br>  chunks = splitter.split_documents(paper)<br>  return chunks<br><br>paper_chunked = chunking(paper)<br><br>#Now that our data is prepared, let&#39;s create embedding to store in the database<br><br>persist_directory = &#39;vector db&#39;<br>embed = OpenAIEmbeddings()<br>vectordb = Chroma.from_documents(documents = paper, persist_directory = persist_directory, embedding = embed)<br>vectordb.persist()<br><br>#Our database is now created and saved on the disk with the embeddings<br>#Now comes the best part. Using it. Let&#39;s load it first<br><br>vec_db = Chroma(persist_directory=persist_directory, embedding_function = embed)<br><br>#Now that our database is loaded and ready to use, we will perform some similarity search<br><br>retriever = vec_db.as_retriever(search_kwargs={&#39;k&#39;:2})<br>retriever.search_type<br>ans = retriever.get_relevant_documents(&#39;what is the decoder?&#39;)<br><br>#with the get relevant documents, we extract paragraphs from the PDF which contains similar information<br>#To get intelligent answers, we will need to incorporate llms with our database<br><br>llm = OpenAI()<br>qa_chain = RetrievalQA.from_chain_type(llm = llm, retriever=retriever, chain_type = &#39;stuff&#39;, return_source_documents=True)<br>qa_chain(&#39;what is the formula for finding positional encodings?&#39;)<br><br>#Here, we get short and to the point answers for our queries.<br>#I created a function to beutify the answers a little bit<br><br>def answer(query):<br>  ans = qa_chain(query)<br>  print(ans[&#39;result&#39;])<br>  print(&#39;\nSources:&#39;)<br>  for i in ans[&#39;source_documents&#39;]:<br>    print(i.metadata[&#39;source&#39;])<br><br>answer(&#39;what is the formula for finding positional encodings?&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7pro5oaL-kWtxbvOaUVCA.png" /><figcaption>This is the output I got for the query</figcaption></figure><p>Fascinating, isn’t it? There is a little bit of a problem with the output. It should be 1000^(2i/dmodel) instead of 10002i/dmodel. A little bit of fine-tuning the llm for understanding math equations, and voila! But this truly shows the potential of Vector Databases and their capabilities to enhance AI applications. Please check my GitHub for the entire code with its outputs. I will also add methods to implement other databases like Pinecone and Weaviate in the same repository in the future.</p><p>Thank you for taking the time to read this article. If you have any questions or feedback, please let me know in the comments. See you, take care!</p><h4>References</h4><ol><li><a href="https://learn.microsoft.com/en-us/semantic-kernel/memories/vector-db">Microsoft</a></li><li><a href="https://docs.trychroma.com/">TryChroma</a></li><li><a href="https://python.langchain.com/docs/get_started/introduction">LangChain Documentation</a></li><li><a href="https://www.youtube.com/watch?v=8KrTO9bS91s&amp;t=6264s">DSwithBappy</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdeec7dfe88e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention is all you need Explained]]></title>
            <link>https://medium.com/@vipul.sarode007/attention-is-all-you-need-explained-1f33686690e2?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f33686690e2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 06:42:47 GMT</pubDate>
            <atom:updated>2024-02-12T06:42:47.497Z</atom:updated>
            <content:encoded><![CDATA[<p>“<a href="https://arxiv.org/abs/1706.03762">Attention is all you need (Vaswani et al.)</a>” is one of the most influential papers that introduced Transformers to us and set the course of some amazing AI architectures like GPT. In this article, we will dive deep into the architecture of the Transformer with Multi-head attention and see the function of each component in detail. For the best learning experience, open the research paper on another tab and read alongside. This will also make you habitual to reading research papers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*7tyq55pLi-W8axMm_1aX_Q.png" /><figcaption>Transformer Architecture (Source: Attention is all you need Vaswani et al.)</figcaption></figure><p>This is the famous Transformer architecture everyone is talking about. Let’s dive deep into this architecture and learn about each component in detail.</p><h4>Input Embeddings</h4><p>As we already know, computers understand numbers, not text. This layer first tokenizes the sentences (how the sentence is tokenized is relevant to the task and the method can be different for different tasks) and then converts them into an embedding vector of dimension d_model, which is 512 in our case.</p><h4>Positional Encoding</h4><p>Okay, now that we have converted our text data into embeddings, we need to give the positional meaning of the words to the model. Without Positional Encodings, the transformer will not understand how these words appear in a sequence. Positional Encoding helps the model distinguish certain words that appear closely more often and those that appear distant and hence creates a learnable pattern for the transformer.</p><p>For Example, in the sentence ‘I ate a chocolate cookie’, ‘chocolate cookie’ are the closer word, and ‘I cookie’ are distant.</p><p>To create these encodings first, we create a vector of dimension d_model (512 in our case). Then, for each element in this vector, we calculate the values in the form of PE(pos, element position) where pos is the position of the word in the sentence. For the elements in the even position, we will use the <strong>sin</strong> formula and for those in the odd position, we will use the <strong>cos</strong> formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*dXFDnvZRj10ojOcA6L-hbw.png" /><figcaption>Formula to find Positional encodings (Source: Attention is all you need)</figcaption></figure><p>The authors used the sin and cos function because of their natural ability to represent a pattern which would immensely help the model in learning. Also, as the sin and cos values range only from -1 to 1 the risk of vanishing or exploding gradients is minimal. Lastly, the encodings are not tied to a specific word of sentence or word which makes it easier to generalize sentences of varying length.</p><p>One thing to note is that the Positional Encodings are fixed and are not updated during training or inference. Hence, they remain the same for different words in different sentences. The input embeddings and positional encodings are added and passed on to the next layer.</p><h4>Layer Normalization</h4><p>Layer Normalization is performed to make all the activation values of each neuron in each layer from 0 to 1 to make the training stable. The mean and variance for each item are calculated independently. Then we introduce a normalization parameter using this formula which is specific to each layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Kn78vuBE3hf1eLH6JD7vxQ.png" /><figcaption>Normalization parameter (Source: <a href="https://www.youtube.com/watch?v=bCz4OMemCcA&amp;t=850s">Umar Jamil</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*i5WU9DvuRM6MiRirCe-CQg.png" /><figcaption>Difference between Batch Norm and Layer Norm (Source: <a href="https://paperswithcode.com/method/layer-normalization">paperswithcode</a>)</figcaption></figure><p>As we can see in the image, all the batch values within the N dimension are calculated in the Batch Norm. While in layer norm with N dimension, all the values belonging to only 1 item independently are calculated at a time.</p><p>We also introduce two new values named gamma and beta. These are learnable parameters and are used to highlight the most important features (or to not highlight less important features). The gamma is multiplied by the normalization parameter and beta is then added to that.</p><h4>Self Attention</h4><p>Before we dive into Multi-head Attention which is used in the official paper, we need to understand the Self Attention i.e. a single head of the Multi-head. Self-attention allows the model to relate all the words to each other. It represents how each word in a sentence is related to other words in the same sentence. If, for some reason, the interaction of some words is not desired, we can replace their values with -inf.</p><p>Self Attention is calculated by converting the input sentence into three identical matrices which are — Query(Q), Key(K), and Value(V). The formula for Self Attention is as below&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*yz5R7XDYbUVnR_fs8yXhFQ.png" /><figcaption>Self Attention Formula (Source: Attention is all you need)</figcaption></figure><p>We divide by the square root of d_k to minimize the variance and introduce stability. After the dot product of Q, K Transpose, and V is done, we get a matrix with a shape equal to the initial matrix. Each value within this matrix represents the intensity of the relationship of a word to the other. In a row, all the values sum up to 1. Self Attention does not require any trainable parameters and leverages the embeddings and positional encodings only to derive the relationship. But, this is not the case in the Multi-head attention.</p><h4>Multi-head Attention</h4><p>We duplicate the output of the Positional Encoding layer into three similar matrices Q, K, and V just like we did in the self-attention. Then we multiply these matrices with other learnable parameter matrices WQ, WK, and WV to get the output as Q’, K’, and V’.</p><p>We divide these matrices into the desired number of heads (in our case, 4) along with the d_model axis and not the sequence length. This is because we want every head to see the sentence but a different part of the embeddings. This will help the model to look at every word with different aspects as a certain word can be a noun in a sentence and a verb in another. We need the model to learn this semantic meaning.</p><p>We calculate the attention using the divided matrices and concatenate all the attention from the four heads. Finally, we multiply the output with a matrix WO to get our Multi-head attention.</p><h4>Masked Multi-head Attention</h4><p>Our final goal is to make the model understand the language and output certain words concerning previous words only. During training, if the model gets to see the future words, it can increase its tendency to cheat hence resulting in a very poor-performing model.</p><p>To overcome this, we replace all the next word values with -inf. After applying softmax to the Attention, all the -inf values will turn to zero consequently restricting the model to cheating.</p><h4>Residual Networks</h4><p>Throughout the architecture, we can see the black arrows connecting components here and there. These are residual networks and they are created to make the information transfer consistent. This helps in the backpropagation state by preventing the problem of vanishing gradients which might stop the model from training.</p><p>In this article, we have seen the Transformer&#39;s architecture and its components in detail. I have intentionally left out the components like Linear, Softmax, and Feed Forward Networks as these are pretty much self-explanatory. If you have any questions or feedback please let me know in the comments below. In the future, we will look into how to code our own Transformer from scratch and perform training and inference on it. See you then!</p><h4>References</h4><ol><li><a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a></li><li><a href="https://www.youtube.com/watch?v=bCz4OMemCcA&amp;t=850s">Umar Jamil</a></li><li><a href="https://paperswithcode.com/method/layer-normalization">Papers with code</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f33686690e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[U-net Unleashed: A step-by-step guide on implementing and training your own segmentation model in…]]></title>
            <link>https://medium.com/@vipul.sarode007/u-net-unleashed-a-step-by-step-guide-on-implementing-and-training-your-own-segmentation-model-in-a90ed89399c6?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90ed89399c6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[unet]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 07:03:13 GMT</pubDate>
            <atom:updated>2024-01-20T07:03:13.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>U-net Unleashed: A step-by-step guide on implementing and training your own segmentation model in Tensorflow: Part 2</h3><p>In the last <a href="https://medium.com/@vipul.sarode007/u-net-unleashed-a-step-by-step-guide-on-implementing-and-training-your-own-segmentation-model-in-a38741776968">part</a>, we saw how to build the U-Net from scratch. In this part, we will use the U-Net and perform segmentations on real-world data. You can find the dataset used in this part <a href="https://www.kaggle.com/datasets/surajghuwalewala/ham1000-segmentation-and-classification">here</a>.</p><p>If you want the full version of the code, you can get it <a href="https://github.com/vipulsarode/Semantic-Segmentation-Using-Unet-built-from-Scratch-/blob/main/skin-cancer-segmentation-using-unet-from-scratch.ipynb">here</a>. To reproduce the results, you may need multiple GPUs. I used the GPUs provided for free by Kaggle for this task.</p><h4><strong>Data</strong></h4><p>I have created a custom function to upload the images and their respective masks simultaneously. In this function, I have convert all the images and their masks into grayscale to lessen the need for computational resources. Also, I have resized all of them to (256,256) size to ensure consistency. Here is the code for the function.</p><pre>def load_images(imgsort, masksort, image_dir, mask_dir):<br>    &#39;&#39;&#39;<br>    Takes the directories and image/mask names and reads them using cv2<br>    &#39;&#39;&#39;<br><br>    images, masks = [], []<br><br>    for img, msk in tqdm(zip(imgsort, masksort), total = len(imgsort), desc = &#39;Loading Images and Masks&#39;):<br>        image = cv2.imread(image_dir + img, cv2.IMREAD_GRAYSCALE)<br>        mask = cv2.imread(mask_dir + msk, cv2.IMREAD_GRAYSCALE)<br><br>        image = cv2.resize(image, (256,256))<br>        mask = cv2.resize(mask, (256,256))<br><br>        <br>        images.append(image)<br>        masks.append(mask)<br><br>        del image, mask<br>        <br>    return images, masks<br>    <br>images, masks = load_images(imgsort, masksort, image_dir, mask_dir)</pre><p>Once we import the images and the masks, we need to perform the most significant step in Machine Learning, which is:</p><p><strong>Visualize, visualize, visualize!</strong> Before training any Machine Learning model, we need to become one with the data as better data is probably the most crucial ingredient to cook a better model. Visualizing the images will also ensure that the images and masks are aligned.</p><pre>#Plotting images for sanity check<br>def plot_image_with_mask(image_list, mask_list, num_pairs = 4):<br>    &#39;&#39;&#39;<br>    This functions takes the image and mask lists and prints 4 random pairs of images and masks<br>    &#39;&#39;&#39;<br>    plt.figure(figsize = (18,9))<br>    for i in range(num_pairs):<br>        idx = random.randint(0, len(image_list))<br>        img = image_list[idx]<br>        mask = mask_list[idx]<br>        plt.subplot(2, 4, i + 1)<br>        plt.imshow(img)<br>        plt.title(f&#39;Real Image, index = {idx}&#39;)<br>        plt.axis(&#39;off&#39;)<br>        plt.subplot(2, 4, i + num_pairs + 1)<br>        plt.imshow(mask)<br>        plt.title(f&#39;Segmented Image, index = {idx}&#39;)<br>        plt.axis(&#39;off&#39;)<br>        del img, mask<br><br>plot_image_with_mask(images, masks, num_pairs = 4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jxu_-OF9jOr8o4WXRqR3KQ.png" /></figure><p>Now that the data is ready, I converted all the images and masks to tensors and performed a train-test-split using the 60–20–20 distribution for the training, validation, and testing set respectively. Again, you can refer to the code <a href="https://github.com/vipulsarode/Semantic-Segmentation-Using-Unet-built-from-Scratch-/blob/main/skin-cancer-segmentation-using-unet-from-scratch.ipynb">here</a>.</p><h4><strong>Setting up Evaluation Metrics</strong></h4><p>Segmentation tasks cannot be evaluated using the traditional accuracy method. Let’s think for a second. Segmentation is just a process of classifying the pixels. As you can see in the above masks, majority of the pixels in the mask are black (no cancer tissue is present there in our case). Hence, even if it classifies 25% of the segmented area correctly, we will still be getting “high accuracy” for our model. But practically, it might be useless. Hence, we evaluate Segmentations with a different metric — the “<strong>Dice Coefficient</strong>”</p><h4><strong>Defining the Dice Coefficient</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yGnX3tlvpgY1l0-YnmthXg.gif" /><figcaption>Visual representation of the Dice Coefficient (Source: <a href="https://www.omicsonline.org/articles-images/JCSB-07-209-g003.html">omicsonline</a>)</figcaption></figure><p><a href="https://oecd.ai/en/catalogue/metrics/average-dice-coefficient"><strong>Dice Coefficient</strong></a><strong> </strong>is the measure of overlap of two sets (in our case, images). For our use case, it measures the similarity between two images, the actual mask and the predicted mask. If the dice coefficient is 1, then the predicted mask is exactly equal to the actual mask (100% overlap). If it is zero, then the predicted and actual masks would not have any similarity.</p><p>Mathematically, the dice coefficient is defined as the ratio of intersection of two sets to their union.</p><p>Dice coefficient = 2 |A ∩ B| / (|A| + |B|) where A and B are two sets whose intensity of overlap is being measured, whereas |A| and |B| are the total number of elements in A and B respectively.</p><p>Let’s see how to code the dice coefficient in Python.</p><pre># Setting dice coefficient to evaluate our model<br>def dice_coeff(y_true, y_pred, smooth = 1):<br>    intersection = K.sum(y_true*y_pred, axis = -1)<br>    union = K.sum(y_true, axis = -1) + K.sum(y_pred, axis = -1)<br>    dice_coeff = (2*intersection+smooth) / (union + smooth)<br>    return dice_coeff</pre><h4><strong>Training the U-Net and creating Segmentations</strong></h4><p>Now that we are all set with the data and the evaluation metric, let’s train the U-Net model and perform Segmentations on the test data. I saved the U-Net we built from scratch in <a href="https://medium.com/@vipul.sarode007/u-net-unleashed-a-step-by-step-guide-on-implementing-and-training-your-own-segmentation-model-in-a38741776968">Part 1</a> in a <strong>.py </strong>file and imported it into this notebook for training.</p><pre>with strategy.scope(): #this line allocates multiple GPUs for training in Kaggle<br>    unet = unet()<br>    unet.compile(loss = &#39;binary_crossentropy&#39;,<br>            optimizer = &#39;adam&#39;,<br>            metrics = [&#39;accuracy&#39;, dice_coeff])<br><br>#Defining early stopping to regularize the model and prevent overfitting<br>early_stopping = EarlyStopping(monitor = &#39;val_loss&#39;, patience = 3, restore_best_weights = True)<br><br>#Training the model with 50 epochs (it will stop training in between because of early stopping)<br>unet_history = unet.fit(train_data, validation_data = [val_data], <br>                        epochs = 50, callbacks = [early_stopping])</pre><p>This is the final epoch before the model stopped training due to the callback we set earlier. As you can see, the accuracy is very high (94%), but the Dice Coefficient is almost (67%), hence justifying the need for the dice coefficient for evaluation. Now, let’s predict some masks for the images in the test set and plot them beside the actual masks to see how well our model is doing.</p><pre>#Function to plot the predictions with orginal image, original mask and predicted mask<br>def plot_preds(idx):<br>  &#39;&#39;&#39;<br>  This function plots a test image, it&#39;s actual mask and the predicted <br>  mask side by side. <br>  &#39;&#39;&#39;<br><br>    plt.figure(figsize = (15, 15))<br>    test_img = images_test[idx]<br>    test_img = tf.expand_dims(test_img, axis = 0)<br>    test_img = tf.expand_dims(test_img, axis = -1)<br>    pred = unet.predict(test_img)<br>    pred = pred.squeeze()<br>    thresh = pred &gt; 0.5<br>    plt.subplot(1,3,1)<br>    plt.imshow(images_test[idx])<br>    plt.title(f&#39;Original Image {idx}&#39;)<br>    plt.axis(&#39;off&#39;)<br>    plt.subplot(1,3,2)<br>    plt.imshow(masks_test[idx])<br>    plt.title(&#39;Actual Mask&#39;)<br>    plt.axis(&#39;off&#39;)<br>    plt.subplot(1,3,3)<br>    plt.imshow(thresh)<br>    plt.title(&#39;Predicted Mask&#39;)<br>    plt.axis(&#39;off&#39;)<br><br>#plotting 10 random images with their true and predicted masks<br>for i in [random.randint(0, 2000) for i in range(10)]:<br>    plot_preds(i)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkV-8lRkrFedHkDwdwarCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRwj9RMzWshZe1PWRJfyzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1dD8S9iEnp5kOtZ3tr07A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE22fCUfgVm41_Tq8EL6RA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT-mU-Dnge0p-y8H7YKVWQ.png" /><figcaption>10 randomly picked images with their actual and predicted mask</figcaption></figure><p>Looks good! I’ll say that the model is performing well with the segmentations. I hope you learnt something new from this article and thanks for sticking around till the end of it. If you have any further questions or concerns, please let me know in the comments.</p><h4>References</h4><ol><li><a href="https://oecd.ai/en/catalogue/metrics/average-dice-coefficient">oced.ai</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90ed89399c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[U-net Unleashed: A step-by-step guide on implementing and training your own segmentation model in…]]></title>
            <link>https://medium.com/@vipul.sarode007/u-net-unleashed-a-step-by-step-guide-on-implementing-and-training-your-own-segmentation-model-in-a38741776968?source=rss-a1026127d874------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38741776968</guid>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Vipul Sarode]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 13:30:02 GMT</pubDate>
            <atom:updated>2024-01-20T07:39:50.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>U-net Unleashed: A step-by-step guide on implementing and training your own segmentation model in Tensorflow: Part 1</h3><p>In this series, we will implement Image Segmentation using a <a href="https://arxiv.org/abs/1505.04597">U-Net</a> model built from scratch. The first part will cover the basics of Segmentation and how to perform it from scratch. In the second part, we will use this U-Net model to perform Segmentation on real-world data.</p><p>Part 1 — Introduction to Segmentation and Coding a U-Net (this article)<br><a href="https://medium.com/@vipul.sarode007/u-net-unleashed-a-step-by-step-guide-on-implementing-and-training-your-own-segmentation-model-in-a90ed89399c6">Part 2 — Performing Segmentations using U-Net</a></p><h4>Segmentation</h4><p>Segmentation is a computer vision task that divides an image into meaningful regions or partitions. It assigns each pixel within an image a specific label to highlight different objects or patterns in an image. Hence, segmentation has pivotal applications in medical image analysis, self-driving cars, robotics, and more.</p><h4>U-Net</h4><p><a href="https://arxiv.org/abs/1505.04597">U-Net</a> is a Convolutional neural network architecture designed by Olaf Ronneberger in 2015. As we can see in the figure, it forms a distinctive U — shape hence the name, “U-Net”. The robust ability of this architecture to contract the image, extract context, and expand the image to localize the image has proven effective in various segmentation tasks, especially in medical image analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFFocoOI-wz5rUaPevB_7A.png" /><figcaption>U-Net Architecture (Source: <a href="https://arxiv.org/abs/1505.04597">https://arxiv.org/abs/1505.04597</a>)</figcaption></figure><h4>Encoder</h4><p>As we can see in the architecture, the Encoder consists of an Input layer a series of two convolutional layers, and a MaxPooling layer. This repeated convolution and downsampling helps the encoder to create a hierarchy of features ranging from low-level features to high-level features. The lower number of filters in the beginning helps the encoder to capture low-level features and vice versa. Hence, in the overall U-Net architecture, the encoder does the job of figuring out the context of objects within the images.</p><p>After an image is received as an input, the two convolutional layers extract features from the image and pass them to the symmetrically opposite decoder layers. Then, the MaxPooling layer downsamples the image and passes it to the next series of Convolutional layers. In the original paper, the author downsamples four times, but ideally, you can downsample the image less than four or greater than four times according to the complexity of the task provided they are equal to the corresponding decoder steps. Now, let’s see how to code this encoder using Tensorflow and Python.</p><pre>#Let&#39;s create a function for one step of the encoder block, so as to increase the reusability when making custom unets<br><br>def encoder_block(filters, inputs):<br>  x = Conv2D(filters, kernel_size = (3,3), padding = &#39;same&#39;, strides = 1, activation = &#39;relu&#39;)(inputs)<br>  s = Conv2D(filters, kernel_size = (3,3), padding = &#39;same&#39;, strides = 1, activation = &#39;relu&#39;)(x)<br>  p = MaxPooling2D(pool_size = (2,2), padding = &#39;same&#39;)(s)<br>  return s, p #p provides the input to the next encoder block and s provides the context/features to the symmetrically opposte decoder block<br><br></pre><h4>Baseline</h4><p>In the <a href="https://arxiv.org/abs/1505.04597">original paper</a>, the authors used two Convolutional layers as their baseline. Again, you can use any number of Convolutional layers in the baseline.</p><p>The baseline acts as a connection between the encoder and the decoder. It takes the most downsampled image as the input which enables it to extract high-level semantic features from the image and then, it sends these features to the decoder for upsampling. Let’s see how to code the baseline in Tensorflow and Python.</p><pre>#Baseline layer is just a bunch on Convolutional Layers to extract high level features from the downsampled Image<br>def baseline_layer(filters, inputs):<br>  x = Conv2D(filters, kernel_size = (3,3), padding = &#39;same&#39;, strides = 1, activation = &#39;relu&#39;)(inputs)<br>  x = Conv2D(filters, kernel_size = (3,3), padding = &#39;same&#39;, strides = 1, activation = &#39;relu&#39;)(x)<br>  return x</pre><h4>Decoder</h4><p>The decoder consists of an upsampler (usually Conv2DTranspose or UpSampling2D) and two Convolutional layers. The decoder’s job in the U-Net is to understand the locations of the object in the image. It upsamples the features sent to it by the baseline and combines them with the hierarchical features received from the encoder via skip connections and produces a higher-resolution segmentation map. This repeatedly upsampling and concatenating helps the decoder in the robust localization of objects within an image. Let’s see how to code one step of the decoder using Tensorflow and Python.</p><pre>#Decoder Block<br>def decoder_block(filters, connections, inputs):<br>  x = Conv2DTranspose(filters, kernel_size = (2,2), padding = &#39;same&#39;, activation = &#39;relu&#39;, strides = 2)(inputs)<br>  skip_connections = concatenate([x, connections], axis = -1)<br>  x = Conv2D(filters, kernel_size = (2,2), padding = &#39;same&#39;, activation = &#39;relu&#39;)(skip_connections)<br>  x = Conv2D(filters, kernel_size = (2,2), padding = &#39;same&#39;, activation = &#39;relu&#39;)(x)<br>  return x</pre><p>Now that we have all the necessary components ready, let’s put them together and finally build a U-Net.</p><pre>def unet():<br>  #Defining the input layer and specifying the shape of the images<br>  inputs = Input(shape = (224,224,1))<br><br>  #defining the encoder<br>  s1, p1 = encoder_block(64, inputs = inputs)<br>  s2, p2 = encoder_block(128, inputs = p1)<br>  s3, p3 = encoder_block(256, inputs = p2)<br>  s4, p4 = encoder_block(512, inputs = p3)<br><br>  #Setting up the baseline<br>  baseline = baseline_layer(1024, p4)<br><br>  #Defining the entire decoder<br>  d1 = decoder_block(512, s4, baseline)<br>  d2 = decoder_block(256, s3, d1)<br>  d3 = decoder_block(128, s2, d2)<br>  d4 = decoder_block(64, s1, d3)<br><br>  #Setting up the output function for binary classification of pixels<br>  outputs = Conv2D(1, 1, activation = &#39;sigmoid&#39;)(d4)<br><br>  #Finalizing the model<br>  model = Model(inputs = inputs, outputs = outputs, name = &#39;Unet&#39;)<br><br>  return model</pre><p>We have successfully coded the U-Net model using TensorFlow. Now, in the next part of the series, we will perform segmentation on real-world Skin cancer images using this same model. See you then. Take care!</p><h4>References</h4><ol><li><a href="https://arxiv.org/abs/1505.04597">U-Net: Convolutional Networks for Biomedical Image Segmentation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38741776968" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>