<?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 Divyanshu Dimri on Medium]]></title>
        <description><![CDATA[Stories by Divyanshu Dimri on Medium]]></description>
        <link>https://medium.com/@ddimri?source=rss-197857c39d34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VgbQdQ_L5PhpCp9b</url>
            <title>Stories by Divyanshu Dimri on Medium</title>
            <link>https://medium.com/@ddimri?source=rss-197857c39d34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:22:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ddimri/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[Retrieval-Augmented Generation (RAG) Pipeline Documentation- Graph-RAG]]></title>
            <link>https://ddimri.medium.com/retrieval-augmented-generation-rag-pipeline-documentation-graph-rag-7cd425e58321?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd425e58321</guid>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 18:38:34 GMT</pubDate>
            <atom:updated>2025-04-06T04:57:33.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retrieval-Augmented Generation (RAG) Pipeline for Ontologies- Graph-RAG</h3><h3><strong>Overview</strong></h3><p>Organizations managing large knowledge bases often face challenges in <strong>manually constructing ontologies</strong> — structured representations of relationships between key entities. This process is not only time-consuming and prone to errors but also lacks scalability.</p><p>This project aims to <strong>automate ontology creatio</strong>n using <strong>Generative AI techniques,</strong> enabling the extraction and organization of meaningful relationships within a given knowledge base. The generated ontology is then utilized in a <strong>Retrieval-Augmented Generation (RAG) pipeline</strong> to enhance information retrieval and question-answering capabilities.</p><p>The proposed workflow consists of four key stages:</p><ol><li><strong>Text Processing</strong> — Extracting entities and relationships from unstructured text.</li><li><strong>Ontology Construction</strong> — Structuring extracted knowledge into a graph-based ontology.</li><li><strong>Cypher Query Fuzzy Matching</strong> — Extracting information using fuzzy matching.</li><li><strong>RAG-based Question Answering</strong> — Leveraging the extracted ontology to improve search relevance and AI-generated responses.</li></ol><h4>Business Impact</h4><p>By integrating ontology-driven retrieval with generative AI, this approach enhances <strong>information discovery, reduces search time, and improves response relevance</strong> in large-scale knowledge bases. The result is a more <strong>efficient and intelligent search mechanism</strong>, leading to better decision-making and user experience.</p><h3>1. Introduction</h3><p>This project implements a <strong>Retrieval-Augmented Generation (RAG) pipeline</strong> that allows users to query a <strong>knowledge base</strong> built from the Live Feed of the input documents (<strong>Any</strong> <strong><em>Book</em></strong> or its <strong><em>URL</em></strong> — <strong><em>[.txt formatted]</em></strong>). The system extracts knowledge, structures it into an <strong>ontology</strong>, and enables querying through a <strong>Streamlit-based UI</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNcZt16EOM738V1dEhbFIA.png" /><figcaption><strong><em>Streamlit UI (GR-1.1)</em></strong></figcaption></figure><h3>2. Features &amp; Implementation Detail</h3><blockquote><strong>Ontology Creation</strong></blockquote><p>Constructs a structured representation of entities and relationships from the book.</p><p>The ontology creation is done leveraging the Knowledge Graph with <strong>Lang-Chain</strong> and <strong>Neo4j</strong>. Graphs are great at representing and storing heterogeneous and interconnected information in a structured manner, effortlessly capturing complex relationships and attributes across diverse data types.</p><p><strong><em>How did we do that ?</em></strong></p><p>For this, we have implemented an <strong>LLMGraphTransformermodule</strong> that significantly simplifies constructing and storing a knowledge graph in a graph database. One sample output from the given <em>reference book </em>can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RPh-1MccOo7uBBhw" /><figcaption><strong>Structured Output from Cypher Query — Query Relevancy (GR-2.1)</strong></figcaption></figure><p>The <strong>structured data</strong> shown in the output represents how we extracted knowledge from <em>Pride and Prejudice</em> and stored it in Neo4j. The relationships in the graph help to <strong>semantically structure the extracted information</strong>, making it easier to query.</p><p>Each <strong>node</strong> (entity) in the knowledge graph represents <strong>a key concept</strong> from <em>Pride and Prejudice</em>, such as:</p><ul><li><strong>Book Title</strong> (e.g., <em>Pride and Prejudice</em>)</li><li><strong>Author</strong> (e.g., <em>Jane Austen</em>)</li><li><strong>Characters</strong> (e.g., <em>Darcy, Lydia, Wickham</em>)</li><li><strong>Publication Details</strong> (e.g., <em>Publisher, Illustrator, Year of Publication</em>)</li><li><strong>Story Settings</strong> (e.g., <em>Derbyshire</em>), etc</li></ul><p>Each <strong>edge (relationship)</strong> defines how these entities are connected.</p><p>To create this <strong>structured knowledge graph</strong>, we utilized an <strong>LLMGraphTransformer module</strong>, which simplifies the process of:</p><ol><li><strong>Extracting entities</strong> from unstructured text using <strong>LLM-based Named Entity Recognition (NER)</strong>.</li><li><strong>Identifying relationships</strong> using <strong>LLM-assisted relation extraction</strong>.</li><li><strong>Storing this structured information</strong> in <strong>Neo4j</strong>, forming a <strong>graph database</strong>.</li></ol><p><strong>This enables natural language querying</strong>, where the LLM can generate <strong>Cypher queries</strong> to fetch precise relationships.</p><p>Breakdown of some Key-Relationships from <strong><em>GR-2.1</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpdW6JPmy41s24RbH3-spA.png" /><figcaption><strong>Key-Relationships (<em>GR-2.1)</em></strong></figcaption></figure><ul><li><strong>Chunking &amp; No Embedding Strategy</strong>: Splits book content and uses the cypher query for the retrieval of relevant information from <strong>Graph Database</strong>.</li></ul><h4>Chunking Approach</h4><p>To efficiently process large documents, we use <strong>RecursiveCharacterTextSplitter</strong> from LangChain for <strong>document chunking</strong>. This method ensures that text is split into <strong>manageable segments</strong> while preserving context.</p><ul><li><strong>Chunk Size:</strong> 514 tokens</li><li><strong>Chunk Overlap:</strong> 20% (default, ensuring contextual continuity)</li><li><strong>Process:</strong></li></ul><ol><li>The document is first loaded as a Document object.</li><li>It is then passed through RecursiveCharacterTextSplitter to generate <strong>base nodes</strong>.</li><li>A <strong>custom overlap function</strong> was created to provide more flexibility &amp; to ensure chunks maintain <strong>contextual coherence</strong> by overlapping <strong>20% of the content</strong> between segments.</li></ol><h4>Cypher Query Strategy</h4><p>This implementation takes a <strong>structured retrieval approach</strong> using <strong>Cypher queries in Neo4j</strong> instead of embedding-based retrieval. Here’s a detailed breakdown of how it works:</p><p><strong>Full-text Search with Fuzzy Matching:</strong></p><ul><li>The function generate_full_text_query(input: str) processes the input query by sanitizing it using remove_lucene_chars.</li><li>It generates a <strong>fuzzy search query</strong> (~2 operator) to allow for minor variations in word spellings.</li><li>Example: If the user searches for <strong>“Elizabeth Bennet”</strong>, the search still retrieves relevant results even if there are minor spelling differences like <strong>“Elisabeth Bennet”</strong>.</li></ul><p><strong>Structured Retrieval using Cypher Queries:</strong></p><ul><li>The structured_retriever(question: str) function:<br>Extracts key <strong>entities</strong> from the question using</li></ul><pre>entity_chain.invoke({&quot;question&quot;: question})</pre><ul><li>Uses <strong>Neo4j’s Full-Text Indexing</strong> (<strong><em>CALL db.index.fulltext.queryNodes</em></strong>) to retrieve relevant nodes from the knowledge graph.</li><li>Traverses the <strong>relationships</strong> between entities using Cypher queries.</li><li>Returns meaningful <strong>graph-based structured data</strong>, not just text chunks.</li></ul><p><strong>Dynamic Prompt Engineering for Answer Generation:</strong></p><ul><li>Instead of using embeddings for similarity search, the retrieved structured data is fed into a <strong>prompt-engineered LLM</strong> for final answer synthesis.</li><li>This approach ensures responses are generated with a <strong>graph-structured context</strong>, making them <strong>factually grounded</strong> in the knowledge graph.</li><li><strong>Natural Language Querying</strong>: Users can input queries and receive relevant answers.</li></ul><p>Implementing <strong>Natural Language Querying</strong> within a <strong>Retrieval-Augmented Generation (RAG)</strong> pipeline involves a series of coordinated steps to ensure users receive accurate and contextually relevant responses. Here’s a detailed overview of the process:</p><h3>Neo4j Database Connection</h3><p>Users begin by connecting to a <strong>Neo4j</strong> graph database using their credentials. This step is crucial as it allows access to the stored knowledge base, which has been processed from the uploaded text file or URL-based input. Neo4j serves as a <strong>graph-based knowledge representation system</strong>, ensuring structured and interconnected information retrieval.</p><h3>Document Ingestion</h3><p>Users have the option to either:</p><ul><li><strong>Upload a text file</strong>: Directly upload the book or document as a .txt file.​</li><li><strong>Provide a URL</strong>: Input the URL of the .txt file for the system to fetch.​</li></ul><p>Once the document is provided, the system processes it to extract and store information.​</p><h3>RAG Pipeline Activation</h3><p>Upon receiving a natural language query from the user, the RAG pipeline is triggered, operating in the following sequence:​</p><h4>a. Retrieval Phase</h4><p><strong>Cypher Query Approach</strong>:</p><ul><li>Cypher query is used for extracting the most relevant models in a structured manner.</li><li>The relationships extracted are then passed on to the response generation pipeline to get you the results.</li></ul><p><strong>Graph-Based Contextual Search Instead of Embeddings:</strong></p><ul><li>Unlike <strong>vector search</strong>, which relies on <strong>embedding similarity</strong>, this method retrieves information by <strong>traversing structured relationships</strong> in Neo4j.</li><li>It extracts information like <strong>character interactions, event relationships, and locations</strong> based on graph structure.</li></ul><p><strong>Ontology-Based Search in Neo4j</strong>:</p><ul><li>If relevant documents exist in Neo4j, <strong>graph traversal queries</strong> (Cypher queries) retrieve structured information related to entities, authors, events, and locations from the book.</li><li>If the document <strong>does not exist</strong>, a <strong>document processing pipeline</strong> is triggered, performing the following:</li></ul><blockquote><strong>Text Processing:</strong> Chunking the documents.</blockquote><blockquote><strong>Ontology Creation:</strong> Structuring information into Neo4j relationships.</blockquote><blockquote><strong>Data Storage:</strong> Saving the new knowledge for future queries.</blockquote><p><strong>Indexing &amp; Chunk Selection</strong>:</p><ul><li>For already indexed files, the system retrieves the <strong>most relevant text chunks</strong>, ensuring that the retrieval is optimized and efficient.</li></ul><h4>b. Response Generation Phase</h4><p>Once the <strong>most relevant chunks</strong> are retrieved, the system proceeds to response generation using an <strong>LLM-based approach</strong>:</p><p><strong>1. Azure GPT-4o-mini for Response Synthesis</strong></p><ul><li>The retrieved content is passed to <strong>Azure GPT-4o-mini</strong>, which formulates <strong>human-like, well-structured responses</strong>.</li><li><strong>Why GPT-4o-mini?</strong></li></ul><blockquote><strong>Optimized Cost-Performance:</strong> More affordable than larger models.</blockquote><blockquote><strong>High Retrieval Accuracy:</strong> Effectively processes short queries.</blockquote><blockquote><strong>Latency Efficiency:</strong> Provides rapid responses for real-time querying.</blockquote><p><strong>2. Final Answer Generation</strong></p><ul><li>The model composes a <strong>coherent, contextually rich response</strong>, integrating factual details from both the knowledge graph and retrieved text chunks.</li><li>Responses are <strong>human-aligned</strong> to ensure clarity and completeness.</li></ul><blockquote><strong><em>Modular Design</em></strong><em>: Built to support </em><strong><em>any book</em></strong><em>, not just Pride and Prejudice.</em></blockquote><p>The system is designed with a <strong>modular architecture</strong>, ensuring flexibility to process and query any book, not just <em>Pride and Prejudice</em>. Key design principles include:</p><p><strong>1. Dynamic Ontology Creation</strong></p><ul><li>The ontology extraction process <strong>automatically identifies</strong> entities from any uploaded book and stores them in <strong>Neo4j</strong>, ensuring adaptability.</li></ul><p><strong>2. Customizable Chunking &amp; LLM Graph Transformer Query</strong></p><ul><li>The <strong>RecursiveCharacterTextSplitter</strong> ensures that any text can be processed into meaningful <strong>overlapping chunks</strong> for optimal retrieval.</li><li><strong>Graph Transformer </strong>module is used to efficiently handle different textual structures without dependency on a specific book.</li></ul><p><strong>3. Configurable Retrieval &amp; Querying</strong></p><ul><li>The <strong>RAG pipeline</strong> dynamically retrieves relevant passages from <strong>any processed book</strong>, making it adaptable to various knowledge bases.</li><li>Queries are resolved using <strong>ontology-based search + cypher query based retrieval</strong>, ensuring accurate responses regardless of book content.</li></ul><p><strong>4. Scalability &amp; Extensibility</strong></p><ul><li>The system allows seamless <strong>swapping of input books</strong> without requiring manual reconfiguration.</li></ul><blockquote><strong><em>Streamlit UI</em></strong><em>: Interactive frontend for </em><strong><em>document ingestion &amp; querying</em></strong><em>.</em></blockquote><p>The Streamlit UI provides an <strong>interactive interface</strong> for users to seamlessly <strong>ingest documents</strong> and perform <strong>natural language queries</strong> using the <strong>Graph-based RAG pipeline</strong>.</p><h4>Key Features</h4><p><strong>1. Neo4j Database Connection</strong></p><ul><li>Users can enter their <strong>Neo4j connection details</strong> (URL, username, password) and establish a database connection.</li><li>Once connected, the system enables <strong>ontology creation &amp; retrieval</strong> from the structured knowledge graph.</li></ul><p><strong>2. Document Ingestion Options</strong></p><ul><li>Users can choose between:</li></ul><blockquote><strong>URL Input</strong>: Paste a .txt file URL (e.g., from Project Gutenberg).</blockquote><blockquote><strong>File Upload</strong>: Upload a .txt file directly.</blockquote><ul><li>The system <strong>parses, chunks, and indexes</strong> the document dynamically into the vector database and Neo4j knowledge graph.</li></ul><p><strong>3. Chunking Range Selection</strong></p><ul><li>Two adjustable parameters ensure efficient chunking:</li></ul><blockquote><strong>Chunking Index (≥ 0, default = 0)</strong> — Specifies the starting point.</blockquote><blockquote><strong>Offset (≥ 1, default = 50)</strong> — Determines how many chunks (each of size <strong><em>514</em></strong> with <strong><em>20%</em></strong> overlap) are processed.</blockquote><ul><li><strong>Why was this introduced?</strong></li></ul><blockquote><strong>Processing the entire book</strong> at once led to performance bottlenecks with <strong>OpenAI and Groq APIs</strong>:</blockquote><p><strong>Groq API limits</strong> — Requests for large documents hit a <strong>rate limit</strong>, causing delays.</p><p><strong>OpenAI API quota constraints</strong> — Larger inputs consumed excessive API usage.</p><blockquote><strong>Solution:</strong></blockquote><p>So for this, I have decided to utilize the <strong>Azure Subscription plan</strong> that I had and used <strong>GPT-4o-mini</strong> to balance accuracy &amp; efficiency.</p><p><strong>4. Querying Mechanism</strong></p><ul><li>Once a document is processed, users can <strong>enter natural language queries</strong> in a text box.<br>Upon submission, the <strong>RAG pipeline</strong> retrieves relevant document chunks and generates responses using <strong>Azure GPT-4o-mini</strong>.</li></ul><p><strong>5. User Experience Enhancements</strong></p><ul><li><strong>Dropdown menu</strong> for selecting input type (<strong>URL/File Upload</strong>).</li><li><strong>Real-time feedback</strong> on connection status &amp; response generation.</li><li><strong>Optimized for real-time performance</strong>, allowing smaller offset values (<strong><em>&lt;50</em></strong>) for faster testing.</li></ul><h3>3. Architecture</h3><h4>High-Level Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*cSOTX0xYzKRVuLSP" /><figcaption><strong><em>Architecture Pipeline (GR-3.1)</em></strong></figcaption></figure><p><strong>System Components</strong></p><ul><li><strong>Data Source</strong>:<a href="https://www.gutenberg.org/cache/epub/1342/pg1342.txt"> Project Gutenberg — Pride and Prejudice </a>or any <strong>.txt/ url</strong>.</li><li><strong>Ontology Extraction</strong>: NLP-based entity &amp; relationship extraction.</li><li><strong>LLM (Large Language Model)</strong>: OpenAI GPT-4 or similar.</li><li>Change the credential from the <strong><em>.env </em></strong>one can change and utilize the different LLMs.</li><li><strong>Frontend</strong>: <strong>Streamlit</strong> UI for interaction.</li><li><strong>Backend Framework</strong>: <strong>FastAPI / LangChain</strong> for query processing.</li><li><strong>Graph Database (Optional)</strong>: <strong>Neo4j</strong> to store relationships.</li></ul><h3>4. Ontology Processing Workflow</h3><p>Ontology creation plays a crucial role in <strong>structuring knowledge</strong> from raw text data, enabling <strong>efficient retrieval</strong> through a <strong>graph-based approach</strong> using Neo4j. This process ensures that relationships between key entities (characters, places, events) are established, providing a <strong>semantic understanding</strong> of the content for <strong>enhanced RAG (Retrieval-Augmented Generation) capabilities</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*89CwWWEqz4MwY3dG" /><figcaption><strong><em>Neo4j Aura Database (GR-4.1)</em></strong></figcaption></figure><h4>Entity Extraction</h4><ul><li>A <strong>Large Language Model (LLM)-based Graph Transformer</strong> is used to <strong>automatically extract key entities</strong> from the document.</li><li>These entities typically fall under the following categories:</li></ul><blockquote><strong>Characters</strong> — Identifying protagonists, antagonists, and supporting roles.</blockquote><blockquote><strong>Places</strong> — Locations where events unfold.</blockquote><blockquote><strong>Events</strong> — Significant occurrences that drive the narrative.</blockquote><ul><li>The LLM ensures that <strong>contextually relevant entities</strong> are extracted, preventing <strong>false positives</strong> or <strong>out-of-context references</strong>.</li></ul><h4>Relationship Definition</h4><ul><li>Once entities are identified, <strong>relationships</strong> between them are <strong>dynamically created</strong> using <strong>graph-based representations</strong>, as explained previously in detail manner.</li><li>These relationships <strong>enhance searchability</strong> by allowing <strong>semantic querying</strong>.</li></ul><h4>Graph Storage in Neo4j</h4><ul><li>The extracted entities and their relationships are <strong>stored as a structured knowledge graph</strong> in <strong>Neo4j</strong>.</li><li>This enables <strong>efficient querying</strong>, supporting <strong>natural language searches</strong> while maintaining <strong>traceability of data sources</strong>.</li></ul><h3>5. Custom Entity Labeling for File Tracking</h3><p>To <strong>ensure efficient file tracking</strong> and <strong>avoid duplication</strong>, a <strong>custom entity-labeling mechanism</strong> has been implemented.</p><h4>How LLM Graph Transformer Works in Neo4j</h4><ul><li>The <strong>LLM Graph Transformer</strong> generates <strong>graph documents</strong> from the text.</li><li>These documents are imported into Neo4j using the <strong>add_graph_documents</strong> method.</li><li>Each node in the ontology is <strong>automatically assigned a base entity label</strong> (__Entity__) for indexing and retrieval.</li></ul><h4>The Limitation of Default Labeling</h4><ul><li><strong>Problem:</strong> By default, Neo4j assigns a <strong>generic __Entity__ label</strong> to every node.</li><li>This becomes problematic when <strong>multiple documents (books) are ingested</strong>, as there is <strong>no direct way to distinguish between entities from different sources</strong>.</li><li>This could lead to <strong>overlapping knowledge graphs</strong>, making <strong>file-based indexing inefficient</strong>.</li></ul><h4>Custom base Entity Labeling (CUSTOM_BASE_ENTITY)</h4><p>To address the above issues, a <strong>custom labeling mechanism</strong> was introduced to <strong>uniquely track files</strong> in the database.</p><h4>How Custom Labeling Works</h4><ul><li>Instead of using the <strong>default BASE_ENTITY_LABEL</strong>, a <strong>dynamic label (CUSTOM_BASE_ENTITY)</strong> is assigned to each document.</li><li>This label is based on the <strong>filename</strong>, allowing for <strong>precise file tracking</strong>.</li></ul><h4>Naming Convention for CUSTOM_BASE_ENTITY</h4><ol><li>Extract the <strong>filename</strong> from the uploaded document (excluding .txt).<br>Convert the filename to <strong>uppercase</strong>.</li><li>Append and prepend it with <strong>“__”</strong> symbols to create a <strong>unique entity label</strong>.</li></ol><p><strong>Example:</strong></p><ol><li>If the file <strong>pg1342.txt </strong>is uploaded, the assigned label becomes:<br><strong>__PG1342__</strong></li></ol><h3>6. How to Run</h3><h4>Setup Instructions</h4><p>1. Clone repository</p><pre>git clone https://github.com/dimridd/ontology_agent<br>cd ontology</pre><p>2. Install dependencies</p><pre>pip install -r requirements.txt</pre><p>3. Set up environment variables (<strong>API keys, DB configs</strong>) mentioned in .env, change them accordingly.</p><p>4. Run Streamlit UI</p><pre>streamlit run ontology_agent.py</pre><h3>7. Conclusion</h3><p>This project demonstrates the power of <strong>ontology-driven retrieval</strong> combined with <strong>Generative AI</strong> to enhance knowledge extraction and searchability. By automating ontology creation and integrating it with a <strong>Retrieval-Augmented Generation (RAG) pipeline</strong>, we achieve a <strong>scalable, efficient, and intelligent</strong> system for answering questions based on structured knowledge.</p><p>The <strong>structured ontology</strong> not only improves search accuracy but also enhances the overall <strong>user experience</strong> by providing more relevant and context-aware responses. This approach significantly <strong>reduces manual effort</strong> in knowledge graph construction while ensuring <strong>high-quality, explainable, and structured insights</strong> from large text corpora.</p><p>I truly appreciate your open communication and feedback. It means a lot to me! Stay tuned for further updates, and feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd425e58321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SentencePiece — The NLP Architect’s Tool for Building Bridges Between Languages]]></title>
            <link>https://ddimri.medium.com/sentencepiece-the-nlp-architects-tool-for-building-bridges-between-languages-7a0b8ae53130?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a0b8ae53130</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[sentencepiece]]></category>
            <category><![CDATA[language-translation]]></category>
            <category><![CDATA[nllb]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 19:53:13 GMT</pubDate>
            <atom:updated>2024-01-11T20:44:11.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>SentencePiece — The NLP Architect’s Tool for Building Bridges Between Languages</h3><h3>Overview</h3><p>Building on our pervious <a href="https://medium.com/@ddimri/decoding-the-secrets-of-language-translation-with-pytorch-a-hands-on-journey-to-seq2seq-modelling-734f3d265b3f"><strong>Blog</strong></a>, where we explored the attention mechanism, this article will explores <strong><em>SentencePiece</em></strong>, a powerful subword tokenization technique empowering seamless language translation within natural language processing (NLP) tasks.</p><p>By delving into its capabilities, we will demonstrate the <em>SentencePiece</em> capability to generating tokens and its different functionality to see how it can help bridging the gap between the languages that it has never seen before by aligning it with the language model of our choice (In our case the LM that we will be focusing on will be <strong><em>NLLB(</em></strong><a href="https://ai.facebook.com/blog/teaching-ai-to-translate-100s-of-spoken-and-written-languages-in-real-time/"><strong><em>No Language Left Behind</em></strong></a><em>) </em>which will further be replaced by one of talking points nowadays(<strong><em>LLMs</em></strong><em> for our </em><strong><em>end2end</em></strong><em> pipeline, which we will discuss in our next </em><strong><em>blog</em></strong><em> post</em>).</p><p><em>NLLB</em> has shown a great tokenization results for sentence&#39;s that are in <strong><em>Hindi</em></strong>(written in <em>english</em>). Given that both our input (<strong><em>Hindi</em></strong>) and output (<strong><em>Garhwali</em></strong>) are also written in English script, NLLB delivers impressive average token per word ratios of <strong>1.436759</strong> (<em>Hindi</em>) and <strong>1.371028</strong> (<em>Garhwali</em>), which itself is a great enough ratio for language translation model &amp; is comparable with that of a high-resource language that <em>NLLB</em> supports with big margins. These ratios itself considered highly favorable for machine translation tasks, and is comparable with most of the high-resource language that <em>NLLB</em> supports with big margins (<a href="https://huggingface.co/facebook/nllb-200-distilled-1.3B"><em>NLLB</em></a> also supports 200 different languages). While <a href="https://huggingface.co/google/mt5-base"><em>Google-MT5</em></a> is also another option in LMs category, <em>NLLB’s</em> slightly superior tokenization for our specific languages, along with its wider language support and less input lengths not exceeding 512 tokens perfectly fits our problem statement ultimately led us to select it for the <strong>first phase</strong> of our language translation pipeline.</p><p>Through in-depth exploration and practical examples, we will demonstrates <em>SentencePiece</em> all in all capability in language communication, paving the way for a future where language barriers crumble and cross-linguistic understanding becomes effortless.</p><blockquote>Note: We are incorporating <strong>NLLB</strong> primarily as a supporting element in our exploration of <strong>SentencePiece</strong>. It’s important to note that for these languages(Not in their native written form currently but will be in the future.), given their excellent average token per word ratios, the utilization of <strong>SentencePiece</strong> may not be essential. But we can still incorporate it in our project for better results.</blockquote><h3><strong>Let’s Understand SentencePiece</strong></h3><p><em>SentencePiece</em> is an <em>language independent</em> tokenization model for NLP task in deep learning, we can use SentencePiece models to Fine-Tune our own custom tokenizer then make it compatible with any other LM’s that support SentencePiece format. Unlike traditional word-level tokenization, SentencePiece breaks down words into smaller, semantic units, enabling finer-grained analysis and better capturing the nuances of language.</p><p>It uses the SentencePieceTrainer.Train module to to train the the text file with your embedded textual information. It takes in that all the textual information from the input .txt file and generate the .<em>spm</em> file.</p><p>This .<em>spm</em> format is nothing but a binary file that stores the trained sentence-piece model. It Contains the vocabulary, model parameters( e.g., <strong><em>BPE</em></strong> merge operations), special tokens( e.g., <strong><em>&lt;unk&gt;, &lt;s&gt;, &amp; &lt;/s&gt;</em></strong>), and normalization rules &amp; is created as the output of the training process.</p><p>Our aim of using <em>SentencePiece</em> is make the model understand the tokens of the languages that’s new to it, that we are basically trying to expand the model vocabulary. Especially this expansion generally comes into play when new language dataset has out-of vocabulary characters, and the average token length is greater than 4 or would rather is not in range 2–3.</p><p>If this is not that case than there is not need to expand the vocabulary of then new model since its already been able to formulate the meaning out of the tokens and need not need extra pre-processing steps for tokenization.</p><p><em>So what would be the </em><strong><em>ideal scenario!, yes its 1(e.g. 1 word per token)</em></strong><em>.</em></p><p>Given the <strong><em>tokensPreprocessing</em></strong> class, it will help you identify the tokenized properties that includes:</p><ol><li>Calculating the number of the tokens per word that the tokenizer is capable of,</li><li>Average words per tokens for that language corpus.</li></ol><p><em>[For both languages]</em></p><pre>def word_tokenize(text):<br>    # a very naive word tokenizer for languages with English-like orthography<br>    return re.findall(&#39;(\w+|[^\w\s])&#39;, text)<br>    <br>class tokensPreprocessing:<br>    def avg_tokens_word(self, pairs):<br>        tokens = tokenizer.tokenize(pairs[0])<br>        word_tokens = word_tokenize(pairs[0])<br><br>        word2tokens = {}<br>        for itr_, word in enumerate(tokens):<br>            if itr_ == 0:<br>                first_index = itr_<br>            elif word[0] == &quot;▁&quot;:<br>                word2tokens[&quot;&quot;.join(tokens[first_index : itr_])[1: ]] = itr_-first_index<br>                first_index = itr_<br>                <br>        word2tokens[&quot;&quot;.join(tokens[first_index :])[1:]] = (itr_-first_index + 1)   <br>        <br>        # return len(tokens) / len(list( word2tokens.keys())), word2tokens<br>        return len(tokens) / len(word_tokens), word2tokens<br><br>    def __call__(self, languages, pairs):<br>        avg_tokens = {}<br>        <br>        for lang in languages.keys():<br>            lng_idx = languages[lang]<br>            <br>            hind = [pair[lng_idx] for pair in pairs]<br>            elem_wise_avg = list(map(self.avg_tokens_word, zip(hind)))<br>            avg = sum(sublist[0] for sublist in elem_wise_avg)/ len(elem_wise_avg)<br>        <br>            word2token_U = {}<br>            for sent in elem_wise_avg:<br>                word2token = sent[1]<br>                for itr, word in enumerate(word2token):<br>                    # print(word)<br>                    if word not in word2token_U:<br>                        word2token_U[word] = &quot;&quot;<br>                    word2token_U[word] = word2token[word]<br>        <br>            dict_ = pd.DataFrame({&#39;words&#39;: list(word2token_U.keys()), &#39;tokens&#39;: list(word2token_U.values())})<br>            <br>            if lang == &quot;hind&quot;:<br>                dict_.to_csv(&quot;hind_tokens.csv&quot;, index=False)<br>                avg_tokens[&quot;hind&quot;] = avg<br>            elif lang == &quot;garh&quot;:<br>                dict_.to_csv(&quot;garh_tokens.csv&quot;, index=False)<br>                avg_tokens[&quot;garh&quot;] = avg<br>                        <br>        pd.DataFrame({&#39;language&#39;: list(avg_tokens.keys()), &#39;avg_tokens&#39;: list(avg_tokens.values())}).to_csv(&quot;avg_tokens.csv&quot;, index=False)<br><br><br># result in 3 files {hind_tokens.csv, hind_tokens.csv, avg_tokens.csv}<br>tokens_preprocess = tokensPreprocessing()<br><br>languages = {&quot;hind&quot;: 0, &quot;garh&quot;: 1}<br># pairs = [[&quot;hindi&quot;], [&quot;garhwali&quot;]]<br>tokens_preprocess(languages, pairs)</pre><p>This function will take the input as <strong><em>languages</em></strong><em>(dict)</em>, and <strong><em>pairs </em></strong>in the format as specified above in the code structure, which you can change according to your use case. And the output will be in the form of the <strong><em>.csv</em></strong> file with the necessary information.</p><p>Once we <strong><em>train</em></strong> and <strong><em>load</em></strong> the tokenizer we will add its tokens to the existing <em>NLLB</em> tokenizer, which is our main module that we are trying to use for our language translation. Lets get into the code and see how we do it.</p><h4>Training SentencePiece</h4><p>There are actually 2 ways of training your custom tokenizer:<br><strong><em>Using the model-prefix parameters.</em></strong></p><pre>import sentencepiece as spm<br> <br>spm.SentencePieceTrainer.train(<br> input=&#39;sentences.txt&#39;, <br> model_prefix=&#39;hi-garh&#39;, <br> model_type=&quot;bpe&quot;,<br> vocab_size=2**6, <br> )</pre><p>This help you provide a detail output format consists of .model .vocab and .model.spm.id files where,</p><ol><li><em>.model</em>: The main .spm model file.</li><li><em>.vocab</em>: A text file containing the vocabulary. &amp;</li><li><em>.model.spm.id</em>: A text file with model metadata.</li></ol><p><strong><em>Using the model-write which takes in 2 formats:<br></em></strong> <strong>.spm file pointer</strong>: Writes the model directly to a specified .spm file.</p><pre>def train_sentence_piece_bytes(size):<br><br>    with open(&quot;model.spm&quot;, &quot;wb&quot;) as model_file:<br>        spm.SentencePieceTrainer.train(<br>            input=&#39;sentences.txt&#39;,<br>            model_writer=model_file,<br>            vocab_size=size,<br>        )<br>proto = train_sentence_piece_bytes(2**6)</pre><p><strong>io.BytesIO():</strong> Writes the model to an in-memory buffer for later usage.</p><pre>import io<br>model_writer = io.BytesIO()<br> spm.SentencePieceTrainer.train(<br> input=&#39;sentences.txt&#39;,<br> model_writer=model_writer,<br> model_type=&quot;bpe&quot;,<br> vocab_size=2**6,<br> )<br> <br> # Access model data from model_writer<br> model_data = model_writer.getvalue()<br> <br> # Optionally write to a file<br> with open(&#39;my_model.model&#39;, &#39;wb&#39;) as f:<br> f.write(model_data)</pre><blockquote>Here is one interested thing about the sentence tokenizer, if you look into the vocabulary that it created for you it contains tokens w.r.t <strong>subword, Special characters, characters, Case Sensitivity, Model type</strong> used(and its variation), Empty Lines or Whitespace, etc. thus the <strong>vocab size</strong> will always be <strong>&gt;=</strong> <strong>(required_chars_.size() + meta_pieces.size()).</strong></blockquote><p>Lets try to understand it with the help of an example, consider I have list of sentences as our corpus “<strong><em>mera naam divyanshu ha.</em></strong>”, “<strong><em>aap kese ho!</em></strong>”, &amp; “<strong><em>wail aanu cha</em></strong>”.</p><p>Then if you run the trainer of our <em>SentencePiece</em> and say(you use 1. method), if u see the .vocab file you will see the min_vocab size consists of unique characters present in the our corpus(which is <strong><em>required_chars_</em></strong> here) plus the meta_pieces (<strong><em>&lt;unk&gt;, &lt;s&gt;, &amp; &lt;/s&gt;</em></strong> in our case).</p><p>These meta_pieces refers to the special tokens or pieces that serve specific purposes within the model.</p><p>Thus based on the functionality/ properties and size of the custom data corpus vocabulary density varies.</p><p><strong>wait functionality/ properties?</strong></p><p>It defines how well versed the model is trained on the different set of languages that it has seen and learned e.g. say while fine-tuning on our own dataset we provide him a word “hello” and vocab_size is also limited (<strong><em>say’s required_chars_.size() + meta_pieces.size() + 2(focus on this 2 here)</em></strong>) since SentencePiece is trained on multiple languages it will first try to fit in all the unique_character + some special_tokens + will then see if some remaining words remains(<strong><em>2</em></strong> in this) it will fill in “<strong><em>lo</em></strong>” which it might have learned from the hindi sentence(say “<strong><em>cha lo</em></strong>”(meaning “<strong><em>lets go</em></strong>”) ). This thus defines the model properties meaning how well that model is been trained on.</p><p>hope this makes the things clearer.</p><h4>Loading SentencePiece</h4><p><strong><em>SentencePieceProcessor</em></strong> is one of the important class of <em>SentencePiece</em> which is responsible of loading the model via <em>file_path.</em></p><p>Now once we have trained the model we are now ready to use it in any way possible, and for this we use SentencePieceProcessor library which is responsible for loading the model using file_path.</p><p>either using the load function by first creating SentencePieceProcessor object then calling the load such as:</p><pre>hi_garh_spm_processor = spm.SentencePieceProcessor()<br>hi_garh_spm_processor.load(&quot;model.spm&quot;) # Use &quot;.spm&quot; or &quot;.model&quot; extension</pre><p>also referred as <strong><em>Load after creation</em></strong>.</p><p>OR <br>directly from SentencePieceProcessor object via model_file argument as:</p><pre>hi_garh_spm_processor = spm.SentencePieceProcessor(model_file=&#39;./hi-garh.model&#39;)</pre><p>also referred as <strong><em>Load during creation</em>.</strong></p><h4>Vocabulary Expansion</h4><p>Once we load the trained model we will extract the model data which is in <strong><em>Protobuf</em></strong> format. for this we will first create a placeholder object to hold the serialized model data in <em>Protobuf</em> format using:</p><pre>new_vocab_spm_proto = sp_pb2_model.ModelProto()</pre><p>then extract the trained model serialized <em>protobuf</em> data and Parses data into Protobuf object:</p><pre>new_vocab_spm_proto.ParseFromString(hi_garh_spm_processor.serialized_model_proto())</pre><p>we will do the same for our pre-trained <em>NLLB</em> tokenized model.</p><pre>from transformers import NllbTokenizer<br><br>nllb_tokenizer = NllbTokenizer.from_pretrained(&#39;facebook/nllb-200-distilled-600M&#39;)<br><br>base_spm_proto = sp_pb2_model.ModelProto()<br>base_spm_proto.ParseFromString(nllb_tokenizer.sp_model.serialized_model_proto())</pre><p>Once this is done we are all ready to add the missing tokens to the <em>NLLB</em> <em>SentencePiece</em> model using below formatted code lines.</p><p>so what we are doing in here is to parse through each tokens that we have created via SentencePiece and if they exists in the <em>NLLB</em> <em>protobuf</em> <br>object we simple ignore it else we add a new piece(pieces here are nothing but the tokens that our tokenizer has stores in its memory ) to <br>this entry.</p><p>we also modify the scores for the new pieces accordingly.</p><p>when this is done we have new modified <em>protobuf</em> object with new &amp; old entry in it, we then save it as new .model file.</p><pre>base_vocab_tokens = {p.piece for p in base_spm_proto.pieces}<br>min_score_in_base_vocab = base_spm_proto.pieces[-1].score<br><br>new_tokens = []<br>for p in new_vocab_spm_proto.pieces:<br>    if p.piece not in base_vocab_tokens:<br>        new_tokens.append(piece.piece)<br>        new_piece = sp_model_pb2.ModelProto().SentencePiece()<br>        new_piece.piece = p.piece<br>        new_piece.score = p.score + min_score_in_base_vocab  # Lower priority for new tokens<br>        base_spm_proto.pieces.append(new_piece)<br><br># **Save combined model:**<br>combined_spm_model_name = &#39;hiGarh_nllb.model&#39;<br>with open(combined_spm_model_name, &#39;wb&#39;) as f:<br>    f.write(base_spm_proto.SerializeToString())</pre><p>Two tokenizers are then loaded: the original one linked to the pre-trained model and a custom tokenizer with an expanded <em>vocabulary</em>. The pre-trained model is then loaded. To ensure compatibility between the model’s embedding layer and the custom vocabulary, the embedding layer of the model is resized to align with the length of the custom tokenizer’s <em>vocabulary</em>. This crucial step ensures smooth integration of the new tokens during model operations.</p><pre>from transformers import AutoModelForSeq2SeqLM, NllbTokenizer<br><br>model_name = &#39;facebook/nllb-200-distilled-600M&#39;<br><br># **Load and resize model for new vocabulary:**<br>combined_tokenizer = NllbTokenizer.from_pretrained(os.path.join(&quot;tokenizer_dir&quot;, combined_spm_model_name))<br><br>model = AutoModelForSeq2SeqLM.from_pretrained(model_name)<br>model.resize_token_embeddings(len(combined_tokenizer))</pre><p>While resizing accommodates new tokens, their initial embeddings are typically assigned random weights. This can potentially hinder model <br>performance during early training stages, as the model must learn these embeddings from scratch.</p><p>In order for the smother adaption the pre-trained model to the expanded vocabulary we can do re-initialization of the embedded vectors <br>before the training, for better understanding of this see <a href="https://cointegrated.medium.com/how-to-fine-tune-a-nllb-200-model-for-translating-a-new-language-a37fc706b865#:~:text=Step%203%20(optional)%3A%20Expanding%20the%20vocabulary"><strong>David Dale</strong></a> article on the same from where I have taken inspiration to write this article on.</p><p>See below example of the two tokenizer before and after been trained on custom dataset, as you can clearly sees how “divyanshu” is been treated differently by the two tokenizer.</p><pre>def text2tokens(text, tokenizer=None):    <br>    return {<br>        &quot;word&quot;: text,<br>        &quot;ids&quot;: tokenizer(text).input_ids,<br>        &quot;tokens&quot;: tokenizer.convert_ids_to_tokens(tokenizer(text).input_ids)<br>    }<br><br>Text = &quot;divyanshu&quot;<br><br># base one:<br>print(text2tokens(Text, tokenizer=tokenizer_old))<br>{&#39;word&#39;: &#39;divyanshu&#39;, &#39;ids&#39;: [256047, 150, 3490, 621, 300, 2], &#39;tokens&#39;: [&#39;eng_Latn&#39;, &#39;▁di&#39;, &#39;vy&#39;, &#39;ans&#39;, &#39;hu&#39;, &#39;&lt;/s&gt;&#39;]}<br><br># combined one<br>print(text2tokens(Text, tokenizer=tokenizer_new))<br>{&#39;word&#39;: &#39;divyanshu&#39;, &#39;ids&#39;: [256053, 256006, 2], &#39;tokens&#39;: [&#39;eng_Latn&#39;, &#39;▁divyanshu&#39;, &#39;&lt;/s&gt;&#39;]}</pre><h3>Conclusion</h3><p>This blog post represents the <strong>second stage</strong> of our journey in creating a robust, customized language translation model. In our <a href="https://medium.com/@ddimri/decoding-the-secrets-of-language-translation-with-pytorch-a-hands-on-journey-to-seq2seq-modelling-734f3d265b3f"><strong>previous post</strong></a>, we explored the <em>attention mechanism</em>, a key component in many neural networks. Now, we delve into <em>SentencePiece</em>, a subword tokenization technique that enhances language representation.</p><p>We not only understood <em>SentencePiece</em> but also expanded its vocabulary and integrated it with <em>NLLB</em>, a versatile language model. This collaboration enables efficient handling of previously unseen languages like <strong><em>Hindi</em></strong> and <strong><em>Garhwali</em></strong>, as seen in favorable token-to-word ratios.</p><p>The series concludes in <strong>Blog Post 3</strong>, where we’ll leverage <em>NLLB</em> and our expanded <em>SentencePiece</em> vocabulary to develop a high-performing translation model for <strong><em>Hindi-Garhwali</em></strong>.</p><p>I truly appreciate your open communication and feedback. It means a lot to me! Stay tuned for further updates, and feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page.</p><h3><strong>References</strong></h3><ul><li><a href="https://github.com/google/sentencepiece/blob/master/python/add_new_vocab.ipynb">sentencepiece/python/add_new_vocab.ipynb at master · google/sentencepiece</a></li><li><a href="https://github.com/google/sentencepiece/blob/master/doc/api.md">sentencepiece/doc/api.md at master · google/sentencepiece</a></li><li><a href="https://medium.com/codex/sentencepiece-a-simple-and-language-independent-subword-tokenizer-and-detokenizer-for-neural-text-ffda431e704e">Sentencepiece: A simple and language independent subword tokenizer and detokenizer for neural text…</a></li><li><a href="https://keras.io/api/keras_nlp/tokenizers/sentence_piece_tokenizer/">Keras documentation: SentencePieceTokenizer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a0b8ae53130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Secrets of Language Translation with PyTorch: A Hands-on Journey to Seq2Seq Model.]]></title>
            <link>https://ddimri.medium.com/decoding-the-secrets-of-language-translation-with-pytorch-a-hands-on-journey-to-seq2seq-modelling-734f3d265b3f?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/734f3d265b3f</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[sequence-to-sequence]]></category>
            <category><![CDATA[teacher-forcing]]></category>
            <category><![CDATA[language-translation]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 21:02:57 GMT</pubDate>
            <atom:updated>2024-01-10T08:50:11.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>In this article we will explores the inner workings of sequence-to-sequence (seq2seq) models with self-attention for machine translation, specifically focusing on <strong><em>Hindi</em></strong> to <strong><em>Garhwali </em></strong>language translation using PyTorch with one of the variant of recurrent neural networks (RNNs). It covers key concepts including:</p><ul><li>Encoder-decoder architecture: The fundamental components of seq2seq models and their roles in encoding input sequences and generating output sequences.</li><li>Attention mechanisms: Why attention is crucial for improved translation accuracy, particularly in longer sequences, and how it enables the decoder to focus on relevant parts of the input.</li><li>Output states vs. hidden states: The rationale behind using output states for attention calculation, as they better preserve individual word contributions compared to hidden states.</li><li>Teacher forcing: A training strategy that accelerates model convergence and stability by using ground truth values as input instead of model predictions.</li><li>Transformer models: A brief overview of their motivations, unique architecture, and impact on seq2seq tasks.</li></ul><p>The work delves into the implementation of these concepts in PyTorch(especially the sequence model), providing a step-by-step breakdown of information flow and sequence processing within RNNs with self-attention. We will also aims to shed light on the transformative power of attention mechanisms and transformers for language translation a bit just to grasp thing around.</p><p>We will be using <strong><em>GRU</em></strong> as one of the RNNs to understand the concept further in detail.</p><h3><strong>Understanding Basic Concept</strong></h3><p>In a machine translation we have two things one is encoder and other is decoder. The work of the encoder is to encode the sentence(A sentence is a series of word in a sequence) to a vector called <em>context vector </em>which is an input to the decoder unit, which in turn decode this <em>context vector</em> to generator a sequence of words in other language.</p><p>Here I am trying to drives into the internal workings of encoder-decoder models with self-attention used for language translation.</p><p>An encoder is a sequence model. In language translation applications that employ self-attention mechanisms, the encoder does not discard the output states. Instead, it utilizes all of the encoder’s outputs as entry points to the decoder model, in conjunction with the encoder’s final hidden state.</p><blockquote>Now the question that might comes to your mind is Why not use the <em>hidden intermediate state </em>of the encoder at every time step instead (since they too capture the information of each input word )?, OR Why use the <em>output state</em> at every time step ?</blockquote><h4><strong>Output states vs. hidden states</strong></h4><p>So lets go back a bit, the reason of introducing attention in the first place(especially in a seq2seq model) is to make sure that the output of the decoder must be aware of what percentage of the word is contributing in its making so that the word/ sentence generated has comes out of from the more meaningful understanding of the input sequence especially longer input sequences. Because In longer sequences, standard encoder-decoder models using a fixed-length <em>context vector</em> to summarize the entire input struggle to maintain information about earlier parts. This leads to inaccurate translations, in other word a normal sequence-to-sequence model uses a fixed length <em>context vector</em> &amp; this vector is used to carry forward the understanding of the input sequence to the decoder model which used this limited amount of memory information to generate the output sequence.</p><p>This is true &amp; will definitely work for smaller set of sequences but will not be able to extend its understanding beyond some point because these fixed smaller sized <em>context vector</em> Often has forgotten the earlier parts of the sequence once it has processed the entire the sequence. which is where attention comes into play, Attention tells the output word at every decoder time-step, which input <em>word</em> it has to focus on (Remember the term <em>word </em>mentioned here.) thus making sure that each word generated in the output sequence keeping in mind the right percentage contribution of input <em>word </em>while generating the output <em>word. </em>Attention model does this by assigning some weighted score to the each input word in the sequence w.r.t each output word in the generating sequence.</p><p><strong><em>How these scores are generated ?</em></strong></p><p>Will look into this later but for now assume an imaginary dictionary of output word where each word has a list of weight score for each word in the input sequence, telling how much percentage contribution that input word has to that output word.</p><p>Hence the answer….the input <em>word</em> that we mentioned, is the reason of using the <em>output states,</em> as each output in the encoder carries the information about that word at each time step which is what our attention focus on(e.g. Attention mechanisms are designed to selectively focus on specific parts of the input that are most relevant to the current task.</p><p>). Which means it emphasises on the individual component not the grouped components of words &amp; that’s what the <em>hidden state</em> store, a cumulative information of its previous time step. Hidden state by focusing on the information from all previous time steps, forms a progressively richer representation of the overall context means, <strong><em>it doesn’t preserve the individual contributions of each word or element in the sequence as cleanly as the output sequence does. </em></strong>Attention, however, often needs to focus on specific parts of the input and make fine-grained decisions about relevance.</p><p>And also as discussed before by the time it reaches the final state, hidden state has blended information from the entire input sequence making it difficult for attention to distinguish the specific parts that are most relevant to the current task. And this line goes for each time step for encoder module(except for first few step, but here we are talking about the larger deeper networks).</p><p>While it’s theoretically possible to use hidden state outputs for attention, the vast majority of research and practical implementations in deep learning frameworks rely on the output sequence for attention weight calculation. This convention has been found to be effective and efficient across various tasks involving attention.</p><p>In this sequence-to-sequence modelling journey, we’ll delve into the intricacies of using recurrent neural networks with self-attention mechanisms in PyTorch. We’ll dissect the information flow step-by-step, gaining a deep understanding of how sequences are processed and transformed. Diving further, we’ll explore the motivations behind the revolutionary shift towards transformer models and how their unique architecture has reshaped the landscape of sequence-to-sequence tasks. Through key architectural insights, we’ll demystify the transformative power of transformers.</p><h4>Teacher Forcing</h4><p>Before we move forward I would also like your attention on one of the concept called <em>Teacher Forcing</em>?</p><p>Problem with the traditional Training is that the output of the current time-step as an input to the subsequent time- step leading to:</p><ul><li>Slow convergence.</li><li>Model in-stability</li><li>Poor skill</li></ul><p>Teacher forcing is the strategy that allow RNNs/ Transformer architecture to use the ground truth/ actual values as an input rather than using the model output from the prior time-step as an input, making the training of RNNs/ Transformer network faster. But there is a slight variant while using the two in RNNs and in Transformers.</p><blockquote>Unlike recurrent models, where teacher forcing involves feeding the previous ground-truth word as input, transformers use the ground-truth output from the previous time step as the “query” for the current self-attention layer.</blockquote><h4><strong>The Encoder Module</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*wRp5TtheJRMWfhMeid2tZg.png" /><figcaption><strong>Encoder Sequence to Sequence Module</strong></figcaption></figure><p>A recurrent network process the input sequence sequentially at each time step(in an incremental fashion), &amp; the subscripts track time steps to maintain order.</p><p>where 0 represents the start of the sequence and subsequent values (1, 2, 3, …) representing subsequent time steps.</p><p>The hidden state accumulates information from all previous time steps, forming a progressively richer understanding of the input sequence’s overall meaning, and we called the last hidden state of the encoder the <strong><em>context vector(ctx)</em></strong><em> </em>which is responsible for carrying forward the information to the decoder unit. These hidden states enables the recurrent networks to capture long-range dependencies within sequences, even if those dependencies span multiple time steps.</p><p>To ensure consistency between input and output dimensions, we constructed an input/output vector with number <strong><em>11</em></strong>, corresponding to the <strong><em>max word </em></strong>sequence length in our entire data corpus.</p><pre>class sequenceEncoder(nn.Module):<br><br>    def __init__(self, input_size, hidden_size, droup_out=0.1):<br>        super(sequenceEncoder, self).__init__()<br><br>        self.input_embedding = nn.Embedding(input_size, hidden_size)<br>        self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)<br>        self.droupout = nn.Dropout(droup_out)<br><br>    def forward(self, X):<br>        if torch.all(input_tensor &gt;= 0) and torch.all(input_tensor &lt; embedding.num_embeddings):<br>            embed_vector = self.droupout(self.input_embedding(X)) <br>        else:                <br>            return [], []<br>        <br>        embed_vector = self.droupout(self.input_embedding(X))        <br>        output, hidden = self.gru(embed_vector)<br>        <br>        return output, hidden</pre><p>Let’s delve into this process with a time-step <strong><em>0</em></strong> in focus, if we zoom in a bit the network at <em>0th</em> time-step will look like this, lets try to understand this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*8ba_wIPcDVakVXWLRqqYHg.png" /><figcaption><strong>Recurrent Network at Encoder Time-Step_0</strong></figcaption></figure><p>Consider we have input sequence as “<strong><em>mera naam divyanshu hai</em></strong>.” When focusing on time-step <strong><em>0</em></strong>, the input sequence “<strong><em>mera</em></strong>” undergoes word-wise indexing as part of the label encoding process. In this approach, each word in the sequence is assigned a unique integer identifier to distinguish it within the training corpus. For our instance, “<strong><em>mera</em></strong>” is labeled as <strong><em>1</em></strong>, “<strong><em>naam</em></strong>” is <strong><em>2</em></strong>, and so on. This is called <strong>word-wise indexing</strong> or referred to <strong>label encoding</strong>.</p><p>The labeled word “<strong><em>mera</em></strong>” is then represented as a tensor of size <strong><em>(batch_size, 1)</em></strong> and passed through an embedding layer. This layer transforms the label encoding into a more semantically meaningful vector representation with a size of (<strong><em>batch_size, 1, 128)</em></strong>. Here, the ‘<strong><em>1</em></strong>’ represents the specific word in focus, and ‘128’ signifies the output embedding dimension. When applied to the entire sentence, the tensor size becomes <strong><em>(batch_size, 11, 128</em>)</strong>, indicating that there are <strong><em>11 words</em></strong>, each with a <strong><em>128-dimensional embedding representation</em></strong>.</p><p>Subsequently, this embedding vector is fed into the <strong><em>GRU </em></strong>unit<strong><em> </em></strong>to generate an <strong><em>output</em></strong> and <strong><em>hidden</em></strong> vector. Specifically, for a single time-step (e.g., time-step <strong><em>0</em></strong>), the output and hidden vectors are both of size <strong><em>(batch_size, 1, 128</em>)</strong>. When considering the entire time sequence, the output vector becomes (<strong><em>batch_size, 11, 128)</em></strong>, and the hidden vector remains <strong><em>(batch_size, 1, 128</em>)</strong>. This process provides a comprehensive understanding of the sequential information encoded in the input sentence.</p><p>We also have a special hidden vector called the context vector(the last of the hidden state vector of an encoder module) and is one of the input to out decoder as it carries the summarised information of the entire sequence in a vector format it has seen throughout previously each time steps.</p><p><em>Note, there is also a vector </em><strong><em>h0</em></strong><em> typically initialised to </em><strong><em>zero</em></strong><em> as the model has not yet started to read the input at this point in time &amp; will have same size as the other hidden sate, in our case it will be </em><strong><em>(batch_size, 1, 128)</em></strong><em>.</em></p><p>Encoder model understanding of recurrent network(<strong><em>GRU</em></strong>) with input sequence: “<strong><em>mera naam divyanshu hai</em></strong>”.</p><pre>Input: &quot;mera&quot;<br>Hidden State (Initial): A vector of zeros, indicating no prior context.<br>Recurrent Processes: Combines input and hidden state, capturing basic information about &quot;mera&quot; and its potential role as a determiner.<br>Output: Represents the GRU&#39;s understanding of &quot;mera&quot; in isolation, its potential meanings, and its role as a sentence starter.<br>Updated Hidden State: Captures the meaning of &quot;mera&quot; and its potential role as a sentence starter.<br><br>Input: &quot;naam&quot;<br>Hidden State: Now contains information about &quot;mera&quot;<br>GRU Processes: Integrates input with hidden state, understanding &quot;naam&quot; in the context of &quot;mera&quot;<br>Output: Represents the GRU&#39;s understanding of &quot;naam&quot; in the context of &quot;mera&quot;<br>Updated Hidden State: Captures the phrase &quot;mera naam&quot; and its potential meaning.<br><br>Similar process continues for &quot;divyanshu&quot;:<br>* Input is the current word.<br>* Hidden state carries information from previous words.<br>* GRU processes input and hidden state, updating both.<br>* Output represents GRU&#39;s understanding at this step.<br>* Updated hidden state captures accumulated context.<br>This process will repeat in itself for each sequence word in the sentence till it reached the end word(&quot;hai&quot;).<br><br>Input: &quot;hai&quot;<br>Hidden State: Contains information about the entire sentence up to &quot;divyanshu&quot;<br>GRU Processes: Integrates input with hidden state, understanding &quot;hai&quot; in the full context.<br>Output: Represents the GRU&#39;s final understanding of &quot;hai&quot; in the sentence.<br>Updated Hidden State: Holds the complete representation of the entire sentence &quot;mera naam divyanshu hai&quot;</pre><h4>The Decoder(Attention) Module</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*_vYaEjwZmfxiT38_DUDZ7A.png" /><figcaption><strong>Decoder Seq2Seq Module via Self Attention</strong></figcaption></figure><p>Now, turning our attention to the decoder sequence, it incorporates a mechanism that considers both the output from the encoder unit, <br>denoted as the “<strong><em>output sequence</em></strong>” and the “<strong><em>context vector (ctx</em>)</strong>,” along with the decoder input at the current time step (represented by <br>the output sequence).</p><p>The distinctive features of the decoder with attention, as compared to a regular decoder, can be outlined as follows:</p><ol><li>Output of the encoder are taken into consideration at every decoder time step, the importance of output sequence is already <br> explained in detail in Encoder part</li><li>The <strong><em>context vector (ctx)</em></strong> is not a conventional representation of the last hidden state of the encoder. Instead, it is computed as <br> the weighted sum of the encoder’s output sequence, where the weights are determined by the attention mechanism with respect to the <br> corresponding input word at the current decoder time step.</li></ol><p>To elaborate further, the <strong><em>attention weights</em></strong> are computed prior to being introduced into the decoder. These weights are derived from a <br>mechanism that assesses the relevance of each element in the encoder’s output sequence to the current decoding step. The calculation <br>involves considering not only the hidden units from previous time steps but also the output of the encoder.</p><blockquote>This approach is particularly effective in capturing and preserving long-term dependencies within the sequential data.</blockquote><p>See below code for detail understanding of the Decoder Module with Self-Attention.</p><pre>class decoderAttention(nn.Module):<br>    def __init__(self, hidden_size, output_size, dropout_p=0.1):<br>        super(decoderAttention, self).__init__()<br><br>        self.output_size = output_size<br>        <br>        self.embedding = nn.Embedding(output_size, hidden_size)<br>        self.attention = attentionMechanism(hidden_size).to(device)<br>        self.gru = nn.GRU(2 * hidden_size, hidden_size, batch_first=True)<br>        self.out = nn.Linear(hidden_size, output_size)<br>        self.dropout = nn.Dropout(dropout_p)<br><br>    def forward(self, encoder_outputs, encoder_hidden, input_tensor=None):<br>        <br>        # First Input Formatting<br>        <br>        ## get the batch_size from the encoder output as it should be match the consistency across the network<br>        batch_size = encoder_outputs.size(0)<br>        <br>        ## decoder_input is the decoder input at that time-step, so it will be the label-encoding of the single word &amp; will have the \<br>        ## dimension (batch_size, 1).<br>        decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)<br><br>        # Second Input Formatting<br>        decoder_hidden = encoder_hidden<br>        decoder_outputs = []<br>        attentions = []<br>        <br>        ## for all the time step(for all the output sequence), we process each word/ time-step using for loop till MAX_LENGTH token.<br>        for time_seq in range(MAX_LENGTH):<br>            ## here we are calling in the &lt;seq_step&gt; function which will do the evaluation per word<br>            decoder_output, decoder_hidden, attn_weights = self.seq_step(decoder_input, decoder_hidden, encoder_outputs)<br>            decoder_outputs.append(decoder_output)<br>            attentions.append(attn_weights)<br>            ## will introduce the concept of &quot;teacher-forcing&quot;(alreday explained); the input to the decoder is the actual output of the<br>            ## decoder from the previous time-step.<br><br>            ## this &quot;input_tensor&quot; will be the &quot;decoder_input&quot; in the time-step to follow, we use the unsqueeze(1) in order to maintain<br>            ## input dimension as (batch_size, 1) as we are dealing in batches<br>            if input_tensor is not None:<br>                decoder_input = input_tensor[:, time_seq].unsqueeze(1) <br>            else:<br>                # Without teacher forcing: use its own predictions as the next input<br>                _, topi = decoder_output.topk(1)<br>                decoder_input = topi.squeeze(-1).detach()  # detach from history as input<br><br>        ## we then concatenate the decoder_ouptuts that we accumalated over different time-steps to the desire format of size<br>        ## (batch_size, MAX_LENGTH, hidden_size); MAX_LENGTH is the time sequence(e.g. the predicted_output word at that time-step) and<br>        ## hidden_size rep. the &quot;hidden_scores&quot;.<br>        decoder_outputs = torch.cat(decoder_outputs, dim=1)<br><br>        ## same as we did for out decoder_outputs<br>        attentions = torch.cat(attentions, dim=1)<br>        <br>        ## so inorder to get the correct predicted result we, do the log_softmax to that &quot;hidden_score&quot;, maximum of which give us the index<br>        ## for the predicted_word at that time-step<br>        decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)<br>        <br>        ## We return `None` for consistency in the training loop<br>        return decoder_outputs, decoder_hidden, attentions<br><br>    def seq_step(self, input, hidden, encoder_outputs):<br>        embedded = self.dropout(self.embedding(input))<br><br>        ## out of the recurrent network is (1, batch_size, Hidden_size), so to make it (batch_size, 1, Hidden_size) for mathematical <br>        ## convenince we use permute(1, 0, 2) which swap in the 0 and 1  dimension for us.<br>        query = hidden.permute(1, 0, 2)<br>        <br>        ## we call the attention_layer<br>        context, attn_weights = self.attention(query, encoder_outputs)<br><br>        ## As explained before in detail the context vector here is not the simple context_vector but our attention scores, and is feed<br>        ## to the next docoder input seqeunce along with the decoder_input (e.g. [decoder_input + cxt] resulting in a hidden input size<br>        ## of 2*hidden_size) which is feed to out recurrent network as an input.<br>        input_gru = torch.cat((embedded, context), dim=2)<br><br>        output, hidden = self.gru(input_gru, hidden)<br>        output = self.out(output)<br><br>        return output, hidden, attn_weights</pre><p>Here is a closer look at how the Attention Mechanism looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26-Enxg5MjyMqoyZfShREg.png" /><figcaption><strong>Attention Mechanism</strong></figcaption></figure><pre>class attentionMechanism(nn.Module):<br>    def __init__(self, hidden_size):<br>        super(attentionMechanism, self).__init__()<br>        self.Wa = nn.Linear(hidden_size, hidden_size)<br>        self.Ua = nn.Linear(hidden_size, hidden_size)<br>        self.Va = nn.Linear(hidden_size, 1)<br><br>    def forward(self, query, key):<br>        # IMPORTANT for Training ATTENTION Weights<br>        # query: represent the input of the decoder(source input), keys: encoder_outputs<br>        scores = self.Va(torch.tanh(self.Wa(query) + self.Ua(key)))<br><br>        # dimension (batch_size, MAX_LENGTH, 1), rep. the softmax score for each input words in the sequence; <br>        # This softmax score determines how much each word will be expressed at this position. Clearly the word at this position will<br>        # have the highest softmax score, but sometimes it’s useful to attend to another word that is relevant to the current word.<br>        weights = F.softmax(scores, dim=1)<br>        <br>        # dimension (batch_size, MAX_LENGTH, hidden_size), multiple softmax_score with its coresponding input vectors; The intuition <br>        # here is to keep intact the values of the word(s) we want to focus on, and drown-out irrelevant words (by multiplying them by <br>        # tiny numbers like 0.001, for example). <br>        <br>        # This will give us a vectors with releveant scoring wrt the query word<br>        context = key * weights<br><br>        # We then sum up the each hidden_vector and get the &quot;context_vector&quot; in response with dimenstion (batch_size, 1, hidden_size), which<br>        # along with the &quot;decoder_input&quot; act as an input to the decoder.<br>        context = torch.sum(context, dim=1, keepdim=True)<br><br>        return context, weights</pre><p>Having possessing only <strong><em>111 training samples</em></strong> for the <strong><em>Garhwali language</em></strong>, which is limited compared to common training datasets, the model equipped with <strong><em>attention mechanism </em></strong>still demonstrates promising language understanding. Despite been a complex language though semantically incorrect translations result, the attention mechanism facilitates capturing phonetic elements of the language to some extend. This provides insightful glimpses into the potential of the network when combined with attention.</p><p>With increased training data in the future, we can expect significant improvements in translation quality. By feeding the network with a richer corpus of <strong><em>Garhwali</em></strong> sentences, the attention mechanism will have more information to draw upon, allowing it to:</p><ul><li><strong><em>Refine semantic understanding:</em></strong> Capture not only phonetics but also the deeper meaning and grammatical structure of the language.</li><li><strong><em>Reduce semantic errors:</em></strong> Generate more accurate and nuanced translations, minimizing semantic deviations from the source text.</li><li><strong><em>Enhance model generalizability</em>:</strong> Adapt to diverse linguistic patterns and translate even complex sentences effectively.</li></ul><p>Therefore, while the current results with limited data are encouraging, they serve as a stepping stone towards achieving high-quality <strong><em>Garhwali</em></strong> translations through further training and leveraging the power of attention mechanism.</p><pre>def asMinutes(s):<br>    m = math.floor(s / 60)<br>    s -= m * 60<br>    return &#39;%dm %ds&#39; % (m, s)<br><br>def timeSince(since, percent):<br>    now = time.time()<br>    s = now - since<br>    es = s / (percent)<br>    rs = es - s<br>    return &#39;%s (- %s)&#39; % (asMinutes(s), asMinutes(rs))<br><br>def train_epoch(dataloader, encoder, decoder, encoder_optimizer,<br>          decoder_optimizer, criterion):<br><br>    total_loss = 0<br>    for data in dataloader:<br>        input_tensor, target_tensor = data<br><br>        encoder_optimizer.zero_grad()<br>        decoder_optimizer.zero_grad()<br><br>        encoder_outputs, encoder_hidden = encoder(input_tensor)<br>        decoder_outputs, _, _ = decoder(encoder_outputs, encoder_hidden, target_tensor)<br><br>        loss = criterion(<br>            decoder_outputs.view(-1, decoder_outputs.size(-1)),<br>            target_tensor.view(-1)<br>        )<br>        loss.backward()<br><br>        encoder_optimizer.step()<br>        decoder_optimizer.step()<br><br>        total_loss += loss.item()<br><br>    return total_loss / len(dataloader)<br><br>def test_epoch(dataloader, encoder, decoder, criterion):<br>    total_loss = 0<br>    with torch.no_grad():  # Disable gradient calculation for testing<br>        for data in dataloader:<br>            input_tensor, target_tensor = data<br><br>            encoder_outputs, encoder_hidden = encoder(input_tensor)<br>            decoder_outputs, _, _ = decoder(encoder_outputs, encoder_hidden, target_tensor)<br><br>            loss = criterion(<br>                decoder_outputs.view(-1, decoder_outputs.size(-1)),<br>                target_tensor.view(-1)<br>            )<br>            total_loss += loss.item()<br><br>    return total_loss / len(dataloader)<br><br>def train(train_dataloader, encoder, decoder, n_epochs, learning_rate=0.001,<br>               print_every=100, plot_every=100):<br>    start = time.time()<br>    plot_losses = []<br>    print_loss_total = 0  # Reset every print_every<br>    plot_loss_total = 0  # Reset every plot_every<br><br>    encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)<br>    decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate)<br>    criterion = nn.NLLLoss()<br><br>    for epoch in range(1, n_epochs + 1):<br>        # Training phase<br>        loss = train_epoch(train_dataloader, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)<br>        print_loss_total += loss<br>        plot_loss_total += loss<br><br>        if epoch % print_every == 0:<br>            print_loss_avg = print_loss_total / print_every<br>            print_loss_total = 0<br>            print(&#39;%s (%d %d%%) %.4f&#39; % (timeSince(start, epoch / n_epochs),<br>                                        epoch, epoch / n_epochs * 100, print_loss_avg))<br><br>        if epoch % plot_every == 0:<br>            plot_loss_avg = plot_loss_total / plot_every<br>            plot_losses.append(plot_loss_avg)<br>            plot_loss_total = 0<br>            <br>        # Evaluation phase<br>        test_loss = test_epoch(test_dataloader, encoder, decoder, criterion)<br>        print(f&#39;Epoch {epoch}, Test Loss: {test_loss:.4f}&#39;)  # Print test loss<br>    <br>    return plot_losses</pre><p>Here are some result that we get while training it for <strong><em>1000 epochs</em></strong>, <strong><em>0.1 dropout</em></strong>, &amp; using <strong><em>Single Training batch</em></strong> getting us to training and validation loss of <strong><em>0.005</em></strong> &amp; <strong><em>0.0021</em></strong> respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9-Q-cygHD_ZyaY2tgt88Xw.png" /></figure><p>Since we only have less data sample at <strong><em>5% split</em></strong> is done, here is the code for the same.</p><pre>def get_dataloaders(batch_size):<br>    input_lang, output_lang, pairs, MAX_LENGTH = prepareData(&#39;hin_eng&#39;, &#39;garh&#39;)<br><br>    n = len(pairs)<br>    <br>    input_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)<br>    target_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)<br><br>    for idx, (inp, tgt) in enumerate(pairs):<br>        inp_ids = indexesFromSentence(input_lang, inp)<br>        tgt_ids = indexesFromSentence(output_lang, tgt)<br>        inp_ids.append(EOS_token)<br>        tgt_ids.append(EOS_token)<br>        input_ids[idx, :len(inp_ids)] = inp_ids<br>        target_ids[idx, :len(tgt_ids)] = tgt_ids<br><br>    dataset = TensorDataset(torch.LongTensor(input_ids).to(device),<br>                            torch.LongTensor(target_ids).to(device))<br><br>    # Split into training and test sets<br>    test_size = int(0.05 * len(dataset))  # 5% for testing<br>    train_size = len(dataset) - test_size<br>    train_dataset, test_dataset = random_split(dataset, [train_size, test_size])<br><br>    train_sampler = RandomSampler(train_dataset)<br>    test_sampler = SequentialSampler(test_dataset)  # Ensure deterministic order for testing<br><br>    train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=batch_size)<br>    test_dataloader = DataLoader(test_dataset, sampler=test_sampler, batch_size=batch_size)<br>    <br>    return input_lang, output_lang, train_dataloader, test_dataloader</pre><p>While some test results deviate from expectations, the model demonstrates a partial ability to capture certain relationships. Notably, in <strong><em>Input_4/Output_</em>4</strong>, the model correctly maps the words “<strong><em>raaste</em></strong>” and “<strong><em>batu</em></strong>” which convey the same meaning.</p><p>Same is also true for sample <strong><em>Input_1/Output_1 </em></strong>where “<strong><em>hu</em></strong>” and “<strong><em>chaun</em></strong>” implies same thing, and we also have <strong><em>Input_2/Output_2 </em></strong>with correct response along with <strong><em>Input_3/Output_3 </em></strong>in some way at-least semantically.</p><pre>test_idx = 0<br>decoded_words = []<br>for idx in X_test[test_idx]:<br>    if idx.item() == 0 or idx.item() == 1:<br>        pass<br>    else:<br>        decoded_words.append(input_lang.index2word[idx.item()])<br><br>test_input = &quot; &quot;.join(decoded_words)<br>input_sequence = test_input<br><br>sentence = normalizeString(input_sequence)<br>print(input_sequence)<br>with torch.no_grad():<br>    input_tensor = tensorFromSentence(input_lang, sentence)<br>    encoder_outputs, encoder_hidden = encoder(input_tensor)<br>    decoder_outputs, decoder_hidden, decoder_attn = decoder(encoder_outputs, encoder_hidden)<br><br>    _, topi = decoder_outputs.topk(1)<br>    decoded_ids = topi.squeeze()<br><br>    decoded_words = []<br>    for idx in decoded_ids:<br>        if idx.item() == 0 or idx.item() == 1:<br>            pass<br>        else:<br>            decoded_words.append(output_lang.index2word[idx.item()])<br>            <br>print(&quot; &quot;.join(decoded_words))</pre><pre>Input_1 :  me theek hu, tum kese ho<br>Output_1:  me theek theek theek chaun theek chaun kai theek theek chaun<br><br>Input_2 :  tumhara naam kya ha<br>Output_2:  tyar naam kya cha ?<br><br>Input_3 :  bhaarat ke kis raajy kee janasankhya sabase adhik hai ?<br>Output_3:  kai india rajya ki jaansakha sabsey bandya cha ?<br><br>Input_4 :  aap kis raaste se aaye ?<br>Output_4:  kai batu aao ? tum kiley aiya ?</pre><h4><strong>Why Transformer?</strong></h4><p>Although with the introduction of attention mechanism we do see the enhance improvement in the recurrent network it still far from what Transformer had brought since its introduction.</p><p>Here’s a breakdown of why transformer models have become increasingly favoured over recurrent seq2seq networks for language translation tasks, even though both utilize attention mechanisms:</p><p><strong><em>Parallel Processing and Speed</em></strong></p><ul><li>Recurrent networks process sequences sequentially, one element at a time, as opposed to transformers leading to slower training and inference</li></ul><p><strong><em>Long-Range Dependencies</em></strong></p><ul><li>While self-attention mechanisms enhanced recurrent networks’ ability to handle longer sequences, their inherent sequential nature still poses challenges for capturing long-range dependencies effectively, especially as sequence length increases. Transformers, in contrast, revolutionise sequence modelling through multi-head attention, not only maintaining long-range dependencies effortlessly but also introducing multifaceted representations that capture information from diverse perspectives.</li></ul><p><strong><em>Global Context</em></strong></p><ul><li>Recurrent networks build context incrementally, with each word’s representation influenced by only those that came before it whereas in transformers, each word’s representation is informed by all other words in the input simultaneously, providing a richer, more comprehensive understanding of the global context.</li></ul><p><strong><em>Improved Performance</em></strong></p><ul><li>Transformers have consistently demonstrated superior performance in various language translation tasks, achieving better accuracy and fluency compared to recurrent seq2seq models.</li></ul><p><strong><em>Easier to Parallelize</em></strong></p><ul><li>The parallelizable nature of transformers makes them more efficient for training on large datasets and deployment on multi-GPU or TPU systems.</li></ul><p><strong>Transformer Architecture</strong></p><p><strong><em>Encoder/Decoder Self-Attention</em></strong></p><p>Query, Key, &amp; Value belong to the same source/target sequence. Where each row(rep. the query) provide how relevant that word is wrt all the word in the source/target sequence to follow.</p><p><strong><em>Encoder-Decoder Attention</em></strong></p><p>Query, &amp; (Key, Value) belong to the different sequence, were <em>query</em> belongs to the source and <em>(key, value)</em> pair belongs to the target sequence however each row(rep. the source <em>query</em>) provide how relevant that word is wrt all the word in the target sequence to follow.</p><p><strong><em>Multi Head Attention Mechanism</em></strong></p><ol><li>It helps the model the ability to focus more on the different position wrt the word in focus. For example If we are translating the sentence say “Divyanshu is a Senior Data Scientist, whose expertise lies in the field of computer vision &amp; NLP Domain”, it would be useful for us to know which word “whose” refers to.</li><li>It helps provide a different representative sub-space of the input sequence , thus gives a way to view the input sequence in a diversified way. Here are some benefits:</li></ol><ul><li><strong><em>Improve Generalisation:</em></strong> Model will be able to translate the input sequence that it has very un-likely seen, by keeping in prospect the different view-points</li><li><strong><em>Enhances expressive power:</em></strong> The model can learn more complex patterns and representations by combining multiple subspaces.</li><li><strong><em>Capture Diverse relationships: </em></strong>Attention heads can focus on different types of relationships within the input, such as word order, semantic similarity, or syntactic structure.</li></ul><blockquote>Decoder is the Auto-aggressive model that generate the word in the sequence so we need to prevent it from conditioning to future tokens, which is done my <strong><em>masking</em></strong>.</blockquote><h3>Conclusion</h3><p>This article explored the intricacies of seq2seq models with self-attention for Hindi to <strong><em>Garhwali</em></strong>(English format for both) translation using PyTorch and GRU networks. We delved into key concepts like <strong><em>encoder-decoder architecture, attention mechanisms, and output states,</em></strong> highlighting their vital roles in accurate and context-aware translation. We also see the detailed descriptive code of the Encoder/Decoder Sequence via Self-Attention, its performance with the limited available data corpus. Furthermore, we also briefly introduced transformer models and its advancement over recurrent network.</p><p>Following our exploration of seq2seq models with self-attention, the next <strong>blog</strong> will shift gears to evaluate the performance of the <strong>Fine-Tuned LMs</strong> (Language Models) &amp; <strong>LLMs</strong>(Large Language Models) on the <strong><em>Hindi-to-Garhwali</em></strong> translation task. These transformer-based models have garnered significant attention, and we’ll be putting their capabilities to the test on the same dataset, which you will see giving us far better results on the same dataset.</p><p>Also do checkout my next <a href="https://ddimri.medium.com/sentencepiece-the-nlp-architects-tool-for-building-bridges-between-languages-7a0b8ae53130"><strong>blog</strong></a> on SentencePiece to delve dive into the tokenization for added vocabulary.</p><p>I truly appreciate your open communication and feedback. It means a lot to me! Stay tuned for further updates, and feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734f3d265b3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Sharing Custom Pipelines with the Hugging Face Hub]]></title>
            <link>https://ddimri.medium.com/building-and-sharing-custom-pipelines-with-the-hugging-face-hub-f50faf6135c5?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50faf6135c5</guid>
            <category><![CDATA[custom-pipeline]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[pre-processing]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 19:28:22 GMT</pubDate>
            <atom:updated>2024-01-10T08:37:51.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>In this blog post, we will discuss the steps involved in deploying a custom model pipeline to the Hugging Face Hub, using the Agri-BERT classification model that we built in our previous blog post as an example. This blog post can be considered as an extension of <a href="https://ddimri.medium.com/bert-for-classification-beyond-the-next-sentence-prediction-task-93acc1412749"><strong>Part I</strong></a>, where we discussed BERT for classification.</p><h3>Introduction</h3><p>Custom model pipelines are a powerful way to extend the capabilities of Hugging Face models. By creating a custom pipeline, you can combine multiple models and pre-processing steps into a single, easy-to-use pipeline. This can be useful for a variety of tasks, such as text classification, question answering, and summarization.</p><p>Deploying a custom pipeline to the Hugging Face Hub is a great way to share your pipeline with others and make it easy for them to use. The Hub is a central repository for Hugging Face models and pipelines, and it is used by millions of people around the world.</p><p>In this blog post, we will walk you through the steps of deploying the Agri-BERT classification pipeline to the Hugging Face Hub. We will cover everything from creating a Hugging Face account to pushing your pipeline to the Hub. The pipeline preprocesses the input text, encodes it and will do the binary classification of the text to its corresponding label.</p><p>By the end of this blog post, you will have a good understanding of how to deploy your own custom pipelines to the Hub.<em>( Note: we will be using Colab for the entire implementation process)</em></p><h3>Discussion</h3><h4><strong>Login to HuggingFace Hub</strong></h4><p>Let’s start first login into the Hugging face, we will use the <em>notebook_login </em>library from <em>huggingface_hub.</em></p><pre>from huggingface_hub import notebook_login<br><br># Login to HF Hub<br>notebook_login()</pre><p>You will be prompted to enter the hugging face token, which you can get from your profile settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHM4lfBOLs6zi62Ae79Vrw.png" /></figure><p><strong>Loading Pre-trained Model and Tokenizer</strong></p><p>Now we need to load our model and the corresponding tokenizer that we used for building our Agri Classification model.</p><pre>from transformers import BertForSequenceClassification<br><br># Load the model architecture<br>model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;)<br><br># Load the saved state dictionary<br>model.load_state_dict(torch.load(&#39;fine_tuned_bert.pth&#39;))</pre><p>Since we will be dealing with the GPU, we need to then move our model to a GPU for accelerated computation using following command. PyTorch will check if a GPU is available in the system. If a GPU is available, it will move the model to the GPU for computations.</p><pre>model.cuda()</pre><p>The architecture looks something like this:</p><pre>BertForSequenceClassification(<br>  (bert): BertModel(<br>    (embeddings): BertEmbeddings(<br>      (word_embeddings): Embedding(30522, 768, padding_idx=0)<br>      (position_embeddings): Embedding(512, 768)<br>      (token_type_embeddings): Embedding(2, 768)<br>      (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>      (dropout): Dropout(p=0.1, inplace=False)<br>    )<br>    (encoder): BertEncoder(<br>      (layer): ModuleList(<br>        (0-11): 12 x BertLayer(<br>          (attention): BertAttention(<br>            (self): BertSelfAttention(<br>              (query): Linear(in_features=768, out_features=768, bias=True)<br>              (key): Linear(in_features=768, out_features=768, bias=True)<br>              (value): Linear(in_features=768, out_features=768, bias=True)<br>              (dropout): Dropout(p=0.1, inplace=False)<br>            )<br>            (output): BertSelfOutput(<br>              (dense): Linear(in_features=768, out_features=768, bias=True)<br>              (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>              (dropout): Dropout(p=0.1, inplace=False)<br>            )<br>          )<br>          (intermediate): BertIntermediate(<br>            (dense): Linear(in_features=768, out_features=3072, bias=True)<br>            (intermediate_act_fn): GELUActivation()<br>          )<br>          (output): BertOutput(<br>            (dense): Linear(in_features=3072, out_features=768, bias=True)<br>            (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>            (dropout): Dropout(p=0.1, inplace=False)<br>          )<br>        )<br>      )<br>    )<br>    (pooler): BertPooler(<br>      (dense): Linear(in_features=768, out_features=768, bias=True)<br>      (activation): Tanh()<br>    )<br>  )<br>  (dropout): Dropout(p=0.1, inplace=False)<br>  (classifier): Linear(in_features=768, out_features=2, bias=True)<br>)</pre><p>We will do the same for the tokenizer.</p><pre>import transformers<br><br># For DistilBERT:<br>tokenizer_class, pretrained_weights = (<br>    transformers.DistilBertTokenizer,<br>    &#39;distilbert-base-uncased&#39;<br>)<br><br># Load pretrained DistilBERTTokenizer <br>tokenizer = tokenizer_class.from_pretrained(pretrained_weights)</pre><p>Then we push both the model and tokenizer to the Hub.</p><pre>model.push_to_hub(&#39;agriBERT_clfModel&#39;)<br>tokenizer.push_to_hub(&quot;agriBERT_clfModel&quot;)</pre><h4>Create Custom Pipeline</h4><p>Now comes the important part<em> </em><strong><em>How to create a custom pipeline ?</em></strong></p><p>Lets understand the process with the code.</p><pre># Custom Inference Pipeline<br>class AgriClfPipeline(Pipeline):<br>    def _sanitize_parameters(self, **kwargs):<br>        preprocess_kwargs = {}<br>        if &quot;text&quot; in kwargs:<br>            preprocess_kwargs[&quot;text&quot;] = kwargs[&quot;text&quot;]<br>        return preprocess_kwargs, {}, {}<br><br>    def preprocess(self, text, **kwargs):<br>        textPre_processing = ProcessText()  <br>        processed_description = textPre_processing(text)<br>        try:<br>            if type(processed_description) == str:<br>                tokenizer = AutoTokenizer.from_pretrained(&quot;divyanshu94/agriBERT_clfModel&quot;)<br>                processed_description = str(processed_description)<br>                predToken = tokenizer.encode(processed_description, add_special_tokens=True)<br><br>                max_len = 155<br>                padded_predToken = np.array([predToken + [0]*(max_len-len(predToken))])<br>                predAttention_mask = np.where(padded_predToken != 0, 1, 0)<br><br>                input_idsPred = torch.tensor(padded_predToken)<br>                attention_maskPred = torch.tensor(predAttention_mask)<br><br>                return {&quot;input_idsPred&quot;: input_idsPred, &quot;attention_maskPred&quot;: attention_maskPred}<br>        except Exception as error:<br>            print(&quot;{}&quot;.format(str(error)))<br>            return -1<br><br>    def _forward(self, model_inputs):<br>        input_idsPred = model_inputs[&quot;input_idsPred&quot;]<br>        attention_maskPred = model_inputs[&quot;attention_maskPred&quot;]<br>        self.model = self.model.to(&quot;cuda&quot;)  # Ensure model is on CUDA if available<br><br>        with torch.no_grad():<br>            output = self.model(input_idsPred.to(&quot;cuda&quot;), token_type_ids=None, attention_mask=attention_maskPred.to(&quot;cuda&quot;))<br>        prediction = 1 if np.argmax(output.logits.cpu().numpy()).flatten().item() == 1 else 0<br><br>        return {&quot;logits&quot;: &quot;agri&quot; if prediction == 1 else &quot;non-agri&quot;}<br><br>    def postprocess(self, model_outputs, **kwargs):<br>        return model_outputs[&quot;logits&quot;]</pre><p>This pipeline consists of your custom class( <em>AgriClfPipeline</em>) that inherit the properties from its base class <em>Pipeline </em>with 4 important methods that need to be implemented namely _sanitize_parameters, preprocess, _forward, and postprocess.</p><blockquote><em>Note: all these parameters are sure to be implemented in anyway, as these are the important methods to make our pipeline work seamlessly without facing any kind of the hiccups.</em></blockquote><p>The structure of this breakdown is to support relatively seamless support for CPU/GPU, while supporting doing pre/postprocessing on the CPU on different threads.</p><ul><li><strong>_sanitize_parameters</strong></li></ul><p>_sanitize_parameters allows users to pass any parameters they want, either at initialization time (e.g. pipeline(..., text=&quot;something&quot;)) or at call time (e.g. pipe = pipeline(...); output = pipe(..., text=&quot;something&quot;)).</p><p>Since my input is text and is only needed in the preprocess pipeline, I will be returning preprocess_kwargs. This will be automatically detected by my preprocess() method.</p><p>We also have postprocess_kwargs for the postprocess() method, which can be used if needed.</p><ul><li><strong>preprocess</strong></li></ul><p>The preprocess() method is responsible for preparing the input text for the BERT model. This includes the following steps:</p><ol><li><strong><em>Cleaning the text</em></strong>: This may involve removing punctuation, stop words, and other irrelevant information.</li><li><strong><em>Tokenizing the text</em></strong>: This involves splitting the text into individual tokens, which are the smallest units of meaning that the BERT model can understand.</li><li><strong><em>Padding the text</em>:</strong> BERT models expect the input text to be of a certain length, so if the input text is too short, it is padded with empty tokens.</li><li><strong><em>Creating the attention mask</em></strong>: The attention mask is a special input to the BERT model that tells it which tokens to pay attention to.</li></ol><p>Once the input text has been preprocessed, it is passed to the _forward() method, which performs the actual prediction task.</p><p>In our case, the preprocess() method is returning the attention mask and token IDs. These are two of the most important inputs to the BERT model, and they are required for the model to make a prediction.</p><ul><li><strong>_forward</strong></li></ul><p>_forward is the implementation detail and is not meant to be called directly. forward is the preferred called method as it contains safeguards to make sure everything is working on the expected device. If anything is linked to a real model it belongs in the _forward method, anything else is in the preprocess/postprocess.</p><p>In our case, the output of the preprocess() method is passed as input to the _forward() method, which returns the label agri or non-agri in a Dictformat.</p><ul><li><strong>postprocess</strong></li></ul><p>postprocess methods will take the output of _forward and turn it into the final output that was decided earlier.</p><p>Here is one important thing to remember, Custom pipelines must be defined in a custom Python file( .py file). If you are using Google Colab, you can use the %%writefile magic command to create a new Python file and write your custom pipeline code to the file.</p><p>In my its agri_custom_pipeline.py file</p><pre>%%writefile agri_custom_pipeline.py</pre><p>This will create a new Python file called agri_custom_pipeline.py in the current working directory. We can then write our custom pipeline code to the file, see the complete code below:</p><pre>%%writefile agri_custom_pipeline.py<br><br>from transformers import AutoTokenizer, BertForSequenceClassification, Pipeline<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import WordNetLemmatizer<br>from nltk.corpus import stopwords<br>from nltk.corpus import wordnet<br>import numpy as np<br>import warnings<br>import string<br>import torch<br>import nltk<br>import re<br><br># Download necessary NLTK packages<br>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br>nltk.download(&quot;stopwords&quot;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;punkt&#39;)<br><br># Supress warning<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br># pre-processing modules<br>class RemovePunctuation:<br>    &quot;&quot;&quot;<br>    class to remove the corresponding punctuation from the list of punctuations<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        :param empty: None<br>        &quot;&quot;&quot;<br>        self.punctuation = string.punctuation<br><br>    def __call__(self, punctuations):<br>        &quot;&quot;&quot;<br>        Apply the transformations above.<br>        :param punctuation: take the single punctuation(in my case &#39;?&#39;)<br>        :return: transformed punctuation list, excluding the &#39;?&#39;<br>        &quot;&quot;&quot;<br>        if type(punctuations) == str:<br>            punctuations = list(punctuations)<br>        for punctuation in punctuations:<br>            self.punctuation = self.punctuation.translate(str.maketrans(&#39;&#39;, &#39;&#39;, punctuation))<br>        return self.punctuation<br><br><br># Accessing the remove_punctuation object<br>remove_punctuation = RemovePunctuation()<br><br><br>def get_wordnet_pos(tag):<br>    if tag.startswith(&#39;J&#39;):<br>        return wordnet.ADJ<br>    elif tag.startswith(&#39;V&#39;):<br>        return wordnet.VERB<br>    elif tag.startswith(&#39;N&#39;):<br>        return wordnet.NOUN<br>    elif tag.startswith(&#39;R&#39;):<br>        return wordnet.ADV<br>    else:<br>        return wordnet.NOUN  # Default to Noun if the part of speech is not recognized<br><br><br>class ProcessText(object):<br><br>    @staticmethod<br>    def remove_punctuation_text(text):<br>        &quot;&quot;&quot;custom function to remove the punctuation&quot;&quot;&quot;<br>        res = (re.findall(r&#39;\w+|[^\s\w]+&#39;, text))<br>        name = []<br>        for word in res:<br>            clean_word = word.translate(str.maketrans(&#39;&#39;, &#39;&#39;, remove_punctuation(&quot;&quot;)))<br>            if clean_word != &quot;&quot;:<br>                name.append(clean_word)<br><br>        return &quot; &quot;.join(name)<br><br>    @staticmethod<br>    def remove_stopwords(text):<br>        stop_words = set(stopwords.words(&#39;english&#39;))<br>        words = word_tokenize(text)<br>        filtered_words = [word for word in words if word.lower() not in stop_words]<br>        return &#39; &#39;.join(filtered_words)<br><br>    @staticmethod<br>    def lower_casing(text):<br>        text_lower = text.lower()<br><br>        return text_lower<br><br><br>    @staticmethod<br>    def lemmatize_text(text):<br>        lemmatizer = WordNetLemmatizer()<br>        words = word_tokenize(text)<br>        tagged_words = nltk.pos_tag(words)<br>        lemmatized_words = [lemmatizer.lemmatize(word, pos=get_wordnet_pos(tag)) for word, tag in tagged_words]<br>        return &#39; &#39;.join(lemmatized_words)<br><br>    @staticmethod<br>    def remove_duplicates_and_sort(text):<br>        # Split the text into individual words<br>        words = text.split()<br><br>        # Create a set to store unique words (which automatically removes duplicates)<br>        unique_words = set(words)<br><br>        # Sort the unique words based on their original order in the text<br>        sorted_unique_words = sorted(unique_words, key=lambda x: words.index(x))<br><br>        # Join the sorted unique words back into a string with space as separator<br>        sorted_text = &#39; &#39;.join(sorted_unique_words)<br><br>        return sorted_text<br><br>    @staticmethod<br>    def remove_numbers(text):<br>        # Use regex to replace all numbers with an empty string<br>        cleaned_text = re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br>        return cleaned_text<br><br>    @staticmethod<br>    def include_words_with_len_greater_than_2(text):<br>        # Split the text into words<br>        words = text.split()<br><br>        # Filter out words with length greater than 2<br>        filtered_words = [word for word in words if len(word) &gt; 2]<br><br>        # Join the filtered words back into a text<br>        cleaned_text = &#39; &#39;.join(filtered_words)<br><br>        return cleaned_text<br><br>    def __call__(self, text):<br>        # remove any punctuation<br>        text = self.remove_punctuation_text(text)<br><br>        # Covert text into lower case<br>        text = self.lower_casing(text)<br><br>        # Stopwords such as &quot;is&quot;, &quot;the&quot;, etc that coney no meaning are removed<br>        text = self.remove_stopwords(text)<br><br>        # Lemmatization is done for converting words to their base or root form, considering their context and part of speech.<br>        text = self.lemmatize_text(text)<br><br>        # Since words are independent to one another in our problem scenario we can sort the text by word and remove any kind of duplicacy<br>        text = self.remove_duplicates_and_sort(text)<br><br>        cleaned_text = self.include_words_with_len_greater_than_2(self.remove_numbers(text))<br><br>        return cleaned_text<br><br><br># custom inference pipeline<br>class AgriClfPipeline(Pipeline):<br>    def _sanitize_parameters(self, **kwargs):<br>        preprocess_kwargs = {}<br>        if &quot;text&quot; in kwargs:<br>            preprocess_kwargs[&quot;text&quot;] = kwargs[&quot;text&quot;]<br>        return preprocess_kwargs, {}, {}<br><br>    def preprocess(self, text, **kwargs):<br>        textPre_processing = ProcessText()  <br>        processed_description = textPre_processing(text)<br>        try:<br>            if type(processed_description) == str:<br>                tokenizer = AutoTokenizer.from_pretrained(&quot;divyanshu94/agriBERT_clfModel&quot;)<br>                processed_description = str(processed_description)<br>                predToken = tokenizer.encode(processed_description, add_special_tokens=True)<br><br>                max_len = 155<br>                padded_predToken = np.array([predToken + [0]*(max_len-len(predToken))])<br>                predAttention_mask = np.where(padded_predToken != 0, 1, 0)<br><br>                input_idsPred = torch.tensor(padded_predToken)<br>                attention_maskPred = torch.tensor(predAttention_mask)<br><br>                return {&quot;input_idsPred&quot;: input_idsPred, &quot;attention_maskPred&quot;: attention_maskPred}<br>        except Exception as error:<br>            print(&quot;{}&quot;.format(str(error)))<br>            return -1<br><br>    def _forward(self, model_inputs):<br>        input_idsPred = model_inputs[&quot;input_idsPred&quot;]<br>        attention_maskPred = model_inputs[&quot;attention_maskPred&quot;]<br>        self.model = self.model.to(&quot;cuda&quot;)  # Ensure model is on CUDA if available<br><br>        with torch.no_grad():<br>            output = self.model(input_idsPred.to(&quot;cuda&quot;), token_type_ids=None, attention_mask=attention_maskPred.to(&quot;cuda&quot;))<br>        prediction = 1 if np.argmax(output.logits.cpu().numpy()).flatten().item() == 1 else 0<br><br>        return {&quot;logits&quot;: &quot;agri&quot; if prediction == 1 else &quot;non-agri&quot;}<br><br>    def postprocess(self, model_outputs, **kwargs):<br>        return model_outputs[&quot;logits&quot;]<br><br></pre><p>We can now import the pipeline into our notebook and use it as follows:</p><pre>from agri_custom_pipeline import AgriClfPipeline</pre><h4><strong>Register The Pipeline</strong></h4><p>Now when the customization of the pipeline is done its time to register our pipeline and then upload it to the hugging face hub so as to make it available for use publicly.</p><p>We do that using PIPELINE_REGISTRYavailable within <em>transformers </em>from <em>HuggingFace Hub.</em></p><pre>from transformers import BertForSequenceClassification<br>from transformers.pipelines import PIPELINE_REGISTRY<br><br># Register your custom pipeline<br>PIPELINE_REGISTRY.register_pipeline(<br>    &quot;agri-classification&quot;,<br>    pipeline_class = AgriClfPipeline,<br>    pt_model = BertForSequenceClassification<br>)</pre><p>In pipeline_class we specify our pipeline class.</p><p>The pt_model argument specifies the BERT model that our pipeline uses which is BertForSequenceClassification here.</p><p>and agri-classification is the name that we have given to our pipeline, a task which is to be added along with the list of supported tasks that the HuggingFace Hub provided. These tasks are performed using the Hub’s pipelines, and are defined in the PIPELINE_REGISTRY class.</p><p>Since we are defining our own custom task we need to add it to our PIPELINE_REGISTRY , that&#39;s what the above command does.</p><p>Once its done we are ready with our pipeline.</p><pre>agri_classifier = pipeline(&quot;agri-classification&quot;, model=&quot;divyanshu94/agriBERT_clfModel&quot;)<br>agri_classifier(&quot;&lt;your input text goes here&gt;&quot;)</pre><p>This will output one of the label agri or non-agri .</p><pre># Output of the pipeline<br>&#39;non-agri&#39; (says)</pre><h4>Uploading to HuggingFace Hub</h4><p>Now we need this to be available publicly for everyone to use. we do this by using the save_pretrained method in a Repository. The Repository class provides a number of methods for interacting with repositories on the Hugging Face Hub.</p><pre>from huggingface_hub import Repository<br><br>repo = Repository(&quot;agriBERT_clfModel&quot;, clone_from=&quot;divyanshu94/agriBERT_clfModel&quot;)<br>classifier.save_pretrained(&quot;agriBERT_clfModel&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jr6JBJOqPVXcN1sdC1dj7g.png" /></figure><p>This will git cloneour model and tokenizer that we uploaded earlier in our Hub to our local directory inside the folder with the same name &quot;agriBERT_clfModel&quot;, along with will also save our classification pipeline in the save folder.</p><p>In short:</p><ol><li>Clone the repository agriBERT_clfModel from the Hugging Face Hub to the local directory.</li><li>Save the classification pipeline to the repository.</li></ol><p>We than simply push the code to the Hub.</p><pre>repo.push_to_hub()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icBvSyVmQ2eYNf9geBT5sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9DNCjeMLkiHG8h9tl5dtg.png" /><figcaption><a href="https://huggingface.co/divyanshu94/agriBERT_clfModel/tree/main">https://huggingface.co/divyanshu94/agriBERT_clfModel/tree/main</a></figcaption></figure><p><strong>Model Inference</strong></p><p>Now the pipeline is available publicly to Hub, can be used by anyone for inference.</p><pre>from transformers import pipeline<br><br>agri_clf = pipeline(model=&quot;divyanshu94/agriBERT_clfModel&quot;, trust_remote_code=True)<br>agri_clf(&quot;&lt;your input text goes here&gt;&quot;)</pre><p>This will output one of the label agri or non-agri .</p><pre># Output of the pipeline<br>&#39;agri&#39; (says)</pre><h3>Conclusion</h3><p>In this blog post, we have discussed the steps involved in deploying a custom model pipeline to the Hugging Face Hub, using the Agri-BERT classification model that we build in <a href="https://ddimri.medium.com/bert-for-classification-beyond-the-next-sentence-prediction-task-93acc1412749"><strong>Part I</strong></a><strong>. </strong>Hope this article will make things clearer to understand.</p><p>Feel free to comment if you have any questions. Your feedback is greatly appreciated and will help me understand the things I am lacking &amp; feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50faf6135c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BERT for Classification: Beyond the Next Sentence Prediction Task]]></title>
            <link>https://ddimri.medium.com/bert-for-classification-beyond-the-next-sentence-prediction-task-93acc1412749?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/93acc1412749</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 22:02:15 GMT</pubDate>
            <atom:updated>2024-01-10T08:38:58.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>In this article, we delve into the world of BERT (<em>Bidirectional Encoder Representations from Transformers</em>), one of the most renowned transformer-based Deep Learning models. While BERT has been a game-changer in the NLP community since its debut in 2018, our focus here is to comprehend the BERT model through the lens of fine-tuning for classification tasks. We will explore how to harness BERT’s unique capabilities, particularly its Next Sentence Prediction (NSP), to enhance our classification endeavors.</p><h3><strong>BERT Architectures</strong></h3><p>BERT is available in two versions: BERT-BASE and BERT-LARGE, each equipped with a different number of encoder layers, which are also referred to as transformer blocks. These encoder layers play a crucial role in the model’s architecture. BERT-BASE has 12 encoder layers, while BERT-LARGE boasts 24 encoder layers.</p><p>What sets these two versions apart is not only the number of encoder layers but also the size of their feed-forward networks and the quantity of attention heads. In BERT-BASE, the feed-forward network has 768 hidden units, and there are 12 attention heads. On the other hand, BERT-LARGE features a more extensive configuration with 1024 hidden units in the feed-forward network and an impressive 16 attention heads.</p><p>This design represents a significant enhancement over the default settings in the original transformer model as described in the foundational paper. The default transformer configuration featured 6 encoder layers, 512 hidden units, and 8 attention heads. BERT’s scaling up to larger models with more encoder layers, hidden units, and attention heads has been instrumental in its success and its ability to handle complex NLP tasks effectively.</p><p>Here we will try to do the classification using two method one with pre-trained weights and second finetune the BERT itself.</p><h3>Approach</h3><p>In this we will try to investigate two different methods for classification using BERT. Our focus is to understand the practical differences in how they are put into action and how these distinctions influence the model’s performance. By conducting this comparative analysis, we aim to provide technical insights into the most effective strategies when working with BERT for classification tasks.</p><h4><strong>BERT with pre-trained weights</strong></h4><p>Lets try to understand the model with BERT-BASE representation. Each position of the input, output’s a vector of size 768 which is a special token(which we will delve deep a bit later) containing feature representation of out input sentence. We then use this feature representation for training our classifier.</p><ul><li>We first try to leverage the pre-trained BERT model, by extracting the features from the last hidden state of size 786, which will be the feature representation of our input text.</li></ul><blockquote>For this we will be using DistilBERT, for extracting pre-trained weights as well as is used for the tokenization. DistilBERT is a smaller version of BERT developed and open sourced by the team at HuggingFace. It’s a lighter and faster version of BERT that roughly matches its performance.</blockquote><ul><li>We than use these feature representation to do the standard classification either using <em>random forest, or logistic regression </em>as per your choice.</li></ul><p>So what is this special token, BERT uses 2 special token one is [CLS] and other is [SEP]. For our classification we leverage the token embedding of [CLS] token, a 786 hidden unit which contains the feature representation of our input text.</p><p><em>Why use </em><em>[CLS] for sentence classification?</em></p><p>The reason been the [CLS] token in BERT helps in containing the encoded information during the NSP(<em>Next Sentence Prediction</em>) by being the global representation of the input sequence.</p><p>Lets try to understand how [CLS] token is trained via NSP and why it contain the feature representation of the input sentence/ text.</p><p>The following example shows how the [CLS] token is used in NSP:</p><pre>Premise: I am Divyanshu.<br>Hypothesis: I work for a service based company as a Data-Scientist.<br><br># In order to prepare this input for the NSP task, you would format it as follows:<br>Input Sequence: [CLS] I am Divyanshu. [SEP] I work for a service based company as a Data-Scientist. [SEP]</pre><ul><li>[CLS] (Classification Token): This token is added at the beginning of the input and represents the start of the sequence. It&#39;s typically used to capture aggregate information about the entire input a stated above.</li><li>[SEP] (Separator Token): This token is used to separate different segments of text within the input. In the context of the NSP task, it indicates the boundary between the two sentences.</li></ul><p>During the NSP training BERT would encode this input sequence and use the output of the [CLS] token to compute the probability distribution over the two possible labels: <em>IsNextSentence</em>and<strong> </strong><em>NotNextSentence</em> . It’s a <em>binary classification</em> task, where BERT is trying to predict the labels for the the given pair of sentences. This help BERT learn the contextual relationships between the sentences, making it capable of understanding text coherence and context in various NLP applications, which in our case is the classification task where we will try to leverage this already trained [CLS] token.</p><pre># For DistilBERT:<br>model_class, tokenizer_class, pretrained_weights = (<br>    transformers.DistilBertModel, <br>    transformers.DistilBertTokenizer, <br>    &#39;distilbert-base-uncased&#39;<br>)<br><br># Load pretrained model/tokenizer<br>tokenizer = tokenizer_class.from_pretrained(pretrained_weights)<br>model = model_class.from_pretrained(pretrained_weights)</pre><p>Here I am working on the text into two category one is agriand other is non-agri. ( <em>because of the confidentiality I will not be sharing the dataset, just for the viewers understanding its a dataset which contains </em><em>agri and </em><em>non-agri input.)</em></p><p><em>Why use </em>bert-base-uncased<em>not </em>bert-base-cased<em> ?</em></p><blockquote>bert-base-uncased is used if the text data is mostly in lowercase/ uppercase and we do not need the model to differentiate between uppercase and lowercase words. It is commonly used when case sensitivity is not crucial, especially in English text. Since for our case we are dealing with sentence classification where word casing is not any issue we go with the bert-base-uncased version and not with the bert-base-cased as it is used when text data contains important information in uppercase letters and we want the model to capture the difference between uppercase and lowercase words. It is useful when maintaining the original casing of words is relevant, such as in NER(Named-Entity-Recognition) tasks.</blockquote><pre>DistilBertModel(<br>  (embeddings): Embeddings(<br>    (word_embeddings): Embedding(30522, 768, padding_idx=0)<br>    (position_embeddings): Embedding(512, 768)<br>    (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>    (dropout): Dropout(p=0.1, inplace=False)<br>  )<br>  (transformer): Transformer(<br>    (layer): ModuleList(<br>      (0-5): 6 x TransformerBlock(<br>        (attention): MultiHeadSelfAttention(<br>          (dropout): Dropout(p=0.1, inplace=False)<br>          (q_lin): Linear(in_features=768, out_features=768, bias=True)<br>          (k_lin): Linear(in_features=768, out_features=768, bias=True)<br>          (v_lin): Linear(in_features=768, out_features=768, bias=True)<br>          (out_lin): Linear(in_features=768, out_features=768, bias=True)<br>        )<br>        (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>        (ffn): FFN(<br>          (dropout): Dropout(p=0.1, inplace=False)<br>          (lin1): Linear(in_features=768, out_features=3072, bias=True)<br>          (lin2): Linear(in_features=3072, out_features=768, bias=True)<br>          (activation): GELUActivation()<br>        )<br>        (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>      )<br>    )<br>  )<br>)</pre><p>Before we hand over the sentence to the BERT, we need to pre-process the text in the format it requires following 3 step process:</p><ul><li>Tokenization</li></ul><p>This break the sentences into the words ad sub-words in the format that BERT is comfortable with, see the below diagram( <em>diagram is just for the explanation purposes and has nothing to do with the dataset</em>).</p><pre>tokenized = productData[&quot;description&quot;].apply((lambda x: tokenizer.encode(x, add_special_tokens=True)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*N2f975k98Jc_4yulWi4KNQ.jpeg" /><figcaption><em>BERT Tokenization by</em><strong><em> </em></strong><a href="https://github.com/jalammar/jalammar.github.io/blob/master/notebooks/bert/A_Visual_Notebook_to_Using_BERT_for_the_First_Time.ipynb"><strong><em>Jalammar</em></strong></a></figcaption></figure><p>BERT uses 101 as [CLS] classifier token index and 102 as [SEP] separator token index.</p><ul><li>Padding</li></ul><pre>max_len = 0<br>for i in tokenized.values:<br>    if len(i) &gt; max_len:<br>        max_len = len(i)<br><br>padded_tokens = np.array([i + [0]*(max_len-len(i)) for i in tokenized.values])<br></pre><p>BERT is a model with <em>absolute position embeddings</em>, means each token in the input sequence is assigned a unique position embedding based on its position in the sequence.</p><p>So it is usually advised to pad the inputs on the right (end of the sequence) rather than the left (beginning of the sequence) This is because the position embedding for a token is based on its position in the sequence, and if the inputs are not padded on the right, then the position embeddings for the padded tokens will be incorrect.</p><p>Our dataset is now padded with below dimensions</p><pre>padded_tokens.shape</pre><pre>(1517, 155)</pre><p>Going with the example above, the padding will looks something like this:</p><pre>[ 101 1045 2572 4487 7054 14235 1012 1045 2147 2005 1037 2326 2241 2194 2004 1037 2951 1011 7155 1012 102 0 0 0 0 0 0 0]</pre><ul><li>Masking</li></ul><p>When feeding padded tokens into BERT, it’s important to ensure that the model doesn’t get confused. To achieve this, we introduce an additional variable that instructs BERT to disregard (or ‘mask’) the padding we’ve included. Padding tokens don’t carry meaningful information, and that’s precisely why we include them — to ensure consistent input lengths. By effectively masking the padding, we ensure that BERT focuses only on the relevant content, enhancing its processing efficiency and accuracy.”</p><pre>attention_mask = np.where(padded_tokens != 0, 1, 0)</pre><p>We than feed the padded &amp; masked output to our model to get all the features, out of which [CLS] is the main goal of focus and we do it as:</p><pre>input_ids = torch.tensor(padded_tokens)<br>attention_mask = torch.tensor(attention_mask)<br><br>with torch.no_grad():<br>    last_hidden_states = model(input_ids, attention_mask=attention_mask)<br><br>features = last_hidden_states[0][:,0,:].numpy()</pre><p>[CLS] for each sentence is the first token of the BERT model which contains the sentence embedding for each sentence and can be extracted as <strong><em>last_hidden_states[0][:,0,:]</em></strong> where size(<em>last_hidden_states</em>) in our case is <strong><em>(1517 x 155 x 768)</em></strong>, We’ll then save those in the <strong><em>features</em></strong> variable, as they’ll serve as the features to our <em>logistics regression or random forest </em>model whichever will be our choice of preference.</p><p>Before moving forward let me also define the pre-processing module which will be come for both the model Architecture.</p><p><strong><em>Pre-Processing Module</em></strong></p><pre>class RemovePunctuation:<br>    &quot;&quot;&quot;<br>    class to remove the corresponding punctuation from the list of punctuations<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        :param empty: None<br>        &quot;&quot;&quot;<br>        self.punctuation = string.punctuation<br><br>    def __call__(self, punctuations):<br>        &quot;&quot;&quot;<br>        Apply the transformations above.<br>        :param punctuation: take the single punctuation(in my case &#39;?&#39;)<br>        :return: transformed punctuation list, excluding the &#39;?&#39;<br>        &quot;&quot;&quot;<br>        if type(punctuations) == str:<br>            punctuations = list(punctuations)<br>        for punctuation in punctuations:<br>            self.punctuation = self.punctuation.translate(str.maketrans(&#39;&#39;, &#39;&#39;, punctuation))<br>        return self.punctuation<br><br><br># Accessing the remove_punctuation object<br>remove_punctuation = RemovePunctuation()<br><br><br>def get_wordnet_pos(tag):<br>    if tag.startswith(&#39;J&#39;):<br>        return wordnet.ADJ<br>    elif tag.startswith(&#39;V&#39;):<br>        return wordnet.VERB<br>    elif tag.startswith(&#39;N&#39;):<br>        return wordnet.NOUN<br>    elif tag.startswith(&#39;R&#39;):<br>        return wordnet.ADV<br>    else:<br>        return wordnet.NOUN  # Default to Noun if the part of speech is not recognized<br><br><br>class ProcessText(object):<br><br>    @staticmethod<br>    def remove_punctuation_text(text):<br>        &quot;&quot;&quot;custom function to remove the punctuation&quot;&quot;&quot;<br>        res = (re.findall(r&#39;\w+|[^\s\w]+&#39;, text))<br>        name = []<br>        for word in res:<br>            clean_word = word.translate(str.maketrans(&#39;&#39;, &#39;&#39;, remove_punctuation(&quot;&quot;)))<br>            if clean_word != &quot;&quot;:<br>                name.append(clean_word)<br><br>        return &quot; &quot;.join(name)<br><br>    @staticmethod<br>    def remove_stopwords(text):<br>        stop_words = set(stopwords.words(&#39;english&#39;))<br>        words = word_tokenize(text)<br>        filtered_words = [word for word in words if word.lower() not in stop_words]<br>        return &#39; &#39;.join(filtered_words)<br><br>    @staticmethod<br>    def lower_casing(text):<br>        text_lower = text.lower()<br><br>        return text_lower<br><br><br>    @staticmethod<br>    def lemmatize_text(text):<br>        lemmatizer = WordNetLemmatizer()<br>        words = word_tokenize(text)<br>        tagged_words = nltk.pos_tag(words)<br>        lemmatized_words = [lemmatizer.lemmatize(word, pos=get_wordnet_pos(tag)) for word, tag in tagged_words]<br>        return &#39; &#39;.join(lemmatized_words)<br><br>    @staticmethod<br>    def remove_duplicates_and_sort(text):<br>        # Split the text into individual words<br>        words = text.split()<br><br>        # Create a set to store unique words (which automatically removes duplicates)<br>        unique_words = set(words)<br><br>        # Sort the unique words based on their original order in the text<br>        sorted_unique_words = sorted(unique_words, key=lambda x: words.index(x))<br><br>        # Join the sorted unique words back into a string with space as separator<br>        sorted_text = &#39; &#39;.join(sorted_unique_words)<br><br>        return sorted_text<br><br>    def remove_numbers(self, text):<br>        # Use regex to replace all numbers with an empty string<br>        cleaned_text = re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br>        return cleaned_text<br><br>    def include_words_with_len_greater_than_2(self, text):<br>        # Split the text into words<br>        words = text.split()<br><br>        # Filter out words with length greater than 2<br>        filtered_words = [word for word in words if len(word) &gt; 2]<br><br>        # Join the filtered words back into a text<br>        cleaned_text = &#39; &#39;.join(filtered_words)<br><br>        return cleaned_text<br><br>    def __call__(self, text):<br>        # remove any punctuation<br>        text = self.remove_punctuation_text(text)<br><br>        # Covert text into lower case<br>        text = self.lower_casing(text)<br><br>        # Stopwords such as &quot;is&quot;, &quot;the&quot;, etc that coney no meaning are removed<br>        text = self.remove_stopwords(text)<br><br>        # Lemmatization is done for converting words to their base or root form, considering their context and part of speech.<br>        text = self.lemmatize_text(text)<br><br>        # Since words are independent to one another in our problem scenario we can sort the text by word and remove any kind of duplicacy<br>        text = self.remove_duplicates_and_sort(text)<br><br>        cleaned_text = self.include_words_with_len_greater_than_2(self.remove_numbers(text))<br><br>        return cleaned_text</pre><p><em>Why use POS for Lemmatization?</em></p><p>Because the same words can have different lemmatized form based on its pos(e.g., noun, verb, adjective, adverb). Example: Consider a word flying , sitting, etc. can have same lemmatized form, This is because these words are treated as a noun in the given sentence rather than a verb; which should be fly, sit, etc. respectively hence introduce pos tagging with lemmatization and also because lemmatization is a process that depends on the context and grammatical role of a word within a sentence.</p><p><strong><em>Random Forest Classification</em></strong></p><p>Lets say we use <em>Random Forest</em><strong><em> </em></strong>for our classification task.</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br># Create a Random Forest Classifier<br>rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)<br><br># Split the dataset into training and testing sets (80% train, 10% test)<br>X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.1, random_state=42)<br><br># Create a Random Forest Classifier<br>rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)<br><br># Train the model on the training data<br>rf_clf.fit(X_train, y_train)<br><br># Make predictions on the test set<br>y_pred = rf_clf.predict(X_test)<br><br># Calculate accuracy<br>accuracy = accuracy_score(y_test, y_pred)<br>print(&quot;Accuracy:&quot;, accuracy)<br><br># Generate a classification report<br>print(&quot;Classification Report:&quot;)<br>print(classification_report(y_test, y_pred))<br><br># Generate a confusion matrix<br>confusion_matrix = confusion_matrix(y_test, y_pred)<br>print(&quot;Confusion Matrix:&quot;)<br>print(confusion_matrix)</pre><p>Below are the sample results from the classification of <em>agri and </em><em>non-agri</em> data on testing dataset, pretty good for small sample size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Xt4n4tzBUKPA_YdtTYBmzg.png" /><figcaption>Classification Metrices</figcaption></figure><p>When experimented with the logistic regression the accuracy got to <em>96.23% . </em>and we will see further improvement in accuracy when we do the classification with fine-tuned BERT model.</p><p><strong><em>Inference Pipeline</em></strong></p><pre>class Predict(object):<br>    def __call__(self, text):<br>        try:<br>            textPre_processing = ProcessText()<br>            processed_description = textPre_processing(text)<br><br>            if type(processed_description) == str:<br>                processed_description = str(processed_description)<br>                predToken = tokenizer.encode(processed_description, add_special_tokens=True)<br><br>                max_len = 155<br>                padded_predToken = np.array([predToken + [0]*(max_len-len(predToken))])<br>                predAttention_mask = np.where(padded_predToken != 0, 1, 0)<br><br>                input_idsPred = torch.tensor(padded_predToken)<br>                attention_maskPred = torch.tensor(predAttention_mask)<br>                with torch.no_grad():<br>                    last_hidden_statesPred = model(input_idsPred, attention_mask=attention_maskPred)<br><br>                featuresPred = last_hidden_statesPred[0][:,0,:].numpy()<br>                predicted_label = rf_model.predict(featuresPred)[0]<br><br>                return predicted_label<br><br>        except Exception as error:<br>            print(&quot;{}&quot;.format(str(error)))<br>            return -1</pre><h4>BERT with Fine-Tuning</h4><p>The problem is still the same but instead of using the last layer feature representation we will fine-tune the complete BERT model for our use-case.</p><p>In this what we did is we leverage the <em>DistilBertTokenizer </em>property to save the <em>attention_mask , </em><em>padding tokens </em>and<em> </em><em>labels </em>that we have calculated above when tokenizing the sentences using <em>DistilBertTokenizer. </em>We save these in a <em>bertInput.pickle </em>file.</p><pre>def save_bertInputs(ids, attention_masks, labels):<br>    # Store features and labels in a dictionary or list<br>    data = {<br>        &#39;input_ids&#39;: ids,<br>        &#39;attention_masks&#39;: attention_masks,<br>        &#39;labels&#39;: labels<br>    }<br><br>    # Save the data to a pickle file<br>    with open(&#39;bertInput.pickle&#39;, &#39;wb&#39;) as f:<br>        pickle.dump(data, f)<br><br><br>save_bertInputs(ids, attention_masks, label)</pre><p>We then loaded the embedding and called our data-loader for test and validation.</p><pre>train_ratio = 0.8<br><br>batch_size = 16<br><br># Indices of the train and validation splits stratified by labels<br>indices = torch.randperm(len(labels)).tolist()<br><br>train_no = int(len(indices) * 0.8)<br>test_no = int(len(indices) - train_no)<br><br>train_idx = np.array(indices[:train_no])<br>val_idx = np.array(indices[-test_no:])<br><br># Train and validation sets<br>train_set = TensorDataset(<br>    attention_masks[train_idx],<br>    input_ids[train_idx],<br>    labels[train_idx]<br>)<br><br>val_set = TensorDataset(<br>    attention_masks[val_idx],<br>    input_ids[val_idx],<br>    labels[val_idx]<br>)<br><br># Prepare DataLoader<br>train_dataloader = DataLoader(<br>            train_set,<br>            batch_sampler = BatchSampler(<br>                RandomSampler(train_set),<br>                batch_size=batch_size,<br>                drop_last=False<br>            )<br>)<br><br>validation_dataloader = DataLoader(<br>            val_set,<br>            batch_sampler = BatchSampler(<br>                RandomSampler(val_set),<br>                batch_size=batch_size,<br>                drop_last=False<br>            )<br>)</pre><p><strong>drop_last</strong> arguments in the BatchSampler allow us to handle cases where number of samples in the dataset are not evenly distributed examples consider a dataset of <strong><em>sample_size</em></strong> 10 and <strong><em>batch_size</em></strong> 3, 10 % 3 = 1, so the last batch will have a sample of size 1 left with it which we can handle using drop_last.</p><p>If <strong><em>drop_last=True</em></strong> it will drop that un-even sample of sample_size=1 while <strong><em>drop_last=False</em></strong> will keep that un-even sample</p><p>Both <strong><em>batch_size</em></strong> &amp; <strong><em>drop_last</em></strong> help us achieve the automatic batching via <strong><em>interactive-style dataset</em></strong> with <strong><em>multi-processing</em></strong> approach.</p><p><strong><em>Model Training</em></strong></p><p>In this case we have used <em>BertForSequenceClassification </em>for both modeling and inference as <em>NSP </em>is all in all a classification problem as explained before.</p><pre># Load the pre-trained BERT model and tokenizer<br>model_name = &#39;bert-base-uncased&#39;<br>model = BertForSequenceClassification.from_pretrained(<br>    pretrained_model_name_or_path=model_name,<br>    output_hidden_states = False,<br>    output_attentions = False,<br>    num_labels = 2,<br>)<br><br>optimizer = torch.optim.AdamW(<br>    model.parameters(),<br>    eps = 1e-08,<br>    lr = 5e-5,<br>)<br><br>model.cuda()</pre><pre>BertForSequenceClassification(<br>  (bert): BertModel(<br>    (embeddings): BertEmbeddings(<br>      (word_embeddings): Embedding(30522, 768, padding_idx=0)<br>      (position_embeddings): Embedding(512, 768)<br>      (token_type_embeddings): Embedding(2, 768)<br>      (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>      (dropout): Dropout(p=0.1, inplace=False)<br>    )<br>    (encoder): BertEncoder(<br>      (layer): ModuleList(<br>        (0-11): 12 x BertLayer(<br>          (attention): BertAttention(<br>            (self): BertSelfAttention(<br>              (query): Linear(in_features=768, out_features=768, bias=True)<br>              (key): Linear(in_features=768, out_features=768, bias=True)<br>              (value): Linear(in_features=768, out_features=768, bias=True)<br>              (dropout): Dropout(p=0.1, inplace=False)<br>            )<br>            (output): BertSelfOutput(<br>              (dense): Linear(in_features=768, out_features=768, bias=True)<br>              (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>              (dropout): Dropout(p=0.1, inplace=False)<br>            )<br>          )<br>          (intermediate): BertIntermediate(<br>            (dense): Linear(in_features=768, out_features=3072, bias=True)<br>            (intermediate_act_fn): GELUActivation()<br>          )<br>          (output): BertOutput(<br>            (dense): Linear(in_features=3072, out_features=768, bias=True)<br>            (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)<br>            (dropout): Dropout(p=0.1, inplace=False)<br>          )<br>        )<br>      )<br>    )<br>    (pooler): BertPooler(<br>      (dense): Linear(in_features=768, out_features=768, bias=True)<br>      (activation): Tanh()<br>    )<br>  )<br>  (dropout): Dropout(p=0.1, inplace=False)<br>  (classifier): Linear(in_features=768, out_features=2, bias=True)<br>)</pre><pre>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br><br>epochs = 10<br>for _ in trange(epochs, desc = &#39;Epoch&#39;):<br><br>    # ========== Training ==========<br><br>    # Set model to training mode<br>    model.train()<br><br>    # Tracking variables<br>    tr_loss = 0<br>    nb_tr_examples, nb_tr_steps = 0, 0<br><br>    for step, batch in enumerate(train_dataloader):<br>        batch = tuple(t.to(device) for t in batch)<br>        b_input_ids, b_input_mask, b_labels = batch<br>        optimizer.zero_grad()<br><br>        # Forward pass<br>        train_output = model(<br>            b_input_ids,<br>            token_type_ids = None,<br>            attention_mask = b_input_mask,<br>            labels = b_labels<br>        )<br><br>        # Backward pass<br>        train_output.loss.backward()<br>        optimizer.step()<br><br>        # Update tracking variables<br>        tr_loss += train_output.loss.item()<br>        nb_tr_examples += b_input_ids.size(0)<br>        nb_tr_steps += 1<br><br>    # ========== Validation ==========<br><br>    # Set model to evaluation mode<br>    model.eval()<br><br>    # Tracking variables<br>    val_accuracy = []<br>    val_precision = []<br>    val_recall = []<br>    val_specificity = []<br><br>    for batch in validation_dataloader:<br>        batch = tuple(t.to(device) for t in batch)<br>        b_input_ids, b_input_mask, b_labels = batch<br>        with torch.no_grad():<br>          # Forward pass<br>          eval_output = model(b_input_ids,<br>                              token_type_ids = None,<br>                              attention_mask = b_input_mask)<br><br>        logits = eval_output.logits.detach().cpu().numpy()<br>        label_ids = b_labels.to(&#39;cpu&#39;).numpy()<br><br>torch.save(model.state_dict(), &#39;fine_tuned_bert.pth&#39;)</pre><p>We then load the saved model and do the inferencing as follows:</p><p><strong><em>Inference</em></strong></p><pre># Load the model architecture<br>model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;)<br><br># Load the saved state dictionary<br>model.load_state_dict(torch.load(&#39;fine_tuned_bert.pth&#39;))<br><br>model.cuda()<br><br>class Predict(object):<br>    def __call__(self, text):<br>        try:<br>            textPre_processing = ProcessText()<br>            processed_description = textPre_processing(text)<br><br>            if type(processed_description) == str:<br>                processed_description = str(processed_description)<br>                predToken = tokenizer.encode(processed_description, add_special_tokens=True)<br><br>                max_len = 155<br><br>                padded_predToken = np.array([predToken + [0]*(max_len-len(predToken))])<br>                predAttention_mask = np.where(padded_predToken != 0, 1, 0)<br><br>                input_idsPred = torch.tensor(padded_predToken)<br>                attention_maskPred = torch.tensor(predAttention_mask)<br><br>                with torch.no_grad():<br>                    output = model(input_idsPred.to(device), token_type_ids = None, attention_mask = attention_maskPred.to(device))<br><br>                prediction = 1 if np.argmax(output.logits.cpu().numpy()).flatten().item() == 1 else 0<br><br>                return prediction<br><br>        except Exception as error:<br>            print(&quot;{}&quot;.format(str(error)))<br>            return -1</pre><p>Below are the sample results from the classification of <em>agri and </em><em>non-agri</em> data on testing dataset, using fine-tuned model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*_-AA0R974xG2DQJ1TF7MSA.png" /><figcaption>Classification Metrices</figcaption></figure><h3>Conclusion</h3><p>In this article, we try to understand BERT by its different way of achieving same( classification) task and also saw how fine-tuning the BERT model for classification tasks, surpassing the conventional pre-trained BERT + logistic regression/ random forest method.</p><p>While the accuracy difference may not be substantial due to our limited data points, the fine-tuned BERT model still shines, showcasing its remarkable ability to understand intricate relationships within the data, resulting in higher accuracy, improved precision, and enhanced performance across our classification tasks.</p><p>This only shows that with an increase in data points, we can anticipate even greater improvements in model accuracy. Expanding our dataset is poised to further elevate the performance of fine-tuned BERT.</p><p>This blog is designed to provide viewers with a deeper understanding of BERT implementation and its various approaches on classification task. Now since the model is ready to use how do we deploy our Model, Tokenizer and all the Text Pre-processing steps aggregated as one to be used directly just by calling the model. For this we will be using hugging face, deploy our custom pipeline in our next blog post as a <a href="https://ddimri.medium.com/building-and-sharing-custom-pipelines-with-the-hugging-face-hub-f50faf6135c5"><strong>Part II</strong></a> of this.</p><p>Your comments and feedback are greatly appreciated for open communication and further insights. Feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93acc1412749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision Metrices]]></title>
            <link>https://ddimri.medium.com/computer-vision-metrices-38e2401934b2?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/38e2401934b2</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[recall]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[precision]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Thu, 04 May 2023 12:35:37 GMT</pubDate>
            <atom:updated>2024-01-10T08:40:02.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Here we will try to understand different types of validation metrics starting off with the basic and then will expand our understanding to the more advance metrices says <strong><em>precision@k, recall@k, MAP, and DCMP/ IDCMP</em>.</strong> And will try to understand each one of them in detail with sample example.</p><p>First thing that comes in our mind when we think of the model evaluation matrices is the accuracy, which is nothing but the ratio of the correct prediction to the total no. of samples from which the prediction is made. remember though we can calculate the accuracy in both test /train dataset but the actual model accuracy is always be calculated on test data.</p><p>But the accuracy is not always the accurate approximation of the model performance. The accuracy of 100% doesn’t always implies that is a perfect model.</p><p>Consider we are working on the model (in medical domain), where we need to classify whether a person is sick or not. So thing might go haywire where Diagnose sick person get classified healthy or vice versa which we referred as False Negative(FN) and False Positive(FP) respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*8IVdbwELv2mnvxffLDjnHQ.png" /><figcaption>where sick ~ 1 and healthy ~ 0</figcaption></figure><p>So in this case we don’t want our medical model, especially in a sick person case to get classified as healthy, implies we need FN frequency as low as possible as we want then the FP one, which we can ignore in some extreme scenario.</p><p>Now consider a scenario where we are building a Spam Detector Model, same cannot be true here because in this we can afford to have spam mails in ham but vice-versa is we cannot, which implies it emphasizes more on FP side rather than FN. So depending on the problem statement we need to decide which one to choose and which not or rather a better term will be “focus”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*epzbt4EFFr3e7axcIug9RA.png" /><figcaption>where, spam ~ 1 and ham ~ 0</figcaption></figure><p>So its kind of one need high recall and other high precision. In our case spam detector is a high precision model while Medical model is a high recall model.</p><p>In some cases we can go with either one of them but in most cases we need to find a middle ground with one score, that is were <strong><em>f1 score </em></strong>comes into play or we can calculate the average of both precision and recall but will that be a good metric, lets see.</p><p>consider a credit card fraud example where fraud ~ 1 and not-fraud ~ 0. But before that lets deep dive into precision-recall tradeoff. Look into the confusion matrix below to get the idea for the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*ClPYytbg3KRG0ia5FJwmsw.jpeg" /><figcaption><strong>confusion matrix</strong></figcaption></figure><p>Precision tells us out of all the prediction that we have made how many did we predict correctly. In credit card fraud example lets say we have 284,335 good cards and 472 bad card and our model predict everything is good so all the transactions are good. So this gives us 100% <strong><em>precision </em></strong>since no transaction is fraud &amp; <strong><em>recall</em></strong> will be out of all the fraud transaction how many did we catch, which implies 0% recall.</p><p>which average out to be 50% which is quiet high score for a biased model, institutively it should give a score close to 0 which is not the case here.</p><p>Now let’s consider another extreme case where all transaction are fraudulent; which will give the <strong><em>precision </em></strong>of 1.6% and <strong><em>recall </em></strong>of 100%, again the average score is around 50%.</p><p>Hence we can say that its not good to take average of precision and recall as a metric measurement for our model rather we can go with some more appropriate model metric which is where <strong><em>f1 score</em></strong> comes into play.</p><p><strong><em>f1 score</em></strong> gives more weightage to the min(precision, recall) thus reducing the total model accuracy close to 0 in case of biasness such as in above fraud card model scenario, it does by providing a accurate model metric that hits the middle ground thus reducing the biasness in the model.</p><p>So in a way in general we are trying to come up with an optimized f1 score, its kind of hyper-parameter tuning of precision and recall based on the problem scenario we encounter, so as to land up in the middle ground.</p><p>Let’s now discuss some of the new metrics which comes into play especially when dealing with bigger problems like recommendation system, or Information retrieval system. These include <strong><em>recall@k , precision@k, MAP, DCG and IDCG.</em></strong></p><p>Let’s discuss these metrics in respect of recommendation system.</p><p>Consider a recommendation system that recommend us N items for each user. Let’s consider for a single user with N~5.</p><p>Let’s say our system recommends us 5 list of items out of which only 3 are the actual recommended items and two are not.</p><p>And out of the total of 7 actual recommended list our recommended system recommend us only 3, with all these we can say that we have TP=3, FP=2 and FN=4.</p><p>Which implies precision as out of all the recommend items that our model has recommended how much of the items are good (3/5). And recall measure the fraction of the relevant items out of all relevant items (3/7).</p><p>Here if you see the above recall scenario if we recommend a lot of items our recall will be high and will be increasing thus is not a good metric for our recommendation system and also for our recommended system we want the relevant items as high as possible thus having high probability score than the one coming n the lower order which is not the case when we consider this<strong><em> precision@k/ recall@k</em></strong> metrics.</p><p>That is precision and recall does not take into account the rank order and we will get a same result for both that where we bring into play the MAP, a concept of mean average precision which take the rank order into consideration.</p><p>MAP is a ranked precision metric that places emaphsis on highly ranked correct predictions (hits).</p><p>So a question might have comes into your mind why not use something like <strong><em>MAR</em></strong><em>(Mean average recall)</em>. The reason that I think of that recall is not a good metric is, it’s kind of do the averaging considering all the relevant items that is not playing any role in our prediction and is also highly unstable because, as we keep on increasing the value of the k it also keep increasing giving us a falsify sense of accuracy.</p><p>Another metrics that comes next in the list are <strong><em>DCG</em></strong><em>(Discounted cumulative gain)</em> and <strong><em>IDCG</em></strong><em>(Ideal Discounted cumulative gain )</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*TJzyvv9Hcl_mM4wyE9i5pw.jpeg" /><figcaption>DCG/IDCG example by <a href="https://www.youtube.com/watch?v=mpv8iMe24-Q"><strong>Wang Hao</strong></a></figcaption></figure><p><strong><em>DCG </em></strong>is the logarithmic reduction factor which gave weightage to the relevant items more than to the irrelevant items.</p><p>Where’s <strong><em>IDCG </em></strong>is just a <strong><em>DCG </em></strong>but it calculate the <strong><em>DCG </em></strong>by re-ordering the relevant items at the top of the list which is an ideal for of <strong><em>DCG </em></strong>hence called <strong><em>IDCG</em></strong>.</p><p>We then use ratio of <strong><em>DCG/IDCG</em></strong> to come up with a score for our recommendation system based on which we can validated our results.</p><p>Feel free to comment if you have any questions. Your feedback is greatly appreciated and will help me understand the things I am lacking &amp; feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e2401934b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Contrastive Search]]></title>
            <link>https://ddimri.medium.com/deep-dive-into-contrastive-search-ed37aa987b14?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed37aa987b14</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deep-dive-search]]></category>
            <category><![CDATA[image-retrieval]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[contrastive-learning]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 16:20:43 GMT</pubDate>
            <atom:updated>2024-01-10T08:42:06.900Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article we will try to understand the concept of contrastive learning with some example scenario that we may face while working on the problem of image matching or doing query searching which is a image retrieval problem in the computer vision domain, In real world application one will hardly get any label data over the internet and you will need to find your own way to label it manually going over millions of data points or will do A smart way, that is where comes the concept of self-supervised technique which we will learn here today using the contrastive learning.</em></p><h3>Table of Content</h3><ul><li>Understanding Contrastive Learning using SimCLR Architecture Stage-wise<br> — <strong>Stage I:</strong> <em>What is </em><strong><em>Data Augmentation?</em></strong><br> — <strong>Stage II:</strong> <strong><em>Feature Representation</em></strong><br> — <strong>Stage III:</strong> <strong><em>Projection Head &amp;</em></strong><br> — <strong>Stage IV:</strong> <strong><em>Contrastive Loss Function</em></strong></li><li>Pytorch Implementation<br> — <strong>Data Augmentation in Pytorch</strong><br> — <strong>Custom Transformation Function</strong><br> — <strong>Custom Batch Display Implement</strong><br> — <strong>Encoder Implementation using pre-trained ResNet</strong><br> — <strong>Projection Head Implementation</strong><br> — <strong>Contrastive Loss Function </strong><br> — <strong>Training Pipeline</strong></li><li>Conclusion</li></ul><h4><strong>Understanding Contrastive Learning using SimCLR Architecture</strong></h4><p>Lets discuss first what is<em> </em><strong><em>self-supervised learning</em></strong><em> </em>in term of computer vison concept. A <em>self supervised learning</em> is a kind of learning technique where the model try to come up which some feature representation of an image without given any kind of label data as we do in a <em>supervised learning</em>. Given only the data points its kind of, try to come up with some learning representation of the image into some meaningful vector space which we further use for our future application.</p><p>Contrastive learning is a kind of self-supervised machine learning technique used to learn the general features of a dataset without labels by teaching the model which data points are similar or different. So given the million of batch data as input to the model contrastive learning try to find out the feature vector representation of the images that are similar or different to one another.</p><p><strong><em>Let us understand the analogy and the intuition behind it?</em></strong></p><p>The intuition behind it is that, we feeds the model with the similar/ different looking images and with our network of non-linear activation function at each layers it try to find out feature that overall generalize the mapping function that defines the similarity and dissimilarity,</p><p>Just as a child when given a pair of objects of 2 different colors (say’s red &amp; green for object1 pair and object2 pair respectively), when given a third object pair of color (says yellow) will be able to figure out on its own that the pair has a same color even when it has not seen it before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*boq7l55Hd7tN9p_-o5QF0w.jpeg" /><figcaption><strong>Understanding contrastive learning through child analogy</strong></figcaption></figure><p>Similar to this analogy our Neural network also learns when it sees million of paired training samples that defines similarity and dissimilarity it figured out on its own patterns (feature representation) such that when it sees some out of bags samples during testing it easily finds out the correct mapping.</p><p><strong><em>working of contrastive learning?</em></strong></p><p>Given the image dataset without labels we are to train our model so that it can quickly adapt to any image recognition task afterward. In this tutorial we will discuss on of the most common simple to understand model in this domain called SimCLR, which is visualized as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QoDlSUaVayFafhTLYScB3g.jpeg" /><figcaption><strong>A simple framework for contrastive learning of visual representations, an Architecture overview by </strong><a href="https://arxiv.org/pdf/2002.05709v3.pdf"><strong>Ting Chen, Simon Kornblith, Mohammad Norouzi, Geoffrey Hinton</strong></a></figcaption></figure><p>Contrastive learning is motivated by the question how likely are two images similar/ different from one another, how it odes that its intuition I have already explain in above paras. I consist of 3 major stages with which we will describe how it work.</p><p><strong>Stage I</strong></p><p><strong><em>Data Augmentation</em></strong></p><p>Image augmentation is a technique to artificially create new training data from existing training data. It acts as a regularizer and helps reduce overfitting when training a model. It helps us to increase the size of the dataset and introduce variability in the dataset, without actually collecting new data. The neural network treats these images as distinct images anyway. The dataset was observed to have less variance and relevant samples in it.</p><p>SimCLR leverage the idea of data augmentation &amp; uses it to perform its training. Augmentation is one of the most crucial hyperparameter if SimCLR since it directly affect the structure of the latent space, and what patterns might be learned from the data.</p><p>It is of the opinion that the augmentation combination of Crop, Blur, Jitter, Flip and Gray Scale provide the great variability in the dataset and gives the better compared representation metric for the images. Although any combination of the augmentation can be used but that stand out out of them is the crop + resize and color distortion, why?</p><p><em>So how does crop + resize and color distortion stands out?</em></p><p>When we do random cropping and then resize the image, we are left with two scenario that can affect the feature vector performance of the model as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*Jnkr-qGe0Pyh1ZxLbP6QSA.jpeg" /><figcaption><strong>(a) Global and local views by </strong><a href="https://arxiv.org/pdf/2002.05709v3.pdf"><strong>Ting Chen &amp; Groffrey Hinton</strong></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*GN2osmv85KPEG2seJavDIQ.jpeg" /><figcaption><strong>(b) Adjacent views by </strong><a href="https://arxiv.org/pdf/2002.05709v3.pdf"><strong>Ting Chen &amp; Groffrey Hinton</strong></a></figcaption></figure><p>(a) we can be left as a two crop images of the same image such that image A provide the local view of the cropped image B or (b) it can be cropped images A and image B showing the neighboring view of the same image; see above figure.</p><p>When situation (a) occur it makes the model to learn some sort of scale invariance to make image crop A and B similar in the latent space, while when (b) occur it makes model to learn feature beyond its limited view as now they do not share any kind of common boundary, but they still be able to learn some common features based on the color intensity of the two cropped images example (says Dog ) if cropped with the adjacent view the model can easily be able to learn feature based on the color space of the Dog, i.e. simply from the color of the fur and green tone of the background, one can easily say that two crop patches belongs to the same image without actually recognizing the dog in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6WcdW7hL7uSFH7fR-RGxQ.jpeg" /><figcaption><strong>Illustrations of the studied data augmentation operators. </strong><a href="https://arxiv.org/pdf/2002.05709v3.pdf"><strong>(Original image cc-by: Von.grzanka)</strong></a></figcaption></figure><p>But in such cases too it will cause the model to focus too much of the color histogram of the images and thus ignoring more generalizable feature, that is where adding the color distortion/ jitter along with the crop+resize and color makes the model learn more generalize features in common thus adding a kind of a generalization affect.</p><p><strong>Stage II</strong></p><p><strong><em>Feature Representation</em></strong></p><p>Now in order for the model to learn something from the positive pairs we first need a vector representation of the images and for this we can take help of the deep learning models. We can ether create one from scratch or use some pre-trained model and fine tune it for our purpose(say Big-CNN such as ResNet) to create the vector representation for each image pair.</p><p>The goal is to train the model so as to output similar representation for similar images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*KFlN7JC3vOtkPAeJM_pVEg.jpeg" /></figure><p><strong>STAGE III</strong></p><p><strong><em>Projection Head</em></strong></p><p>Projection head is a mapping function that takes the feature representation of the of the previous layer and projects the image vector(High Dimensional Image Vector) to some Low dimensional Image vector.</p><p>The intuition behind this is to overcome one of the biggest problem of the High Dimension Vectors called “Curse of Dimensionality”.</p><p><em>What is curse of dimensionality?</em></p><blockquote>The higher the dimension we have the more variable we add or more variable we considering to our problem, the exponentially more data points we needed in order to achieve the same level of statistical significance and robustness</blockquote><p>Thus to overcome this issue of dimensionality we perform the projection mapping using multilayer perceptron (MLP), a mapping to low dimension space. And same is the reasoning behind suing similarity metric such as cosine similarity instead of Euclidean norm as Cosine similarity maps similar looking vectors to its correct cluster in higher dimension, they are more precise than Euclidean norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amn-t0c4Bs3D0sEoTabqYQ.jpeg" /><figcaption><strong>vector representation in 2D space. ( Original image cc-by: </strong><a href="https://learning.oreilly.com/library/view/mastering-machine-learning/9781785283451/?_gl=1*ifs7ia*_ga*MTgwNDY0Njc3OS4xNjgwMDE4ODI2*_ga_092EL089CH*MTY4MDAxODgyNi4xLjEuMTY4MDAxODk1Ny41Ni4wLjA."><strong>Alex Tellez, Max Pumperla, Michal Malohlava</strong></a><strong>)</strong></figcaption></figure><p><strong>STAGE IV</strong></p><p><strong><em>Contrastive Loss Function</em></strong></p><p>Lastly we try to maximize the similarity of the two vector representations by minimizing a contrastive loss function.</p><p>Overtime , the model will learn that 2 images of (sys dogs) should have a similar representation and that the representation of dog should be differnt from that of a cat.</p><p>This implies that the model is able to distinguish between different types if images without even knowing what the images are.</p><p>For the loss function we use a NT-Xent(Normalized Temperature-Scaled Cross Entropy Loss)</p><p><em>NT-Xnet</em> is the <em>SoftMax </em>with input to the fn. is the cosine similarity as discussed in above stage. with this our model tried to assign the highest probability to that positive pairs such that the sum of the output vector is equal to one.</p><p>where Numerator is the positive sample and denominator is the sum of e^similarity(all pairs, including Negative pairs).</p><p>Negative pairs are obtained by creating pairs between our augmented images, and all of the other images in our batch.</p><p>We then -log this SoftMax function and model is trained to minimize this loss. Negative sign is for the mathematical convenience since the log function output negative values for x in range(0, 1). Thus negative sign to minimize it which in turns maximizing the probability that two images are similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWIIXgBva3sBS_Aen5Uj8Q.jpeg" /><figcaption><strong>The contrastive loss function. (Original cc-by: </strong><a href="https://arxiv.org/pdf/2002.05709v3.pdf"><strong>Ting Chen &amp; Groffrey Hinton</strong></a><strong>)</strong></figcaption></figure><h4>Pytorch Implementation</h4><p><strong>Data Augmentation in Pytorch</strong></p><pre>class CLDataset:<br>    &quot;&quot;&quot;<br>    Contrastive Learning Dataset<br>    &quot;&quot;&quot;<br>    def __init__(self, images, split=&quot;TRAIN&quot;):<br><br>        self.images = images<br>        self.SPLIT = split<br><br>    def __getitem__(self, idx):<br>        &quot;&quot;&quot;<br>        :param idx: index, Integer Index<br>        :return: normalized Tensor Image, normalized Tensor Landmarks as dictionary for the given Index<br>        &quot;&quot;&quot;<br>        image = self.images[idx]<br>        image = np.asarray(image).transpose(1, 2, 0)<br><br>        image = image.astype(&#39;uint8&#39;)<br><br>        image = transforms.ToPILImage()(image)<br><br>        image1 = transform(image, split=self.SPLIT)<br>        image2 = transform(image, split=self.SPLIT)<br><br>        return image1, image2<br><br>    def __len__(self):<br>        return self.images.shape[0]<br><br><br>dataset = CLDataset(images)</pre><p><strong>Custom Transformation Function</strong></p><pre># Python imports<br>from PIL import Image<br>import pandas as pd<br>import numpy as np<br>import random<br>import time<br>import copy<br>import sys<br>import cv2<br>import re<br><br># Pytorch imports<br>import torchvision.transforms.functional as FT<br>from torchvision.models import resnet18<br>from torchvision import transforms<br>import torch.optim as optim<br>import torch.nn as nn<br>import torchvision<br>import torch<br><br>def display_image(image):<br>    &quot;&quot;&quot;<br>    :param image: image, a PIL Image<br>    :return: void, Display Image<br>    &quot;&quot;&quot;<br>    image = np.array(image)<br><br>    cv2_imshow(image)<br><br>def photometric_distort(image):<br>    &quot;&quot;&quot;<br>    Distort brightness, contrast, saturation, and hue, each with a 50% chance, in random order.<br>    :param image: image, a PIL Image<br>    :return: distorted image<br>    &quot;&quot;&quot;<br>    new_image = image<br><br>    distortions = [FT.adjust_brightness,<br>                   FT.adjust_contrast,<br>                   FT.adjust_saturation,<br>                   FT.adjust_hue]<br><br>    random.shuffle(distortions)<br><br>    for d in distortions:<br>        if random.random() &lt; 0.5:<br>            if d.__name__ == &#39;adjust_hue&#39;:<br>                # Caffe repo uses a &#39;hue_delta&#39; of 18 - we divide by 255 because PyTorch needs a normalized value<br>                adjust_factor = random.uniform(-18 / 255., 18 / 255.)<br>            else:<br>                # Caffe repo uses &#39;lower&#39; and &#39;upper&#39; values of 0.5 and 1.5 for brightness, contrast, and saturation<br>                adjust_factor = random.uniform(0.5, 1.5)<br><br>            # Apply this distortion<br>            new_image = d(new_image, adjust_factor)<br><br>    return new_image<br><br>def resize(image, dims=(224, 224)):<br>    &quot;&quot;&quot;<br>    Resize image.<br><br>    you may choose to retain them.<br>    :param dims: default dimension to resize<br>    :param image: image, a PIL Image<br>    :return: resized image<br>    &quot;&quot;&quot;<br>    image = FT.to_pil_image(np.array(image))<br><br>    # Resize image<br>    new_image = FT.resize(image, dims)<br><br>    return new_image<br><br>def flip(image):<br>    &quot;&quot;&quot;<br>    Flip image horizontally.<br>    :param image: image, a PIL Image<br>    :return: flipped image<br>    &quot;&quot;&quot;<br>    # Flip image<br>    new_image = FT.hflip(image)<br><br>    return new_image<br><br>class ToTensor(object):<br><br>  def __call__(self, image):<br>    image = np.asarray(image, dtype = float)<br><br>    image = image.transpose((2, 0, 1))<br><br>    image_tensor = torch.from_numpy(image)<br><br>    return image_tensor<br><br>def transform(image, split=&#39;TRAIN&#39;):<br>    &quot;&quot;&quot;<br>    Apply the transformations above.<br>    :param image: image, a PIL Image<br>    :param split: one of &#39;TRAIN&#39; or &#39;TEST&#39;, since different sets of transformations are applied<br>    :return: transformed PIL image<br>    &quot;&quot;&quot;<br>    assert split in {&#39;TRAIN&#39;, &#39;TEST&#39;}<br><br>    # Mean and standard deviation of ImageNet data that the base VGG from torchvision was trained on<br>    mean = [0.485, 0.456, 0.406]<br>    std = [0.229, 0.224, 0.225]<br><br>    new_image = image<br><br>    # Skip the following operations for evaluation/testing<br>    if split == &#39;TRAIN&#39;:<br>        # A series of photometric distortions in random order, each with 50% chance of occurrence, as in Caffe repo<br>        new_image = photometric_distort(new_image)<br><br>        # Flip image with a 50% chance<br>        if random.random() &lt; 0.5:<br>            new_image = flip(new_image)<br><br>        # resized image with a 50% chance with given aspected ratio<br>        if random.random() &lt; 0.5:<br>            T_RandomResizedCrop = transforms.RandomResizedCrop(32, scale=(0.08, 1.0), ratio=(0.75, 1.3333333333333333))<br>            new_image = T_RandomResizedCrop(new_image)<br><br>        T_RandomGrayscale = transforms.RandomGrayscale(p = 0.25)<br>        new_image = T_RandomGrayscale(new_image)<br><br>        # Convert PIL image to Torch tensor using custom Tensor Class<br>        T_ToTensor = ToTensor()<br>        new_image = T_ToTensor(new_image)<br><br>        # Normalize by mean and standard deviation of ImageNet data that base VGG was trained on<br>        new_image = FT.normalize(new_image, mean=mean, std=std)<br><br>        return new_image</pre><p><strong>Custom Batch Display Implementation</strong></p><pre>class DisplayBatchImages:<br>    &quot;&quot;&quot;<br>    Display Batch Images<br>    &quot;&quot;&quot;<br>    def __init__(self, dataset):<br>        self.dataset = dataset<br><br>        self.indices = torch.randperm(len(self.dataset)).tolist()<br><br>        self.train_no = int(len(self.indices) * 0.8)<br>        self.test_no = int(len(self.indices) - self.train_no)<br><br>        self.train_idx = self.indices[:self.train_no]<br>        self.test_idx = self.indices[-self.test_no:]<br><br>        self.dataset_train = torch.utils.data.Subset(self.dataset, self.train_idx)<br>        self.dataset_test = torch.utils.data.Subset(self.dataset, self.test_idx)<br><br>        self.dataloader_train = torch.utils.data.DataLoader(self.dataset_train, batch_size=128,<br>                                                            shuffle=True, num_workers=0)<br>        self.dataloader_test = torch.utils.data.DataLoader(self.dataset_test, batch_size=128,<br>                                                           shuffle=False, num_workers=0)<br><br><br>    def display_train(self):<br>        &quot;&quot;&quot;<br>        :return: void, Display the Batch Images for Train Dataset<br>        &quot;&quot;&quot;<br>        for i_batch, sample_batch in enumerate(self.dataloader_train):<br>            image_batch1 = sample_batch[0]<br>            image_batch2 = sample_batch[1]<br><br>            batch_size = len(image_batch1)<br><br>            I1 = []<br>            I2 = []<br><br>            k_images = 4<br>            <br>            for idx in range(batch_size):<br>              if idx &lt; k_images:<br>                  # Normalized Tensor Image<br>                  image1 = image_batch1[idx]<br>                  image2 = image_batch2[idx]<br><br>                  # Normalized parameters<br>                  mean = [0.485, 0.456, 0.406]<br>                  std = [0.229, 0.224, 0.225]<br>                  <br>                  # Inverse Normalization<br>                  inverse_norm = UnNormalize(mean=mean, std=std)<br>                  image1 = inverse_norm(image1)<br>                  image2 = inverse_norm(image2)<br><br>                  image1 = np.asarray(image1).transpose(1, 2, 0)<br>                  image2 = np.asarray(image2).transpose(1, 2, 0)<br><br>                  image1 = cv2.resize(image1, (64, 64),interpolation = cv2.INTER_LINEAR)<br>                  image2 = cv2.resize(image2, (64, 64),interpolation = cv2.INTER_LINEAR)<br><br>                  I1.append(image1)<br>                  I2.append(image2)<br><br>            img1_concate_Hori = np.concatenate(tuple(I1), axis=1)<br>            img2_concate_Hori = np.concatenate(tuple(I2), axis=1)<br>            cv2_imshow(img1_concate_Hori)<br>            cv2_imshow(img2_concate_Hori)<br><br>            cv2.imwrite(&quot;batch_images/image_set1.jpg&quot;, img1_concate_Hori)<br>            cv2.imwrite(&quot;batch_images/image_set2.jpg&quot;, img2_concate_Hori)<br><br>            break<br><br>display = DisplayBatchImages(dataset)<br>display.display_train()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*H3Bd9DFhzoMR9eXup4YmIw.jpeg" /><figcaption><strong>Output Of DisplayBatchImages function, display the images pair-wise in batches of 128 (4 pairs are show for convenience)</strong></figcaption></figure><p><strong>Encoder Implementation using Pre-Trained ResNet</strong></p><p><strong>Projection Head Implementation</strong></p><p><strong>Contrastive Loss Function Implementation</strong></p><pre>def custom_NtXentLoss(proj_out1,  proj_out2, temperature):<br>  proj_out = torch.cat([proj_out1, proj_out2], dim=0)<br>  n_samples = len(proj_out)<br><br>  mm = torch.mm(proj_out1, proj_out2.t().contiguous())<br>  sim = torch.exp(mm / temperature)<br><br>  mask = ~torch.eye(n_samples).bool()<br>  neg_pos_samples = sim.masked_select(mask).view(n_samples, -1).sum(dim=-1)<br><br>  pos_samples = torch.exp(torch.sum(proj_out1 * proj_out1, dim=-1)/ temperature)<br>  pos_samples = torch.cat([pos_samples, pos_samples], dim=0)  <br><br>  loss = -torch.log(pos_samples/ neg_pos_samples).mean()<br><br>  return loss</pre><p><strong>Training pipeline</strong></p><h3>Conclusion</h3><p>Here I have tried to get deep into the contrastive learning via SimCLR Architecture, described in detail its the behind the scene working and its implementation detail in PyTorch. The entire post is written to keep the learning of the individual seeing this post as simple as possible. Remember the post is not to come up with some optimized solution in term of accuracy but instead should only be used for learning purpose. In case you want me to publish an optimized solution comment in the section and feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page till then peace out✌️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed37aa987b14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Action Items Detection System]]></title>
            <link>https://ddimri.medium.com/action-items-detection-system-971100105d33?source=rss-197857c39d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/971100105d33</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[action-items]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <dc:creator><![CDATA[Divyanshu Dimri]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 22:08:42 GMT</pubDate>
            <atom:updated>2024-01-10T08:43:49.980Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Assumptions</strong></p><ol><li>Data is correctly labeled</li><li>Maximum no. of word length that I have assumed is 200 (reason for this I have already mentioned in the “Problem faced in the Action-item Dataset” section), and</li><li>Meaning conveyed by action-items sentences are correct grammatically(no unknows)</li></ol><p><strong>Problem Statement</strong></p><p>The State of my problem statement is to do the case study on the action-item detection in a statement or conversation given to us.</p><p><strong>Introduction</strong></p><p>Action Item Detection is the problem of detecting or highlighting the action-item in a text. Is one of the major Text Classification problems where we are classifying the text / conversation / sentence / document on the bases of the action-items present in them.</p><p>One of the major applications of this topic is in Email action-item Detection[1], where we are classifying the Email and ranking them on bases of highest probability. Ranking can be done either document or sentence wise. This type of the detection mechanism helps the Email receiver to view the messages that are in high prior to taking the action against, thus helping him reduce the delay time in the message response(especially the messages that are in need of urgency).</p><p>Our aim here in the problem is to perform the sentence level classification. Whenever there is an action-item present in the sentence we classify the sentence in an action-item class else we classify them to a non action-item class. In layman terms if we can identify an responsive statement which requires an action from the user we call such a statement an action-item statement.</p><p>There are many algorithms that have come into the implementation of the text-classification, which we will be implementing for our problem statement and see which one provides us the better result in terms of precision / recall and accuracy.</p><p>We will discuss some of the model implementation and some model theory on why and what bases are we or not considering them over each other. It also depends on the problem-statement that we are currently working on, so the model might result in different outcomes depending upon the problem the user is working on.</p><p>[ Note: From here onwards I will be talking in perspective of the problem statement given, for example <strong>documents</strong> ←→ <strong>sentences</strong> ← → statement will be used interchangeably. ]</p><p><strong><em>Action-items</em></strong></p><p>Lets first discuss what are action-items?</p><p>Action-items are the phrases in your sentence that makes your sentence answerable. So how do we recognize whether the sentence is answerable or not?</p><p>Here are some of my viewpoints that I considered absolutely of utter importance in detecting an action-item statement.</p><ol><li>First thing is the question mark(“?”). If a statement ends with the “?” it means it requires the response independent of whether it is urgent or not.</li><li>The sequence of the word matters. The sequence of how the word appears changes the meaning completely, for example: “you have” and “have you” in a statement changes the meaning completely.</li><li>The other important thing is to detect the urgent phrases in a sentence. How do we identify them?</li></ol><ul><li>To maintain the urgency in the sentence, the order of the word must be consistent, so instead of focusing on the word independently we need to maintain the dependency between them.</li><li>It’s not a word now, it’s words that we focus on.</li></ul><p>4. One other thing that’s of utmost importance is to identify the abbreviation and replace them with its original meaning as they define the action in most of the statements, for example <strong>ASAP (As Soon As Possible)</strong> used in many conversations.</p><p>5. Some example of the action items are as following:</p><ul><li><em>Would like to know</em></li><li><em>Let me know</em></li><li><em>Have you,</em></li><li><em>As soon as possible(asap) , etc</em></li></ul><p><strong>Precision and Recall</strong></p><p>Precision and recall are one of the important model parameters that are helpful in determining the model accuracy and how good the model is. Depending on the problem statement and its usage in different domains help me determine the importance of precision-recall tradeoff, especially <strong>precision</strong>.</p><p>The action-item emphasizes on highlighting the documents that have high response time. So, it is important for the user to see the document with high priority and urgency. Even if there is a list of documents with no urgency among the high ones, the user can ignore them as he is still able to answer most of the important one them. So in order to obtain the model for action-items we needed to decrease the total number of <strong>True Negative(TN)</strong> as much as we could, thus increasing the <strong>Precision</strong>.</p><pre>𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 = 𝑇𝑃/(𝑇𝑃 + 𝑇𝑁)<br>𝑤h𝑒𝑟𝑒 𝑇𝑃(𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒) 𝑎𝑛𝑑 𝑇𝑁(𝑇𝑟𝑢𝑒)</pre><p>How do we maintain this precision-recall tradeoff in python? We use the <strong>confusion_matrix </strong>one of the <strong>sklearn </strong>packages, one of the important NLP parameters.</p><p><strong>Methodology Used</strong></p><p>Here we will go through some of the Machine Learning(ML), Deep Learning(DL), and Natural Language Processing(NLP) concepts and their algorithm working and impact on our problem statement.</p><p><strong>1. Naive Baye Algorithm</strong></p><p>Naive Bayes Algorithm is what the name suggests is Naive in nature. It is based on the Bayes theorem which uses the conditional probability. Naive Bayes classifier assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature.</p><pre>𝑃(𝑐|𝑥) = [𝑃(𝑥|𝑐)𝑃(𝑐)]/𝑃(𝑥)</pre><ul><li>Here P(c|x) is the posterior probability of class (c, target) given predictor (x, attributes).</li><li>P(c) is the prior probability of class.</li><li>P(x|c) is the likelihood which is the probability of the predictor given the class.</li><li>P(x) is the prior probability of the predictor.</li></ul><p>One of the reasons for not using Naive Bayes Classifier for our problem statement is because of the independent nature of the algorithm. Therefore where the order of the word and dependency between them plays an important part, naive bayes surely oppose it.</p><p><strong>2. SVM</strong></p><p><strong>Support Vector Machine(SVM)</strong> is a supervised learning algorithm which can be used for both classification or regression challenges. However, it is mostly used in classification problems.</p><p>In the SVM algorithm, we plot each data item as a point in n-dimensional space (where n is the number of features you have) with the value of each feature being the value of a particular coordinate.</p><p>Then, we perform classification by finding the hyper-plane that differentiates the two classes.</p><p>One of the important characteristics of the SVM is its kernel, which helps them to maintain the high dimensional vector space. The kernel does this with the help of the <strong>dot product</strong> (present in its cost function) which simply converts the product between the two n-dimensional vectors to a <strong>one scalar</strong> value thus reducing the computational cost by far.</p><p>SVM uses the <strong>Lagrange multiplier</strong> to solve for its parameters.</p><p>Since high dimensional features are easily handled by SVM we have used this algorithm in one of many algorithms we have implemented for our action-items detection. Which is basically a classification problem where we are trying to find out the best fitted hyper for our problem statement.</p><p><strong>3. N-gram</strong></p><p>N-gram are the sequence of n words, they show the words are relatable with each other in terms of conditional probability. Ngram consists of bi-gram where bi means 2, unigram, trigram, etc.</p><p>So, it’s a way of looking into the n words around the prob word and thus calculating the probability distribution for all the words in a sequence. Higher the value of N, higher will be the dependency we will consider.</p><p>For example if we are using bi-gram then when we perform some kind of tokenization we will divide the sentences into pairs of words(pair of 2).</p><pre><strong>input</strong>: &quot;My name is Divyanshu Dimri&quot;<br><strong>bi-gram</strong>: [&quot;My name&quot;, &quot;name is&quot;, &quot;is Divyanshu&quot;, &quot;Divyanshu Dimri&quot;]</pre><p>And so the pairing changes as the value of n changes.</p><p><strong>4. TF-IDF</strong></p><p><em>TF-IDF</em> is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics.</p><p>how many times a word appears in a document, and the inverse document frequency of the word across a set of documents.</p><p><strong>5. GloVe</strong></p><p>Glove takes the advantage of the whole dataset using the co-occurrence matrix or the count matrix. That is it increases the frequency of the word in the count matrix depending on the context of its neighbouring word.</p><p>But the problem with the co-occurrence matrix is that with increase in vocabulary the size of the matrix increases, thus the computational cost. So in order to reduce the cost <strong>glove </strong>uses the <strong>word vector</strong> with the co-occurrence matrix thus they were able to capture the <strong>local </strong>and <strong>global </strong>properties of the dataset.</p><p>Glove depends on two things:</p><ul><li>Co-occurrence probability of the work</li><li>Ratio of co-occurrence probability</li></ul><p>This ratio gives us some insight on the correlation of the probe word wk with the word wi and wj􏰀.</p><p>Given a probe word, the ratio can be small, large or equal to 1 depends on their correlations. For example, if the ratio is large, the probe word is related to wi but not wj. This ratio gives us hints on the relations between three different words. Intuitively, this is somewhere between a bi-gram and a 3-gram.</p><p><strong>6. Word2Vec</strong></p><p><em>Word2vec</em> is an algorithm used to produce distributed representations of words, and by that we mean word types; i.e. any given word in a vocabulary, such as get or grab or go has its own word vector, and those vectors are effectively stored in a lookup table or dictionary.</p><p>It make use of the Co-occurrence matrix to determine the relationship between the target and context word</p><p>Gensim is the python based library that we have used for our problem statement to perform word2vec embedding</p><p><strong>7. Logistic Regression</strong></p><p>Logistic regression makes use of the sigmoid function which outputs a probability between 0 and 1. It is a simple classification problem which makes use of the Log loss as its cost function to perform its classification task.</p><p><strong>8. BERT</strong></p><p>This is the transformer neural network architecture. So why not LSTM?.</p><p>LSTM is slow in terms of processing and is not truly bidirectional meaning they still need different steps for computation on either side and then concatenate the result.</p><p>Transformers resolve both of these problems as they learn the context of the words simultaneously and hence are fast too. Transformer consist of 2 key components:</p><p>Consider an example of machine translation unit</p><ul><li><strong>Encoder</strong>: Encoder takes the english word simultaneously and generates the embeddings for every word, these embeddings are the vectors that encapsulate the meaning of the words like similar words that have close numbers in their vector or vice-versa.</li><li><strong>Decoder</strong>: Decoder on the other hand takes these embedding and previously generated words from the decoder units and uses them together to generate a new word.</li></ul><p><strong>So what BERT is?</strong></p><p>It’s a Bidirectional Encoder Representation from Transformers. That is in a transformer if we stack up an encoder unit we give birth to BERT.</p><p>BERT training consist of two parts:</p><ul><li>Pretrain BERT to load the already train weight,</li><li>Then <strong>fine tuning</strong> them to learn the specific task(which in our case we</li></ul><p>have use it for action-item detection)</p><p>For our problem statement we fine tune BERT by extracting the <strong>fully connected layer</strong> which consists of . This is the features and then add some dropout, relu and sigmoid function to perform the classification task.</p><p>BERT can take as input either one or two sentences, and uses the special token [SEP] to differentiate them. The [CLS] token always appears at the start of the text, and is specific to classification tasks.</p><p>For example: [CLS] The man went to the store. [SEP] He bought a gallon of milk</p><p><strong>Problem faced in the Action-item Dataset</strong></p><ol><li>One of the biggest problems that I face is the problem of skewness in the dataset. The dataset given as shown in figure 1.1 is left skewed and one of the main reasons for this is because of the bin shadowing maximum peak.</li><li>The peak has around 4k tokens with the next best being 700 word length.</li><li>My reason for taking an assumption of token length(200) is not only because of this skewness and also because the amount of data entry between (200, 700 ) is only 32 with 4000 exceptions. This 4k long sentence consists of many unknown entries that convey no meaning .</li><li><strong>Whether to include the dataset with or without stopwords?</strong></li></ol><p>a. Dataset with <strong><em>stopwords</em></strong></p><ul><li>The reason for including stopwords is to preserve the action-item meaning within the sentences. As I have mentioned above the different sentences with similar words might represent a completely different meaning especially when we have such a narrow margin in detecting action-item sentences</li></ul><p>b. Dataset without <strong><em>stopwords</em></strong></p><ul><li>For our Action-item detection system it’s simply not feasible.</li></ul><p>Also based on the dataset used, I have tested it on different models. Dataset with <em>stopwords </em>always gives me better accuracy than the one without <em>stopwords</em>.</p><p>5. lemmatization vs stemming?</p><p>The problem I faced here is because of the stemming, just because they come from the same family tree that doesn’t imply they are the same.</p><p><strong><em>Lemmatization</em></strong></p><p>Lemmatization does not change the meaning of the word and always returns the base or dictionary form of a word, which is known as the lemma. Thus lemmatization can be considered good practice especially if you are dealing with the large corpus where similar meaning words can be tagged together.</p><p><strong><em>Stemming</em></strong></p><p>Stemming on the other hand is the root of the word set. It skimm the word to its shortest form possible which in many cases destroys the word meaning completely.</p><p><strong>For example</strong> if you perform the stemming on a <strong>list(“organization”, “organizing”, “organizer”)</strong>, you will see that it will return the word “<strong>organ</strong>”.</p><p><strong>Preprocessing Step</strong></p><p>The preprocessing steps consist of two python module:</p><ul><li>utils module: Consists of all the utilities function required for preprocessing this includes:</li></ul><pre><strong>remove_casing:</strong> to convert all the words in a sentence to lowercase<br><strong>remove_punctuation:</strong> remove any punctuation present except(&quot;?&quot;)<br><strong>lemmatization:</strong> perform lemmatization<br><strong>remove_urls:</strong> remove any &lt;urls&gt; present<br><strong>remove_html:</strong> remove any &lt;html&gt; tags<br><strong>abbreviations:</strong> replace any abbreviation to its complete representation<br><strong>correct_spellings:</strong> spelling checker here correct any spelling mistake<br><strong>tokenization:</strong> performing word level tokenization</pre><ul><li>preprocess_data module: This module uses all the functionality provided by the utils module and thus performs the cleaning of the text.</li></ul><blockquote><em>[Note: After preprocessing the data is stored in the “action-item.csv” file, all the training process will be done on this to get the desire accuracy]</em></blockquote><p><strong>Code Implementation Detail</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvCaVKrQQHq2kGRORrTOqw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6L1yOKDiny1r6Xigffd7Kw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2Wsh-lF_hP_U0BhfPJsng.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBINzvu1NLh98f9a9oBDgA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kz2CBz9PDLcD-aoW_kKuw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YBSd-IdJ0Gbk_EbGmoy-g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDnXTM-QUU6TEAx_4Hl88w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDnXTM-QUU6TEAx_4Hl88w.jpeg" /></figure><p>Feel free to reach out or connect with me via my <a href="https://www.linkedin.com/in/divyanshu-dimri-730446159/"><strong>LinkedIn</strong></a><strong> </strong>page</p><p>[1] Feature Representation for Effective Action-Item Detection by Paul N. Bennett Computer Science Department, and Jaime Carbonell Language Technologies Institute. Carnegie Mellon University Pittsburgh.<em> </em><a href="http://www.cs.cmu.edu/~pbennett/papers/action-item-detection-ws.pdf"><em>http://www.cs.cmu.edu/~pbennett/papers/action-item-detection-ws.pdf</em></a></p><p>[2] AIMU: Actionable Items for Meeting Understanding by Yun-Nung Chen, Dilek Hakkani-Tür(2016). <a href="https://www.csie.ntu.edu.tw/~yvchen/doc/LREC16_AIMU.pd"><em>https://www.csie.ntu.edu.tw/~yvchen/doc/LREC16_AIMU</em></a><em>.pdf</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=971100105d33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>