<?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 Raman Shinde on Medium]]></title>
        <description><![CDATA[Stories by Raman Shinde on Medium]]></description>
        <link>https://medium.com/@raman.shinde15?source=rss-e6bc96af9357------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*liEIhFJr17kpQm0NYhAIYQ.jpeg</url>
            <title>Stories by Raman Shinde on Medium</title>
            <link>https://medium.com/@raman.shinde15?source=rss-e6bc96af9357------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:55:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raman.shinde15/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[Exploring the World of AI Compilers: Powering AI Compute and Inferance]]></title>
            <link>https://medium.com/@raman.shinde15/exploring-the-world-of-ai-compilers-powering-high-performance-machine-learning-4b3d0d8d6927?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3d0d8d6927</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[ai-compute]]></category>
            <category><![CDATA[ai-compiler]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 14:41:59 GMT</pubDate>
            <atom:updated>2026-05-23T05:10:24.143Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This Blog can be read for free <a href="https://www.ramanshinde.com/blog/ai-compilers-overview/">here</a></blockquote><p>Artificial Intelligence (AI) is transforming industries, from autonomous vehicles to personalized streaming. But behind the scenes, AI compilers are the unsung heroes making these models run faster and smarter on diverse hardware. Whether you’re deploying a large language model on a GPU or optimizing a neural network for an edge device, AI compilers bridge the gap between high-level models and hardware-specific performance. In this blog, we dive into the exciting world of AI compilers, exploring top players like NVIDIA TensorRT, Apache TVM, and more. Buckle up for a journey through the tools powering the AI revolution!</p><h3>What Are AI Compilers?</h3><p>AI compilers take machine learning models — built in frameworks like PyTorch, TensorFlow, or JAX — and transform them into optimised, hardware-specific code. Think of them as translators that turn abstract algorithms into instructions your GPU, CPU, or specialised accelerator can execute efficiently. They employ techniques such as quantisation, kernel fusion, and graph optimisation to reduce latency and increase throughput, enabling the development of real-time AI applications.</p><p><strong>Why It Matters</strong>: Whether you’re a developer building autonomous systems or a data scientist deploying models on edge devices, AI compilers are key to unlocking performance. Let’s explore the top AI compilers shaping the industry today.</p><h3>Top AI Compilers You Should Know</h3><h3>1. NVIDIA TensorRT: The GPU Inference Powerhouse</h3><p>NVIDIA’s <strong>TensorRT</strong> is a titan in the AI compiler space, designed for high-performance deep learning inference on NVIDIA GPUs. Its ecosystem includes the TensorRT compiler, TensorRT-LLM, Model Optimizer, and more, delivering low latency for applications like autonomous driving and real-time streaming.</p><ul><li><strong>Key Features</strong>:</li><li>Advanced quantization (FP8, INT4, AWQ) for compact, fast models.</li><li>Optimized for CUDA-enabled NVIDIA GPUs.</li><li>Used by giants like Amazon, Netflix, and Zoox.</li><li><strong>Community</strong>: Open-source with 11.7k+ stars on <a href="https://github.com/NVIDIA/TensorRT">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: TensorRT’s ability to minimize memory bandwidth makes it ideal for real-time AI, from self-driving cars to medical devices.</li></ul><h3>2. Apache TVM: The Universal Optimizer</h3><p><strong>Apache TVM</strong> is an open-source compiler framework that shines in flexibility, supporting CPUs, GPUs, and ML accelerators. It’s a favourite for engineers who need to deploy models across diverse hardware.</p><ul><li><strong>Key Features</strong>:</li><li>Optimises computations for any hardware backend.</li><li>Backed by a vibrant community with 12.3k+ stars on <a href="https://github.com/apache/tvm">GitHub</a>.</li><li>Used by Alibaba, AWS, Intel, and more.</li><li><strong>Why It’s Cool</strong>: TVM’s hardware-agnostic approach makes it a go-to for cross-platform AI deployment, from cloud servers to edge devices.</li></ul><h3>3. XLA (Accelerated Linear Algebra): Google’s Optimization Engine</h3><p>Google’s <strong>XLA</strong> compiler optimizes models from PyTorch, TensorFlow, and JAX for high-performance execution across GPUs, CPUs, and accelerators. It’s a backbone for Google’s AI infrastructure.</p><ul><li><strong>Key Features</strong>:</li><li>Speeds up model execution with linear algebra optimizations.</li><li>Open-source with 5.3k+ stars on <a href="https://github.com/openxla/xla">GitHub</a>.</li><li>Broad hardware support.</li><li><strong>Why It’s Cool</strong>: XLA powers Google’s AI ecosystem, making it a critical tool for scalable ML workloads.</li></ul><h3>4. ONNX Runtime: Microsoft’s Cross-Platform Champion</h3><p><strong>ONNX Runtime</strong>, developed by Microsoft, is a production-grade engine for accelerating ML inference and training across platforms, from Linux to web browsers.</p><ul><li><strong>Key Features</strong>:</li><li>Supports large model training and on-device inference.</li><li>Runs on Windows, Mac, iOS, Android, and more.</li><li>16.8k+ stars on <a href="https://github.com/microsoft/onnxruntime">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: Its cross-platform versatility makes it perfect for developers targeting diverse environments.</li></ul><h3>5. Glow: Meta’s Accelerator-Friendly Compiler</h3><p>Meta’s <strong>Glow</strong> compiler optimizes computation graphs from PyTorch for ML accelerators, using techniques like kernel fusion to speed up model development.</p><ul><li><strong>Key Features</strong>:</li><li>Tailored for accelerators, CPUs, and GPUs.</li><li>Open-source with 3.3k+ stars on <a href="https://github.com/pytorch/glow">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: Glow’s focus on accelerators makes it a great choice for cutting-edge AI hardware.</li></ul><h3>6. nvFuser PyTorch: NVIDIA’s JIT Compiler</h3><p><strong>nvFuser</strong> is NVIDIA’s just-in-time compiler for PyTorch, generating fast “fusion” kernels for NVIDIA GPUs (Volta and later).</p><ul><li><strong>Key Features</strong>:</li><li>Automatic kernel generation for deep learning networks.</li><li>Open-source on <a href="https://github.com/NVIDIA/Fuser">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: nvFuser’s runtime compilation delivers significant speedups for PyTorch users.</li></ul><h3>7. PlaidML: Intel’s Portable Tensor Compiler</h3><p>Intel’s <strong>PlaidML</strong> enables deep learning on laptops, embedded devices, and hardware with restrictive software stacks.</p><ul><li><strong>Key Features</strong>:</li><li>Supports Keras, ONNX, and nGraph.</li><li>Targets NVIDIA, AMD, and Intel hardware.</li><li>4.6k+ stars on <a href="https://github.com/plaidml/plaidml">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: PlaidML democratizes AI for devices with limited support.</li></ul><h3>8. OpenVINO: Intel’s Edge AI Toolkit</h3><p><strong>OpenVINO</strong> is Intel’s toolkit for deploying AI solutions in the cloud, on-premises, and on edge devices, optimized for Intel hardware.</p><ul><li><strong>Key Features</strong>:</li><li>Supports generative and conventional AI models.</li><li>8.4k+ stars on <a href="https://github.com/openvinotoolkit/openvino">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: OpenVINO excels at edge AI, powering smart cameras and IoT devices.</li></ul><h3>9. IREE: Scaling from Data Centers to Edge</h3><p><strong>IREE</strong> (Intermediate Representation Execution Environment) is an MLIR-based compiler for datacenter and edge deployments, supporting JAX, ONNX, PyTorch, and TensorFlow.</p><ul><li><strong>Key Features</strong>:</li><li>Scales across GPUs, CPUs, and accelerators.</li><li>3.2k+ stars on <a href="https://github.com/iree-org/iree">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: IREE’s unified approach simplifies deployment across diverse environments.</li></ul><h3>10. MLC-LLM: Optimizing Large Language Models</h3><p><strong>MLC-LLM</strong> is a compiler and deployment engine for large language models, offering OpenAI-compatible APIs via MLCEngine.</p><ul><li><strong>Key Features</strong>:</li><li>Native deployment on GPUs, CPUs, and accelerators.</li><li>Open-source on <a href="https://github.com/mlc-ai/mlc-llm">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: MLC-LLM makes LLMs accessible for developers on any platform.</li></ul><h3>11. Triton: OpenAI’s GPU Programming Simplified</h3><p>OpenAI’s <strong>Triton</strong> is a Python-like language for writing efficient GPU code, enabling researchers to achieve expert-level performance with minimal effort.</p><ul><li><strong>Key Features</strong>:</li><li>Uses LLVM for GPU and CPU code generation.</li><li>Open-source on <a href="https://github.com/triton-lang/triton">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: Triton’s simplicity empowers non-CUDA experts to write high-performance kernels.</li></ul><h3>12. SHARK-Studio: IREE’s Community Experiment</h3><p><strong>SHARK-Studio</strong>, a community project by IREE, is currently not maintained but explored MLIR-based compilation.</p><ul><li><strong>Key Features</strong>:</li><li>Targeted GPUs, CPUs, and accelerators.</li><li>Open-source on <a href="https://github.com/nod-ai/SHARK-Studio">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: A glimpse into experimental AI compilation.</li></ul><h3>13. Hidet: Python-Powered Inference</h3><p><strong>Hidet</strong> is a Python-based deep learning compiler for PyTorch and ONNX models, optimizing inference on NVIDIA GPUs.</p><ul><li><strong>Key Features</strong>:</li><li>End-to-end compilation with graph and operator optimizations.</li><li>Requires Linux, CUDA 11.6+, Python 3.9+.</li><li>700+ stars on <a href="https://github.com/hidet-org/hidet">GitHub</a>.</li><li><strong>Why It’s Cool</strong>: Hidet’s Pythonic approach simplifies GPU optimization.</li></ul><h3>14. PolyBlocks: The A100 Speedster</h3><p><strong>PolyBlocks</strong>, an MLIR-based compiler, reportedly outperforms CuBLAS/CuDNN/TensorRT on NVIDIA A100 GPUs. It’s not yet fully released.</p><ul><li><strong>Key Features</strong>:</li><li>Closed-source, targeting NVIDIA GPUs.</li><li>Learn more at <a href="https://docs.polymagelabs.com/compiler-overview.html">PolyBlocks Docs</a>.</li><li><strong>Why It’s Cool</strong>: Promises next-level performance for NVIDIA hardware.</li></ul><h3>15. Mojo: Pythonic Power Without CUDA</h3><p><strong>Mojo</strong>, paired with the Modular Platform (MAX), offers blazing-fast AI inference on CPUs and GPUs without CUDA.</p><ul><li><strong>Key Features</strong>:</li><li>Targets Intel, AMD, ARM CPUs, and NVIDIA/AMD GPUs.</li><li>Closed-source, details at <a href="https://docs.modular.com/mojo/why-mojo/">Mojo Docs</a>.</li><li><strong>Why It’s Cool</strong>: Mojo abstracts hardware complexity for seamless AI deployment.</li></ul><h3>Comparison Table</h3><p>Below is a table summarizing key attributes of the AI compilers discussed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAulgSjIxGmyOGhcztMviA.png" /><figcaption>AI Compilers compared.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3d0d8d6927" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imports in Solidity…]]></title>
            <link>https://medium.com/@raman.shinde15/imports-in-solidity-7aec77c50423?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aec77c50423</guid>
            <category><![CDATA[import]]></category>
            <category><![CDATA[brownie-config]]></category>
            <category><![CDATA[brownies]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 07:27:50 GMT</pubDate>
            <atom:updated>2026-05-22T13:47:12.888Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This blog can be read here for <a href="https://www.ramanshinde.com/blog/imports-in-solidity/">free</a></blockquote><p>Recently while completing a course on a smart contract from FreeCodeCamp, I faced difficulty in understanding the imports in Solidity.</p><p>Basically, there are three ways to import</p><ol><li>Local Imports</li><li>Import Through Github(Works only in Remix)</li><li>Import in brownie</li></ol><h4>1. Local Imports -</h4><p>You can import local and external files in Solidity. For e.g. see the below-attached image. Here ./ specifies the root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*YCU9fLfz5QaZKGMS9APJ2g.png" /><figcaption>In the same folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*beR4lgxxbKjjm3iM1aR_Rg.png" /><figcaption>In different folder</figcaption></figure><h4>2. Import Through Github(Works only in Remix) -</h4><p>There are many other ways to import other than Github in the remix. But I found this one too easy to follow. You just need to copy the GitHub URL pointing to the contract and paste it after import. Please find below e.g.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zjeglJfrSzvnPlM1UbfzhA.png" /></figure><h4>3. Import in Brownie -</h4><p>Brownie is a great package for smart contract development. It is a Python-based development and testing framework for smart contracts targeting the <a href="https://solidity.readthedocs.io/en/v0.6.0/introduction-to-smart-contracts.html#the-ethereum-virtual-machine">Ethereum Virtual Machine</a>.</p><p>There are two steps to follow</p><ol><li><strong>Adding Dependancy:-</strong></li></ol><p>To import a smart contract/source from a package, one needs to declare the dependencies by adding a dependencies field to your project <a href="https://eth-brownie.readthedocs.io/en/latest/config.html#default-configuration">configuration file</a>. Brownie will download that dependency in the <strong><em>.brownie\packages </em></strong>folder during compilation.</p><p>The format to add dependency is <strong>[ORG]/[REPO]@[VERSION].</strong></p><p>For e.g. let’s import a smart contract from chainlink Github repo. To do so, we need to define dependency in the config file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*T7qpfRWlPtzdtHjhUFNyEw.png" /></figure><p>One thing to remember is that the repo must-have release version and tag associated with it. When you execute the brownie compile, the brownie will download the package in the below location on your windows machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*iAwQ9KbRuKk48uU1d9zqLA.png" /></figure><p><strong>2. Path Remappings:-</strong></p><p>Now we need to do path remappings. Brownie exposes this functionality via the compiler.solc.remappings field in the configuration file. Each value under remappings is a string in the format prefix=path</p><p>In simple words, it tells brownie to search for a given prefix at a specific path. For e.g.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*w7hK3lIKbByF6lXS0pRgew.png" /></figure><p>Whenever, there is @chainlink occurs in import, it will tell brownie that is refers to <strong>smartcontractkit/chainlink@1.3.0 </strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*9nqkCe1mn9xG0ivzwAkTtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Ons-iGob4PP_SaV7ICDjkQ.png" /></figure><p>above import’s refer to the same thing.</p><h3>EndNote:</h3><ol><li>Thanks a lot if you have reached here. I expect the readers to be a bit generous and ignore the minor mistakes I might have made.</li><li>If the article appeals to you, do provide some comments, feedback, constructive criticism, etc.</li></ol><h3>References:</h3><ol><li><a href="https://eth-brownie.readthedocs.io/en/stable/config.html">https://eth-brownie.readthedocs.io/en/stable/config.html</a></li><li><a href="https://solidity-by-example.org/import">https://solidity-by-example.org/import</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aec77c50423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Question And Answering Using SQAD Dataset And Attention..!!!]]></title>
            <link>https://medium.com/@raman.shinde15/neural-question-and-answering-using-sqad-dataset-and-attention-983d3a1dd42c?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/983d3a1dd42c</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras-custom-layer]]></category>
            <category><![CDATA[question-and-answer]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Sun, 04 Aug 2019 19:43:52 GMT</pubDate>
            <atom:updated>2019-09-01T14:11:17.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWIY742FKYnd260L1jq-Xw.jpeg" /></figure><p>ML and DL are taking over everything, especially in the field of NLP. Recently I was working on the question and answer case study based on Standford Attentive Reader. But I was unable to find any proper resource that could be easily understandable by a beginner like me. So decided to write this post.</p><h3>Table of Contents</h3><ol><li>About Dataset</li><li>EDA</li><li>Attention</li><li>Keras Custom Layer</li><li>Input to Model</li><li>Prediction</li><li>Inferance</li><li>End Notes</li><li>References</li></ol><h3>About Dataset:</h3><p>Let’s first understand the dataset. For this case study, let’s use the Standford Question and Answer (SQUAD) dataset. You can download the dataset from <a href="https://rajpurkar.github.io/SQuAD-explorer/">here</a>.</p><blockquote><strong>S</strong>tanford <strong>Qu</strong>estion <strong>A</strong>nswering <strong>D</strong>ataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or <em>span</em>, from the corresponding reading passage, or the question might be unanswerable.</blockquote><p>The structure of JSON file is as below…</p><pre>structure:<br>  article (dict)<br>  ├── title (str)<br>  ├── paragraphs (dict)<br>      ├── context (str)<br>      └── qas (dict)        <br>          ├── question (str)<br>          ├── id (str)<br>          └── answers (dict)<br>              ├── answer_start (integer)<br>              └── text (str)<br>  ...<br>  └── paragraphs n<br>      ├── context<br>      └── qas</pre><p>First, extract all the data from the JSON file into the CSV file. This can be done by below code snippet…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9f15cea73b53c7ec5e4dbf7d3cd504d/href">https://medium.com/media/d9f15cea73b53c7ec5e4dbf7d3cd504d/href</a></iframe><p>Data cleaning was done on both context and question. As part of it, we removed punctuation marks from the text data and lowered it. Context data containing other than the English language were ignored as part of language detection.</p><h3><strong>D</strong>ata <strong>A</strong>nalysis:</h3><p>Exploratory Data Analysis was done on context, question and answer length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ok_6VcJJ4T8VJEODODFctQ.png" /><figcaption>Density plot for context, question and answer span.</figcaption></figure><p>It was found that avg. answer span was less than 4 words for the 75% of data points. Answer span of 15 words was considered for a safer side for prediction.</p><p>To understand how the machine does the reading comprehension, we need to understand the <strong><em>Attention</em></strong> first.</p><h3>All I Need is Attention:</h3><h4><strong>Why Attention….?</strong></h4><p>LSTM fails to capture information for longer sequences. What does that mean…? For e.g. consider a below context and try to answer to find the answer for the question</p><blockquote>Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champion <strong>Denver Broncos</strong> defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi&#39;s Stadium in the San Francisco Bay Area at Santa Clara, California. As this was the 50th Super Bowl, the league emphasized the &quot;golden anniversary&quot; with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as &quot;Super Bowl L&quot;), so that the logo could prominently feature the Arabic numerals 50.</blockquote><p><strong>Which NFL team represented the AFC at Super Bowl 50?</strong></p><p><em>Prediction: </em>Denver Broncos</p><p>The final <em>thought/Context</em> vector of LSTM fails to hold all the information in the context which is needed to answer the question. To answer the question we need to focus on a specific area of context. This is where attention comes handy.</p><p>Attention will give higher scores to the most relevant hidden state in the context of the question and fewer scores to other hidden states. Which is analogous to focusing more on the area where the actual answer is. In our case, it will be…</p><blockquote>The American Football Conference (AFC) champion <strong>Denver Broncos</strong> defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title.</blockquote><p>There are various functions used to calculate scores. Below is a summary table of several popular attention mechanisms and corresponding alignment score functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*CGr60uphxzWOv5x-NMd9bQ.png" /><figcaption>Score functions.</figcaption></figure><p>To understand attention in more detail, I would recommend you to read the blog <a href="https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3#ba24">Attn: Illustrated Attention</a> written by Raimi Karim.</p><p>In our case, based on the paper by <a href="https://arxiv.org/pdf/1704.00051.pdf">Danqi Chen</a>, we are going to use</p><ol><li>Weighted Sum attention for question embedding</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*ZWn14vEJjBNFwjui4hqmew.png" /><figcaption>weighted sum</figcaption></figure><p>2. Aligned Question Embedding:- where the attention score captures the similarity between <em>pi</em> and each question words <em>qj .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BxjN6g72kcwMEJljk13aA.png" /></figure><p>3. And Bilinear Similarity Term for prediction of start and end tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*sxcIAazfV2hpqXdlrH754g.png" /></figure><h3>Keras Custom Layer:</h3><h4>Yeah Seems ok…. But how to write code for this…?</h4><p>Let&#39;s get to the point. Writing code for above in TensorFlow is a tedious task and frustrating. Building model using Keras is an easy task, but unfortunately, attention implementation is not present as of now in Keras. To implement the above function we need to write <a href="https://keras.io/layers/writing-your-own-keras-layers/">custom Keras layer</a>.</p><p>To implement it in Keras we need to write just three simple method’s. It is as simple as that.</p><ul><li><strong><em>build(input_shape)</em></strong>: This is where you will define your weights. This method must set self.built = True at the end, which can be done by calling super([Layer], self).build().</li><li><strong><em>call(x)</em></strong>: This is where the layer&#39;s logic lives.</li><li><strong><em>compute_output_shape(input_shape)</em></strong>: In case your layer modifies the shape of its input, you should specify here the shape transformation logic.</li></ul><p>Let&#39;s start with the code for Weighted Sum attention...</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c228b269f8858dc7d39d55d912c642/href">https://medium.com/media/40c228b269f8858dc7d39d55d912c642/href</a></iframe><p>Here as per the equation, we need to implement a dense layer for every token on question word qj. Our score function is,</p><blockquote>simply dot product of weight vector followed by GLOVE representation of the question word.</blockquote><p>This operation is analogous to adding a simple dense layer. This is done in <strong><em>__init__().</em></strong></p><p>Inside call, we just need to apply a dense layer on the received output of LSTM to get attention_weights.</p><p>Make sure <strong><em>return_sequenes = True </em></strong>to get all hidden states form all the timesteps. To get the final vector, just multiply attention_weights with an output of LSTM and we are done.</p><p>All the remaining operations are for tensor shape manipulation. For a clear understanding of how tensor is multiplied, please check the concept of broadcasting in numpy.</p><p>Similarly, We can do for the other two…</p><p>Herewith code for the bilinear similarity…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1382d5e5ccd47c1ad7eca879dd4d507/href">https://medium.com/media/e1382d5e5ccd47c1ad7eca879dd4d507/href</a></iframe><h3>Input to Model</h3><p>The input to our model is a list of</p><p><strong><em>[questions ,context,pos_tag,exact_match.term_frequency]</em></strong></p><p>The given <em>question/context</em> is broken down into tokens and then embedded using the <strong><em>glove 300d. </em></strong>An example of question embedding is shown below. A similar approach is used for context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoTL9cyIyMmJkpfdfEMvUg.png" /></figure><h3>How model does Prediction…?</h3><p>At the paragraph level, the goal is to predict the span of tokens that is most likely the correct answer.</p><blockquote>We use the bilinear term to capture the similarity between each passage token pi and q (weighted question ) as input to <strong><em>BilinearSimilarity</em></strong> and compute the probabilities of each token being start and end.</blockquote><blockquote>During prediction, we choose the best span from token i to token i’ such that probability of start and end is maximized.</blockquote><p>How to do that…?</p><p>Since using start_probability and end_probability can construct a similarity matrix of size <em>(context_length x context_length).</em></p><p>And we know,</p><p><strong><em>answer_start &lt; answer_end</em></strong></p><p>The main logic in that, our answer is always going to be part of the upper triangular region of the matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHe6UptRkU8fPa4fWr08zA.png" /><figcaption>prediction.</figcaption></figure><p>And that’s it. Let&#39;s build the model and train it…</p><p>I was able to achieve micro f1 score of 40.33 % using a single layer BiLSTM with 64 units.</p><p>If you have a high computational resource, I would recommend you to implement the full architecture as described in the paper by <a href="https://arxiv.org/pdf/1704.00051.pdf">Danqi Chen</a>.</p><p>Full code and ipynb notebook can be found <a href="https://github.com/Raman-Raje/Machine-Reading-Comprehension-Neural-Question-Answer-"><em>here</em></a><em>.</em></p><h3>Inference:</h3><p>Let’s check what practically this f1 score of 40.33% indicates.</p><p>Let’s pass some question from different categories and try to predict answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*jkH0pDoOdPtCihiYbWLy4Q.png" /><figcaption>workflow</figcaption></figure><ol><li><strong><em>when did texts begin to appear solely in romance?</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_krB-yi4Oa6DMjjTHIQSQ.png" /></figure><p>The actual answer is given in <strong><em>by 1080</em></strong> and we predicted <strong><em>1080</em></strong>. Not bad...</p><p>2.<em> </em><strong><em>what species are usually hunted?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pn92qHBEpRwfqpRVul7cA.png" /></figure><p>That’s an exact prediction. Very nice.</p><p>3. <strong><em>in what indus valley civilization district was kalibangan within?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMYbg8XQe3g4II3xWWqoCQ.png" /></figure><p>Ohhh…! that is completely unexpected and wrong.</p><p>4. <strong><em>lack of strategic and hard power countries are excluded from what?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlNU8lweSY5IqNFjuJOh-Q.png" /></figure><p>Mostly correct..! but excluded a most important word <strong><em>UN</em></strong></p><p>It is wrong if I only show you correct prediction.</p><p>5. <strong><em>what is the name of the coldplay drummer from southampton?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shiEJ1Y1OBZVRfKjGQfh5A.png" /></figure><p>This is completely wrong.</p><h3>BERT Fine Tuned:</h3><p>Fine-tuned the SOTA bert model on SQUAD dataset using colab TPU.</p><ul><li>Most of the code is taken reference from google-research</li><li>The bert model is <strong>fine-tuned</strong> only.</li><li>Code has been modified as per necessity</li><li>Used the <strong>bert uncased_L-12_H-768_A-12</strong> model</li><li>All the references are mentioned in the reference section</li></ul><p>Got the f1 score of <strong><em>88.02%.</em></strong></p><h3>EndNote:</h3><ol><li>Thanks a lot if you have reached here. I expect the readers to be a bit generous and ignore the minor mistakes I might have made.</li><li>If the article appeals to you, do provide some comments, feedback, constructive criticism, etc.</li></ol><h3>References:</h3><ol><li><a href="https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3#ba24">https://towardsdatascience.com/attn-illustrated-attention-5ec4ad276ee3#ba24</a></li><li><a href="https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html?source=post_page---------------------------#a-family-of-attention-mechanisms">https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html?source=post_page---------------------------#a-family-of-attention-mechanisms</a></li><li><a href="https://rajpurkar.github.io/SQuAD-explorer/">https://rajpurkar.github.io/SQuAD-explorer/</a></li><li><a href="https://hanxiao.github.io/2018/04/21/Teach-Machine-to-Comprehend-Text-and-Answer-Question-with-Tensorflow/">https://hanxiao.github.io/2018/04/21/Teach-Machine-to-Comprehend-Text-and-Answer-Question-with-Tensorflow/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983d3a1dd42c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BackPropagation through LSTM: A differential approach]]></title>
            <link>https://medium.com/@raman.shinde15/backpropagation-through-lstm-a-differential-approach-4eb5ecc58d9d?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb5ecc58d9d</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[bptt]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Fri, 17 May 2019 13:22:05 GMT</pubDate>
            <atom:updated>2019-05-17T13:29:08.113Z</atom:updated>
            <content:encoded><![CDATA[<p>LSTM’s are very powerful but they are confusing if you are a beginner. To understand things internally, we need to understand the back propagation.</p><p>So, let’s dive in and try to understand how things work…</p><p>For Simplicity, let&#39;s ignore the non-linearities.</p><h3><strong>Prerequisites:</strong></h3><p>This is a slightly advanced topic which requires knowledge of</p><ol><li>working of LSTM</li><li>Multi path derivative and partial differentiation</li><li>Chain Rule and understanding of back propagation.</li></ol><p>All the necessary references are mentioned at the end. I strongly recommend going through it if you are new to this.</p><h3>Forward Pass:</h3><p>LSTM consists of cell state(St) and various gates. Cell state is one core component of LSTM and it holds the information that is has learned over time.</p><p>LSTM has mainly three gates</p><ol><li>Keep Gate: It determines what information to keep from the previous state and what to erase.</li><li>Input Gate: Adds the new information form present input to cell state. Cell state gets updated.</li><li>Output Gate: Produces the final output vector.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWCpGENt8tnhi7zoMe3zoQ.png" /><figcaption>Single LSTM Unit</figcaption></figure><p>Let&#39;s write down equations for a forward pass. Ignoring the non-linearities i.e all bias terms are set to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODc6IBiVV01frIC3t6eVeg.jpeg" /><figcaption>Equations for forward pass</figcaption></figure><p>During forward pass, we concatenate input x with previous state output i.e [x,h(t-1)] and fed it to LSTM. So, we can write</p><p><strong><em>Z = W x I</em></strong></p><p>where,</p><p>I = concatenated input vector</p><p>W = weight matrix of input weights and hidden state weights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*q39SetIpg4Vbzc8oqw1NJA.png" /></figure><h3>Backward Pass:</h3><p>During backward pass, we calculate local gradients at each step. Gradients are accumulated before being back propagated the previous time steps.</p><p>We write gradient of <strong><em>dl/dh ==&gt; δh</em></strong>. Since this helps us to have the concise notation and avoids repetition of <strong><em>dl</em></strong> every time.</p><p>One important point is that gradients are always w.r.t to the final output.</p><p>Let&#39;s calculate gradients…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5wX8NuEa3Q1ZgB7wcFiyw.png" /><figcaption>Gradient calculation for the state.</figcaption></figure><p>At State, gradient comes from two sources to the top summation node at <strong>St. </strong>Both paths are mentioned in the above figure.</p><p>The gradient at state evaluates to…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oL4BNr7_MtDmcaoo162-pg.jpeg" /><figcaption>state gradient</figcaption></figure><p>Which can be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rv5KZ1GyMr2q7wb5FdBBGw.jpeg" /></figure><p>Gradients at gates…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qihUi2mvVeykbL_bisiwxw.jpeg" /><figcaption>Gradient at gates.</figcaption></figure><p>We can write these gradients in terms of input to gates i.e</p><p><strong><em>(W* X + U * h)</em></strong></p><p>as shown in forward pass equations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VbdfBASRsEMLHlU8gzrKQ.jpeg" /><figcaption>gradients w.r.t to inputs to gates.</figcaption></figure><h3><strong>Weight Updation:</strong></h3><p>The aim all the above equations is to find the weights that minimizes loss.</p><p>So , the most important question is how to updates weight. We know,</p><p><strong><em>Z = W x I</em></strong></p><p>We can obtain <strong><em>δZ</em></strong> from above equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*Q2KvFVo7FQ90v0fqXHhQzw.png" /></figure><p>Our aim is to get <strong><em>δh </em></strong>and<strong><em> δW.</em></strong></p><p><strong><em>δh ==&gt;</em></strong> Useful to back propagate to previous time steps.</p><p><strong><em>δW ==&gt; </em></strong>Useful for weight update.</p><p><strong><em>δh </em></strong>can be calculated from <strong><em>δI.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*xIVpV-Sr2zEdUnVDL0n58w.png" /></figure><p>In the same way we can obtain<strong><em> δW.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*XBG-b956qABDfwakFJu6FQ.png" /></figure><p>Remember, if input has T time-steps, we need to accumulate all the gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*pRN7RAQ4fqCIlnMvtvcomg.png" /></figure><p>Finally , weights are updated using appropriate gradient descent optimization algorithm.</p><h3>References:</h3><ol><li><a href="http://arunmallya.github.io/writeups/nn/lstm/index.html#/">http://arunmallya.github.io/writeups/nn/lstm/index.html#/</a></li><li><a href="http://cs231n.github.io/optimization-2/">http://cs231n.github.io/optimization-2/</a></li><li><a href="https://medium.com/@aidangomez/let-s-do-this-f9b699de31d9">https://medium.com/@aidangomez/let-s-do-this-f9b699de31d9</a></li><li><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb5ecc58d9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Captioning With Flickr8k Dataset & BLEU]]></title>
            <link>https://medium.com/@raman.shinde15/image-captioning-with-flickr8k-dataset-bleu-4bcba0b52926?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bcba0b52926</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[ds-in-the-real-world]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Wed, 01 May 2019 18:22:49 GMT</pubDate>
            <atom:updated>2019-09-24T11:29:28.609Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inside AI</h4><h3>Table of Contents:</h3><ol><li>Introduction</li><li>Why Flickr8k dataset</li><li>Let’s understand the data</li><li>EDA…</li><li>How to featurize images..?</li><li>Caption Preprocessing…</li><li>Sequential Data preparation</li><li>BLEU…?</li><li>Inference</li><li>Conclusion</li><li>References</li></ol><h3>1. Introduction:</h3><p>RNN’s have become very powerful. Especially for sequential data modelling. Andrej Karapathy has very nicely explained the use of RNN’s in his blog <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">The Unreasonable Effectiveness of Recurrent Neural Networks</a>. There are basically four types of RNN’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kje9TpsSvMGeBF6vIv6k5Q.jpeg" /><figcaption>Types of RNN’s.</figcaption></figure><p>Image captioning is an application of one to many RNN’s. for a given input image model predicts the caption based on the vocabulary of train data. We are considering the Flickr8K dataset for this case study. The official site for data is not working, but thanks to <strong>Jason Brownlee.</strong> From <a href="https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/">here </a>you can download the dataset.</p><h3><strong>2. Why Flickr8k dataset…?</strong></h3><ol><li>It is small in size. So, the model can be trained easily on low-end laptops/desktops...</li><li>Data is properly labelled. For each image 5 captions are provided.</li><li>The dataset is available for free.</li></ol><h3><strong>3. Let’s understand the data…</strong></h3><p>Data pre-processing and cleaning is an important part of the whole model building process. Understanding the data helps us to build more accurate models.</p><p>After extracting zip files you will find below folders…</p><ol><li>Flickr8k_Dataset: Contains a total of 8092 images in JPEG format with different shapes and sizes. Of which 6000 are used for training, 1000 for test and 1000 for development.</li><li>Flickr8k_text : Contains text files describing train_set ,test_set. Flickr8k.token.txt contains 5 captions for each image i.e. total 40460 captions.</li></ol><h3>4. EDA…</h3><p>We have mainly two types of data.</p><ol><li>Images</li><li>Captions (Text)</li></ol><p>The size of the training vocabulary is 7371. The top 10 most frequent words are</p><pre>(&#39;a&#39;, 46784),(&#39;in&#39;, 14094),(&#39;the&#39;, 13509),(&#39;on&#39;, 8007),(&#39;is&#39;, 7196),<br>(&#39;and&#39;, 6678),(&#39;dog&#39;, 6160),(&#39;with&#39;, 5763),(&#39;man&#39;, 5383),       (&#39;of&#39;, 4974)</pre><p>Since the words which occur very less does not carry much information. We are considering words with a frequency of more than 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*biFTpf4RjIx1K9faQrfrJA.png" /><figcaption>Distribution of word count.</figcaption></figure><p>The distribution of top 50 words is as follows…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWoO6P3OAxKBT3mjPT-Gtg.png" /></figure><p>Here with the distribution of the least frequent word we removed earlier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24Hs8APjNkZ2g_XWWIDtvg.png" /><figcaption>Distribution of lease frequent words with a frequency of less than 1</figcaption></figure><p>Avg caption length per image in the training</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yWnS9_kE-H7A4U4aNF0Lg.png" /></figure><p>The mean,std-dev and percentiles is as follows…</p><pre>count    6000.000000<br>mean       10.815467<br>std         2.057137<br>min         4.200000<br>25%         9.400000<br>50%        10.600000<br>75%        12.200000<br>max        19.200000</pre><p>Maximum Sequence length found 37.</p><h3><strong>5. How to Featurize images….?</strong></h3><p>There are already pre-trained models on standard Imagenet dataset provided in keras. Imagenet is a standard dataset used for classification. It contains more than 14 million images in the dataset, with little more than 21 thousand groups or classes.</p><p>We will be using InceptionV3 by google. The research paper can be found <a href="https://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Szegedy_Rethinking_the_Inception_CVPR_2016_paper.pdf">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wBEk0UbYry_7fW1cThyQ-w.png" /></figure><h4>Why Inception…?</h4><ol><li>It has a smaller weight file i.e approx 96 MB</li><li>It is faster to train.</li></ol><p>We will remove soft-max layer form inception as we want to use it as a feature extractor. For a given input image inception gives us 2048 dimensional feature extracted vector. The code is as follow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55e6201eb3617a70f0732945379f9323/href">https://medium.com/media/55e6201eb3617a70f0732945379f9323/href</a></iframe><p>For every training image, we are resizing it to (299,299) and then passing it to Inception for feature extraction. Remember to save the train_image_extracted dictionary. it will save a lot of time if you are fine-tuning the model.</p><h3><strong>6. Caption Preprocessing...</strong></h3><p>Each image in the dataset is provided with 5 captions. For e.g image 1000268201_693b08cb0e.jpeg has captions</p><pre>[&#39;A child in a pink dress is climbing up a set of stairs in an entry way .&#39;,<br> &#39;A girl going into a wooden building .&#39;,<br> &#39;A little girl climbing into a wooden playhouse .&#39;,<br> &#39;A little girl climbing the stairs to her playhouse .&#39;,<br> &#39;A little girl in a pink dress going into a wooden cabin .&#39;]</pre><p>Captions are read from Flickr8k.token.txt file and stored in dictionary k:v where k = image id and value =[ list of caption ].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d01d650f4f46f060b9e5808f2b3cdc38/href">https://medium.com/media/d01d650f4f46f060b9e5808f2b3cdc38/href</a></iframe><p>Since there are 5 captions for each image and we have preprocessed and encoded them in below format</p><p>“startseq “ + caption + “ endseq”</p><p>The reason behind startseq and endseq is,</p><p><strong>startseq</strong> : Will act as our first word when feature extracted image vector is fed to decoder. It will kick-start the caption generation process.</p><p><strong>enseq</strong> : This will tell the decoder when to stop. We will stop predicting word as soon as endseq appears or we have predicted all words from train dictionary whichever comes first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSFjJvgi-wV2C2qIJvnOCg.jpeg" /></figure><h3><strong>7. Sequential Data preparation….</strong></h3><p>This one is a tricky part. how do we convert this data to sequential form..?</p><p>For the understanding purpose, we will consider the above image and corresponding sequences where a bunch of people are swimming in water.</p><p>First fed the image to inception and get feature extracted 2048 dimensional vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*AJ87F0vEBqTcfUz1YGi-vg.png" /><figcaption>transfer learning</figcaption></figure><p><strong><em>caption:</em></strong> startseq a bunch of people swimming in water endseq.</p><p>we will form the sequence as below.</p><pre>Image_vector + [&#39;startseq&#39;]<br>Image_vector + [&#39;startseq&#39;, &#39;a&#39;]<br>Image_vector + [&#39;startseq&#39;, &#39;a&#39;, &#39;bunch&#39;]<br>Image_vector + [&#39;startseq&#39;, &#39;a&#39;, &#39;bunch&#39;, &#39;of&#39;]<br>Image_vector + [&#39;startseq&#39;, &#39;a&#39;, &#39;bunch&#39;, &#39;of&#39;, &#39;people&#39;]<br>Image_vector + [&#39;startseq&#39;, &#39;a&#39;, &#39;bunch&#39;, &#39;of&#39;, &#39;people&#39;,&#39;swimming&#39;]<br>...</pre><p>convert the sequence to numerical with the help of vocabulary. Please refer <a href="https://towardsdatascience.com/image-captioning-with-keras-teaching-computers-to-describe-pictures-c88a46a311b8">this</a> for in detail diagrammatic explanation. Below is the source code for dataset preparation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1cb961a06beb4c7cc19bed99fe57fe6/href">https://medium.com/media/e1cb961a06beb4c7cc19bed99fe57fe6/href</a></iframe><h4>The problem….?</h4><p>There is a problem if we fit all the data point at once to model. Since we have total 40k captions.</p><p>Max length of the caption is 37. So each caption in encoded into a sequence of 37.</p><p>Let&#39;s assume on an average, to encode a sequence we need 10 rows.</p><p>And, each word in a sequence will be embedded to 300-dimensional glove vector.</p><p>So considering 1 byte for each number , our final data matrix will occupy..</p><p>40k x 10x((37 x 200) + 2048) ===&gt; approx. 3.7GB at least.</p><h4><strong>Solution:</strong></h4><p>Rather than getting whole data at one time, use data_generator to generate data in batches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5b67753757a6f2a60410dd3f40b876/href">https://medium.com/media/fd5b67753757a6f2a60410dd3f40b876/href</a></iframe><h3>8. BLEU…?</h3><p>BLEU stands for Bilingual Evaluation Understudy.</p><p>It is an algorithm, which has been used for evaluating the quality of machine translated text. We can use BLEU to check the quality of our generated caption.</p><ul><li>BLEU is language independent</li><li>Easy to understand</li><li>It is easy to compute.</li><li>It lies between [0,1]. Higher the score better the quality of caption</li></ul><p><strong>How to calculate BLEU score…?</strong></p><p><strong>predicted caption</strong>= “the weather is good”</p><p><strong>references:</strong></p><ol><li>the sky is clear</li><li>the weather is extremely good</li></ol><p>first, convert the predicted caption and references to unigram/bigrams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*0-ayyhbUm61lyF0bf0cVyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyakPUW9fNJqpKvsI8Glvg.jpeg" /></figure><p>BLEU tells how good is our predicted caption as compare to the provided 5 reference captions.</p><h3>9. Inference…</h3><p>For a given feature extracted test image and startseq as i/p to model, we get a distribution of probability over all the words in the vocabulary. The word corresponding to the index of maximum probability is the predicted word.</p><p>We stop predicting when the word “endseq” appears.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbf3b9e9b432f5f29c6d0a0ad64c89ec/href">https://medium.com/media/fbf3b9e9b432f5f29c6d0a0ad64c89ec/href</a></iframe><p>Here are some examples of my ipnb notebook...</p><ul><li>Prediction is very good. It describes an image correctly. Observe the BLEU value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Uou-r55OLQnDEd3WR5GtkQ.jpeg" /></figure><ul><li>A child is predicted correctly but the model is treating adults as a child. BLEU value drops here as prediction is not analogous to references.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ci6_uZvk0wD6itShj7qqnQ.png" /></figure><ul><li>Not a good one. BLEU is very small, close to zero except, unigram.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*LleYrhydAObr6N6cvLW2iw.png" /></figure><ul><li>Nooo… not a good one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*OQxg50E3CGjEGU1nrTFhJw.png" /></figure><ul><li>Nice try, but not an accurate caption. Observe the high value of unigram</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*pMo_-UmacJm-ADtbAP8oXw.png" /></figure><ul><li>Woman predicted as a little boy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*4Q6b_wexn7njKiErX-dFFw.png" /></figure><h3>10. Conclusion:</h3><ol><li>The performance of the model can be improved by training it on a larger dataset and hyperparameter tuning.</li><li>From above we can observe that unigram bleu scores favour short predictions.</li><li>Prediction is good if all the BLEU scores are high.</li></ol><p>That’s it from my end…!</p><p>For whole code please check the ipython notebook <a href="https://github.com/Raman-Raje/ImageCaptioning">here</a>.</p><p>End.</p><h3>11. References:</h3><ol><li><a href="https://towardsdatascience.com/intuitive-understanding-of-attention-mechanism-in-deep-learning-6c9482aecf4f?%24Ga=true">https://towardsdatascience.com/intuitive-understanding-of-attention-mechanism-in-deep-learning-6c9482aecf4f?%24Ga=true</a></li><li><a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">http://karpathy.github.io/2015/05/21/rnn-effectiveness/</a></li><li><a href="https://fairyonice.github.io/Develop_an_image_captioning_deep_learning_model_using_Flickr_8K_data.html">https://fairyonice.github.io/Develop_an_image_captioning_deep_learning_model_using_Flickr_8K_data.html</a></li><li><a href="http://cs231n.github.io/transfer-learning/">http://cs231n.github.io/transfer-learning/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bcba0b52926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding sequential/TimeSeries data for LSTM….]]></title>
            <link>https://medium.com/@raman.shinde15/understanding-sequential-timeseries-data-for-lstm-4da78021ecd7?source=rss-e6bc96af9357------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da78021ecd7</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[lstm]]></category>
            <dc:creator><![CDATA[Raman Shinde]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 09:36:35 GMT</pubDate>
            <atom:updated>2019-09-24T14:48:58.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding sequential/TimeSeries data for LSTM…</h3><p>LSTM’s are very powerful but they are a little bit confusing, especially for beginners. Recently I was working on a deep Learning case study of Human Activity Recognization in which the dataset provided as time series data. You can download the dataset from <a href="https://www.kaggle.com/uciml/human-activity-recognition-with-smartphones">here</a>.</p><p>Let’s dig into it and understand how things work...</p><h3>Dataset Overview</h3><p>The data is obtained from an experiment which has been carried out with a group of 30 volunteers within an age bracket of 19–48 years. Each person performed six activities wearing a smartphone (Samsung Galaxy S II) on the waist. So, it is a multiclass classification problem.</p><pre><em># Activities are the class labels</em><br><em># It is a 6 class classification</em><br>ACTIVITIES = {<br>    0: &#39;WALKING&#39;,<br>    1: &#39;WALKING_UPSTAIRS&#39;,<br>    2: &#39;WALKING_DOWNSTAIRS&#39;,<br>    3: &#39;SITTING&#39;,<br>    4: &#39;STANDING&#39;,<br>    5: &#39;LAYING&#39;,<br>}</pre><p>After downloading the dataset, you will find two types of data.</p><ol><li>Already featured data with a 561-feature vector with time and frequency domain variables. (Ready data for ML)</li><li>The raw data, i.e 3-axial acceleration and gyroscope signal. This data were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window).</li></ol><p>We are going to work on raw time-series signal data. There are a total of 7352 data points for each axis. What that means…?</p><p>Our data is sampled at 2.56 sec with 50% overlap.</p><p>for 1 window ===&gt; 2.56 sec.</p><p>for 2nd window = (2.56+1.28) = 3.84 sec.</p><p>So, for total 7352 data points,</p><p>we have time-series data of time length 14,115 sec. i.e. nearly 235 minutes. Close to 4 hours.</p><p><strong>The question is given time series data, How to frame it so that it can be fed to LSTM..?</strong></p><p>Before that, let&#39;s understand some terminologies in LSTM.</p><h3>More about LSTM</h3><h4>1. Input Shape</h4><p>LSTM input shape is always 3D tensor. i.e</p><p><strong><em>(samples , sequence,data_dim)</em></strong></p><p>or</p><p><strong><em>(batch_size,timesteps,features)</em></strong></p><p>Take a look at following code snippet to understand more...</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7629a212548577203bf5001a31c41259/href">https://medium.com/media/7629a212548577203bf5001a31c41259/href</a></iframe><p>Since batch_size is generally given at the time of training and is a variable. So, change in batch_size will give an error if you use <em>batch_input_shape</em>.</p><p>So it&#39;s better to use <em>inut_shape</em>.</p><p>The output of LSTM can be 2D/3D depending on return sequences.</p><h4>2. Return Sequences:</h4><p>In LSTM, if you want to access the output of hidden state at each time step, then this parameter is going to help you. This can be done by setting</p><p><strong><em>return_sequences =True.</em></strong></p><p>It is must, when you are stacking LSTM layer’s, to make sure that the next layer gets 3D input. What does that mean..?</p><p>Take a look at the following picture...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*4NVOF-HvFI6ZH6jLKZO99w.png" /><figcaption>return_sequences in LSTM</figcaption></figure><p>By default, <strong><em>return_sequences = False. </em></strong>The<strong><em> </em></strong>output of LSTM is,</p><p>2D tensor ====&gt; <em>(batch_size,units) i.e (16,5) or (None,5) </em>in our case.</p><p>But when you want LSTM output from each <em>timestep, </em>then set <strong><em>return_sequneces = True. </em></strong>Which will give 3D tensor as output,</p><p>3D tensor ==&gt; <em>(batch_size,timesteps,units) i.e (16,128,5) or(None,128,5).</em></p><h4><strong>3. Repeat Vector:</strong></h4><p>Repeat vector tells us how much time we need to repeat the <em>output/final hidden state/thought </em>vector. In simple, how much repetitions do we need to perform? This is mostly used in an encoder-decoder case.</p><p>Take a look at below image to understand more…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tY-hvESk4lCqZqOhM-QnDQ.jpeg" /><figcaption>Repeat vector</figcaption></figure><p>Repetition is based on output <em>sequence/timesteps</em> length.</p><p>Here is code snippet taken from keras for better understanding. Observe the output shape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13a4f30822c6b2ea6d3d97526f78ddc1/href">https://medium.com/media/13a4f30822c6b2ea6d3d97526f78ddc1/href</a></iframe><h4>4. Back-Propagation through LSTM:</h4><p>To get clear understanding of how exactly things works inside, we need to understand how the back-propagation takes place in LSTM through time. I have tried to explain forward pass , backward pass and back propagation in LSTM <a href="https://medium.com/@raman.shinde15/backpropagation-through-lstm-a-differential-approach-4eb5ecc58d9d?source=friends_link&amp;sk=78eadcaf19b2524063ccab25d3a94793"><em>here</em></a><em>.</em></p><h3>Data Preparation</h3><h4>Let’s come back to our problem</h4><p>For simplicity let’s consider x-axis body_acc time series signal. The signal would look like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*oLtDHHVJAdyvCvboZKMkfw.png" /></figure><p>As we have a total of 128 readings from each window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*aTCKh_i_oVZYo5NVQ90vUw.png" /></figure><p>We can do the same for the other 8 time-series signals. Then construct a vector from these readings. The resultant vector will have the size of [1x128].</p><p>What we will have is like this.</p><pre>timesteps = len(X_train[0])<br>input_dim = len(X_train[0][0])<br>n_classes = _count_classes(Y_train)<br><br>print(timesteps) <br>print(input_dim)<br>print(len(X_train))<br>128<br>9<br>7352</pre><h4>How do we represent this data..?</h4><p>As we know, LSTM requires 3D input tensor. We have,</p><p><em>timesteps/sequence = 128</em></p><p><em>input_dim/features = 9</em></p><p><em>total_samples = 7352</em></p><p>Transform the 128 readings vector to the column vector. Do the same ofr other features and concatenate all of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*3sohp69xZX8asoSZqUXTgw.png" /><figcaption>A single data sample</figcaption></figure><p>Now, we have 2D tensor, <em>(128,9) ==&gt;(timesteps,features)</em> for 1 slice of time.</p><p>Remember LSTM requires input as a 3D tensor.</p><p><strong><em>(batch_size,timesteps,features)</em></strong></p><p>Since batch_size can be varied during training. Generally, it is not given can be left as <em>None</em>. So, <em>input_shape = (timesteps,features).</em></p><p>For eg., if we set the <em>batch_size</em> to 16 then our tensor will look like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*YnGyWhlkVc88XYOvvQ1QbA.png" /><figcaption>Example of the 3D tensor.</figcaption></figure><p>Now, we can feed this tensor to our LSTM. The code snippet is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbcc5e237e69e4638cbdac045fca89a/href">https://medium.com/media/bdbcc5e237e69e4638cbdac045fca89a/href</a></iframe><h4>How Does the LSTM processes the input 3D tensor…?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*OD1KyJUwPKXiHKdZfOfPAA.jpeg" /></figure><p>Let&#39;s understand how LSTM internally process this…</p><p>Consider a <em>single sample/batch_size</em> of 1 for simplicity. So, input to LSTM will be <em>(1,128, 9)</em>.</p><p>Now, we have 128 (1 x 9) dimensional row vectors representing nine features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnGqMA9-JUBFl-w1XXET0A.png" /><figcaption>Breaking tensor to individual inputs</figcaption></figure><p>Each of this row vector is passed to LSTM as per timesteps. LSTM will produce final output 2D tensor <strong><em>(batch_size, units)</em></strong> if<em> </em><strong><em>return_sequences=False</em></strong><em>.</em></p><p>And 3D tensor <strong><em>(batch_size, timesteps, units)</em></strong> if<em> </em><strong><em>return_sequences=True</em></strong></p><p>The unroll version of LSTM is shown below. Here for understanding, we have considered <em>batch_size</em> = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaAcylXyJyh6gKc5IJEqZQ.png" /><figcaption>Unroll LSTM Version</figcaption></figure><h3>Model Traning</h3><h4>Let&#39;s train the model:</h4><p>Now we are ready to train our LSTM network. There is no scientific formula for which model/architecture to use. Since we have a small dataset, I have tried and tested various configurations to get the best results.</p><ol><li>The 2-Layer architecture was used with dropout varying from 0.4 to 0.6</li><li>Single layer LSTM with 128 units with variable dropout.</li><li>Single layer LSTM with 64 units with variable dropout.</li></ol><p>Every time when dropout was reduced, overfitting in the model was observed. Which is expected behaviour due to the increase in the number of hyperparameters.</p><p>Below is the summary of the results I got.</p><pre>+--------------+---------+---------------------+--------------------+<br>|    Model     | Dropout |      Test Loss      |   Test Accuracy    |<br>+--------------+---------+---------------------+--------------------+<br>| 2 Layer LSTM |   0.6   | 0.28306087015040565 | 0.9104173736002714 |<br>| 2 Layer LSTM |   0.5   |  0.2612545601277785 | 0.9155072955548015 |<br>| 2 Layer LSTM |   0.4   | 0.38503823976051715 | 0.9029521547336274 |<br>|  LSTM(128)   |   0.5   | 0.36085634430697744 | 0.9090600610790635 |<br>|  LSTM(128)   |   0.6   |  0.3239700397747638 | 0.9182219205972175 |<br>|  LSTM(128)   |   0.7   |  0.3424076799891987 | 0.9110960298608755 |<br>|   LSTM(64)   |   0.2   | 0.29805776571111475 | 0.9032914828639295 |<br>|   LSTM(64)   |   0.4   |  0.302408124333561  | 0.9032914828639295 |<br>|   LSTM(64)   |   0.5   |  0.3958842686579247 | 0.8914149983033594 |<br>|   LSTM(64)   |   0.6   |  0.5637321862749768 | 0.8948082796063793 |<br>+--------------+---------+---------------------+--------------------</pre><p>The results can be improved by training the network on a large dataset and trying out various architectures. Full code and ipynb notebook can be found <a href="https://github.com/Raman-Raje/Human-Activity-Recognization"><em>here.</em></a></p><h3><strong>EndNote:</strong></h3><ol><li>Thanks a lot if you have reached here. This is my first attempt in blogging so I expect the readers to be a bit generous and ignore the minor mistakes I might have made.</li><li>All the values considered in this example are selected as per convenience.</li><li>If the article appeals to you, do provide some comments, feedback, constructive criticism, etc.</li></ol><h3><strong>References:</strong></h3><ol><li><a href="https://stackoverflow.com/questions/51749404/how-to-connect-lstm-layers-in-keras-repeatvector-or-return-sequence-true">https://stackoverflow.com/questions/51749404/how-to-connect-lstm-layers-in-keras-repeatvector-or-return-sequence-true</a></li><li><a href="https://stats.stackexchange.com/questions/274478/understanding-input-shape-parameter-in-lstm-with-keras">https://stats.stackexchange.com/questions/274478/understanding-input-shape-parameter-in-lstm-with-keras</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da78021ecd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>