<?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 Gagan Gupta on Medium]]></title>
        <description><![CDATA[Stories by Gagan Gupta on Medium]]></description>
        <link>https://medium.com/@gagangupta_82781?source=rss-40313f7b41a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jEpLiES50_YeXlCp</url>
            <title>Stories by Gagan Gupta on Medium</title>
            <link>https://medium.com/@gagangupta_82781?source=rss-40313f7b41a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:09:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gagangupta_82781/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[Talk to your text data using T5 Model following RAG]]></title>
            <link>https://medium.com/@gagangupta_82781/talk-to-your-text-data-using-t5-model-following-rag-a2203c6318d5?source=rss-40313f7b41a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2203c6318d5</guid>
            <dc:creator><![CDATA[Gagan Gupta]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 13:36:24 GMT</pubDate>
            <atom:updated>2024-07-16T13:36:24.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is T5 Model?</h3><p>T5 Stands for Text-to-Text-Transfer-Transformer, model is a versatile language model developed by Google Research, designed to perform a wide variety of natural language processing (NLP) tasks using a unified framework.</p><p>Its model architecture is based on the Transformer architecture with an encoder-decoder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_4tvle1URvND58OF.png" /></figure><p>I have covered everything about T5 model in my previous blog, for more details on T5 : <a href="https://medium.com/@gagangupta_82781/understanding-the-t5-model-a-comprehensive-guide-b4d5c02c234b">https://medium.com/@gagangupta_82781/understanding-the-t5-model-a-comprehensive-guide-b4d5c02c234b</a></p><h3>RAG</h3><p>RAG stands for Retrieval Augmented Generation. It is an evolution in Gen AI methodology which enhances the capability of Gen AI in generating the optimized output with targeted information. And that targeted information can be more up-to-date than LLM as well as specific to a particular domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*b0YMO-D-IvVX7Db8.png" /></figure><p>I have covered everything about RAG architecture in my previous blog, for more details on RAG : <a href="https://medium.com/@gagangupta_82781/rag-retrieval-augmented-generation-5b332a4b7b7f">https://medium.com/@gagangupta_82781/rag-retrieval-augmented-generation-5b332a4b7b7f</a></p><h3>T5 implementaion using RAG architecture for Question &amp; Answering from Text Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gg6VXxfftzLWCEhIUYKYVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZpqY1M6XSZVGwygHKXDOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NVcpdYwgDeE47HIJ8VOuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNBF90UX4NLLLXNgWe3Khg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Vz0yH0uoJVTi2EvMg7qBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtMiWwqzboX3R6WzhxcSwg.png" /></figure><p>for code please ref: <a href="https://github.com/Gagan824/GenAI-Projects/blob/master/QnA%20System/QnA%20System%20using%20T5.ipynb">https://github.com/Gagan824/GenAI-Projects/blob/master/QnA%20System/QnA%20System%20using%20T5.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2203c6318d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the T5 Model: A Comprehensive Guide]]></title>
            <link>https://medium.com/@gagangupta_82781/understanding-the-t5-model-a-comprehensive-guide-b4d5c02c234b?source=rss-40313f7b41a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4d5c02c234b</guid>
            <dc:creator><![CDATA[Gagan Gupta]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 09:09:57 GMT</pubDate>
            <atom:updated>2024-07-16T12:09:27.369Z</atom:updated>
            <content:encoded><![CDATA[<p>The field of Natural Language Processing (NLP) has seen tremendous advancements over the years, and one of the significant milestones is the development of the T5 model by Google Research. T5, which stands for Text-To-Text Transfer Transformer, is a versatile and powerful model that has revolutionized how we approach various NLP tasks. In this blog, we’ll delve into what the T5 model is, its architecture, applications, how it differs from other models, and its impact on the NLP landscape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klpuSi3zqB1LoTLIR1nL-A.png" /><figcaption>Figure 1. T5 Models</figcaption></figure><h3>What is the T5 Model?</h3><p>T5 is an innovative NLP model introduced in the paper “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Colin Raffel et al. The primary idea behind T5 is to convert all NLP tasks into a text-to-text format, where both the input and output are text strings. This unified approach simplifies the framework for tackling different NLP tasks such as translation, summarization, and question-answering.</p><h3>Key Features of the T5 Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*kD5H8pRe-9kJZLL_L29kLA.png" /><figcaption>Figure 2. text-to-text framework</figcaption></figure><ol><li><strong>Text-to-Text Framework</strong>: By framing every task as a text-to-text problem, T5 allows for a more uniform and flexible approach to solving various NLP challenges. This approach simplifies the model architecture and makes it easier to transfer learning across different tasks.</li><li><strong>Transfer Learning</strong>: T5 leverages transfer learning, where the model is pre-trained on a massive corpus of data and then fine-tuned on specific tasks, leading to improved performance and efficiency. This approach has proven to be highly effective in improving the accuracy of NLP models.</li><li><strong>Scalability</strong>: T5 can be scaled up with larger models like T5–11B, which consists of 11 billion parameters, demonstrating the ability to handle complex NLP tasks with high accuracy. The scalability of T5 allows it to be adapted to different computational resources and task requirements.</li></ol><h3>Assumptions for T5 data</h3><ul><li>We only retained lines that ended in a terminal punctuation mark (i.e. a period, exclamation mark, question mark, or end quotation mark).</li><li>We discarded any page with fewer than 3 sentences and only retained lines that contained at least 5 words.</li><li>We removed any page that contained any word on the “List of Dirty, Naughty, Obscene or Otherwise Bad Words”.</li><li>Many of the scraped pages contained warnings stating that Javascript should be enabled so we removed any line with the word Javascript.</li><li>Some pages had placeholder “lorem ipsum” text; we removed any page where the phrase “lorem ipsum” appeared.</li><li>Some pages inadvertently contained code. Since the curly bracket “{” appears in many programming languages (such as Javascript, widely used on the web) but not in natural text, we removed any pages that contained a curly bracket.</li><li>Since some of the scraped pages were sourced from Wikipedia and had citation markers (e.g. [1], [citation needed], etc.), we removed any such markers.</li><li>Many pages had boilerplate policy notices, so we removed any lines containing the strings “terms of use”, “privacy policy”, “cookie policy”, “uses cookies”, “use of cookies”, or “use cookies”.</li><li>To deduplicate the data set, we discarded all but one of any three-sentence span occurring more than once in the data set.</li></ul><h3>Architecture of the T5 Model</h3><p>The architecture of T5 is based on the Transformer model, which consists of an encoder and a decoder. The encoder processes the input text, while the decoder generates the output text. Here are the main components of the T5 architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vK9Fa0mcfz_Ed_XHHHMcIg.png" /><figcaption>Figure 3. transformer</figcaption></figure><h4><strong>Input Representation</strong></h4><ol><li><strong>Tokenization</strong>:</li></ol><ul><li>Uses SentencePiece, which creates a vocabulary of subword units. The input text is split into these subword tokens.</li><li>For example, translate English to French: How are you? might be tokenized into: [ &#39;translate&#39;, &#39;▁English&#39;, &#39;▁to&#39;, &#39;▁French&#39;, &#39;:&#39;, &#39;▁How&#39;, &#39;▁are&#39;, &#39;▁you&#39;, &#39;?&#39; ]</li></ul><p>2.<strong> Conversion to Token IDs</strong>:</p><ul><li>Each token is mapped to a unique integer ID from the vocabulary.</li></ul><p>3. <strong>Embedding</strong>:</p><ul><li>Token IDs are converted into dense vectors (embeddings).</li><li>Positional embeddings are added to these token embeddings to encode the position of each token in the sequence.</li></ul><h4>Encoder</h4><p>The encoder is composed of multiple layers (e.g., 12 layers in T5-Base). Each layer consists of:</p><ol><li><strong>Self-Attention Mechanism</strong>:</li></ol><ul><li>Allows each token to attend to all other tokens in the input sequence.</li><li>Multi-head attention is used, where multiple attention heads capture different aspects of the relationships between tokens.</li></ul><p>2.<strong> Feed-Forward Neural Network (FFN)</strong>:</p><ul><li>A two-layer fully connected network with a ReLU activation in between.</li><li>Typically includes dropout for regularization.</li></ul><p>3.<strong> Layer Normalization</strong>:</p><ul><li>Applied before each sub-layer to stabilize training (pre-norm).</li></ul><p>4. <strong>Residual Connections</strong>:</p><ul><li>Skip connections around each sub-layer ensures effective gradient flow during training.</li></ul><h4>Decoder</h4><p>The decoder also consists of multiple layers (e.g., 12 layers in T5-Base). Each layer includes:</p><ol><li><strong>Self-Attention Mechanism</strong>:</li></ol><ul><li>Similar to the encoder but with masking to prevent positions from attending to future positions in the output sequence.</li></ul><p>2. <strong>Cross-Attention Mechanism</strong>:</p><ul><li>Allows each position in the decoder to attend to all positions in the encoder’s output.</li></ul><p>3. <strong>Feed-Forward Neural Network (FFN)</strong>:</p><ul><li>Similar to the encoder.</li></ul><p>4. <strong>Layer Normalization</strong>:</p><ul><li>Applied before each sub-layer (pre-norm).</li></ul><p>5. <strong>Residual Connections</strong>:</p><ul><li>Skip connections around each sub-layer.</li></ul><h3>Architectural variants</h3><h4>Model Structures</h4><p>A major distinguishing factor for different architectures is the “mask” used by different attention mechanisms in the model. Recall that the self-attention operation in a Transformer takes a sequence as input and outputs a new sequence of the same length. Each entry of the output sequence is produced by computing a weighted average of entries of the input sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*xS_rtmdNelOo6GokITv4EQ.png" /><figcaption>Figure 4. Attention mask patterns</figcaption></figure><p>Matrices representing different attention mask patterns. The input and output of the self-attention mechanism are denoted x and y respectively. A dark cell at row i and column j indicates that the self-attention mechanism is allowed to attend to input element j at output timestep i. A light cell indicates that the self-attention mechanism is not allowed to attend to the corresponding i and j combination. Left: A fully-visible mask allows the self-attention mechanism to attend to the full input at every output timestep. Middle: A causal mask prevents the ith output element from depending on any input elements from “the future”. Right: Causal masking with a prefix allows the self-attention mechanism to use fully-visible masking on a portion of the input sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*Bpbn-ovy6n1Apj6RbA7ilQ.png" /><figcaption>Figure 5. architecture variants</figcaption></figure><p>Schematics of the Transformer architecture variants we consider. In this diagram, blocks represent elements of a sequence and lines represent attention visibility. Different colored groups of blocks indicate different Transformer layer stacks. Dark grey lines correspond to fully-visible masking and light grey lines correspond to causal masking. We use “.” to denote a special end-of-sequence token that represents the end of a prediction. The input and output sequences are represented as x and y respectively. Left: A standard encoder-decoder architecture uses fully-visible masking in the encoder and the encoder-decoder attention, with causal masking in the decoder. Middle: A language model consists of a single Transformer layer stack and is fed the concatenation of the input and target, using a causal mask throughout. Right: Adding a prefix to a language model corresponds to allowing fully-visible masking over the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*EDb5UrzfXjLn7jtBKWA2tw.png" /></figure><h3>Training Objectives</h3><ol><li><strong>Span Corruption for Pre-training</strong>: Random spans of tokens are masked and the model is trained to predict these spans, similar to BERT’s masked language model but with spans instead of individual tokens.</li><li><strong>Task-Specific Fine-Tuning</strong>: After pre-training, T5 is fine-tuned on specific tasks (e.g., translation, summarization) by training on labeled datasets for those tasks.</li></ol><h3>All T5 Models:</h3><ul><li><strong>T5-Small: </strong>Parameters: ~60 million</li><li><strong>T5-Base: </strong>Parameters: ~220 million</li><li><strong>T5-Large: </strong>Parameters: ~770 million</li><li><strong>T5–3B: </strong>Parameters: ~3 billion</li><li><strong>T5–11B: </strong>Parameters: ~11 billion</li></ul><h3>How T5 Differs from Other Models</h3><ol><li><strong>Unified Approach</strong>: Unlike models designed for specific tasks, T5’s text-to-text framework allows it to be applied to a variety of tasks without needing significant modifications. This unified approach simplifies the model architecture and training process.</li><li><strong>Pre-training on Colossal Data</strong>: T5 is pre-trained on the C4 dataset (Colossal Clean Crawled Corpus), which is one of the largest and cleanest datasets available, enabling it to generalize well across tasks. The pre-training process involves training the model on a diverse set of text data, allowing it to learn a wide range of language patterns and structures.</li><li><strong>Performance</strong>: In various benchmarks, T5 has outperformed many other models, demonstrating superior performance in tasks like GLUE, SuperGLUE, and others. The performance of T5 can be attributed to its large-scale pre-training, unified architecture, and effective transfer learning.</li></ol><h3>Applications of the T5 Model</h3><p>T5 has been applied to a wide range of NLP tasks, showcasing its versatility and effectiveness:</p><ol><li><strong>Text Summarization</strong>: T5 can generate concise summaries of long documents, capturing the essential information accurately. This is particularly useful for creating summaries of news articles, research papers, and other lengthy documents.</li><li><strong>Machine Translation</strong>: T5 can translate text from one language to another with high fidelity. This makes it a valuable tool for multilingual applications and cross-lingual communication.</li><li><strong>Question Answering</strong>: T5 can understand and answer questions based on given context or documents. This is useful for building question-answering systems, virtual assistants, and chatbot.</li><li><strong>Sentiment Analysis</strong>: T5 can determine the sentiment of a given text, whether positive, negative, or neutral. This is valuable for analyzing customer reviews, social media posts, and other forms of text data.</li><li><strong>Text Classification</strong>: T5 can categorize text into predefined classes, useful in tasks like spam detection, topic classification, and document categorization.</li></ol><h3>Challenges and Limitations</h3><p>While T5 has achieved remarkable success, it is not without challenges and limitations:</p><ol><li><strong>Computational Resources</strong>: Training and fine-tuning large models like T5–11B require substantial computational resources, including high-performance GPUs or TPUs. This can be a barrier for researchers and practitioners with limited access to such resources.</li><li><strong>Data Requirements</strong>: The performance of T5 depends heavily on the quality and quantity of the training data. For some tasks, acquiring large, high-quality datasets can be challenging.</li><li><strong>Model Size</strong>: Large models like T5–11B have a high number of parameters, which can lead to increased memory and storage requirements. This can be a limitation for deployment in resource-constrained environments.</li></ol><h3>Conclusion</h3><p>The T5 model represents a significant leap forward in the field of NLP, thanks to its unified text-to-text approach, scalability, and versatility. Whether you’re working on summarization, translation, or any other NLP task, T5 offers a robust solution that can handle the complexity and nuances of human language.</p><p>As the field of NLP continues to evolve, the T5 model will likely remain a cornerstone for researchers and practitioners looking to push the boundaries of what’s possible with language models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4d5c02c234b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification Using LSTM]]></title>
            <link>https://medium.com/@gagangupta_82781/text-classification-using-lstm-7e4cc30f6232?source=rss-40313f7b41a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4cc30f6232</guid>
            <dc:creator><![CDATA[Gagan Gupta]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 09:35:42 GMT</pubDate>
            <atom:updated>2024-06-30T09:35:42.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Here in this blog we will look at LSTM architecture and see how we can implement LSTM for text classification. We have some ticket’s data using which we will predict the team.</p><h3>LSTM:</h3><p>LSTM (Long Short-Term Memory) is a recurrent neural network (RNN) architecture designed to model sequential data and long-term dependencies. Unlike standard RNNs, LSTMs can learn long-range temporal dependencies, thanks to their unique architecture that includes a memory cell and three gating mechanisms: forget, input, and output gates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmcUultdCEOoTVvwG0DTlw.png" /></figure><h3>Key Components:</h3><p>In above figure we can see LSTM uses three gates:</p><p>1. Forget Gate: Decides which information from the previous cell state to forget. It outputs a number between 0 and 1 for each number in the cell state.</p><p>2. Input Gate: Determines which new information to store in the cell state. It has two parts:</p><p>2.1. Input Gate Layer: Decides which values to update</p><p>2.2. Candidate Layer: Creates a vector of new candidate values to be added to the state</p><p>3. Output Gate: Determines the output based on the cell state. It controls what parts of the cell state make it to the output.</p><p>Cell State Update: Combines the previous cell state, the forget gate, and the input gate to update the current cell state.</p><h3>Why Use LSTM?</h3><p>LSTMs are particularly effective for tasks where context or historical information is crucial, such as:</p><ul><li>Time series prediction</li><li>Natural language processing (NLP)</li><li>Speech recognition</li><li>Anomaly detection in sensor data</li></ul><h3>Now lets have a look on its implementation:</h3><p>Importing all important libraries</p><pre>import json<br>import numpy as np<br>import pandas as pd<br><br>from sklearn.preprocessing import OneHotEncoder as OHE<br>from sklearn.metrics import classification_report<br><br>import nltk<br>from nltk import word_tokenize,sent_tokenize<br>from nltk.corpus import stopwords<br>from string import punctuation<br>from nltk.stem import PorterStemmer<br><br>from tensorflow.keras.preprocessing.text import Tokenizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br>from tensorflow.keras.layers import Dense, LSTM, BatchNormalization, Dropout, Input<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.losses import CategoricalCrossentropy as CC<br>from tensorflow.keras.activations import relu, softmax<br>from tensorflow.keras.initializers import he_uniform, glorot_uniform<br>from tensorflow.keras.metrics import AUC<br>from tensorflow.keras import Model<br>from tensorflow.keras.regularizers import l2<br>import tensorflow as tf</pre><p>reading data from file.</p><pre>ticket_data = pd.read_csv(&#39;data/ticket_data.csv&#39;)</pre><p>below we can see the available fields in data and their corresponding values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*MgW88aWN4xYtigX5yCMMlw.png" /></figure><p>Here our problem is to identify the ‘Team’ for the given Ticket details that is Title, Body, Category and Sub-category.</p><p>Once we are done with the data reading and data overview, we can move towards data preprocessing:</p><pre>def data_preprocess(data):<br>    nltk.download(&#39;punkt&#39;)<br>    nltk.download(&#39;stopwords&#39;)<br>    nltk.download(&#39;PorterStemmer&#39;)<br>    <br>    ## stop words list<br>    stop = stopwords.words(&quot;english&quot;)    <br>    stop_punc = list(set(punctuation))+stop<br>    <br>    ## Concatinating all text into one<br>    data[&#39;new&#39;] = data[&#39;Title&#39;] +&quot; &quot;+ data[&#39;Body&#39;]+ &quot; &quot;+data[&#39;Category&#39;]+&quot; &quot;+data[&#39;SubCategory&#39;]<br>    <br>    ## dropping off all un necessary columns<br>#     data = data.drop([&#39;Title&#39;, &#39;Body&#39;, &#39;Category&#39;, &#39;SubCategory&#39;,&#39;Opened At&#39;], axis = 1)<br>    <br>    ## lower casing the text<br>    data[&quot;lower_text&quot;] = data[&#39;new&#39;].map(lambda x:x.lower())<br>    <br>    def remove_stop(strings, stop_list):<br>        classed = [s for s in strings if s not in stop_list]<br>        return classed<br>    <br>    ## tokenizing the text<br>    data[&quot;tokenized&quot;] = data[&#39;lower_text&#39;].map(word_tokenize)<br>    <br>    ## removing stopwords based on stopword list<br>    data[&quot;selected&quot;] = data[&#39;tokenized&#39;].map(lambda df:remove_stop(df, stop_punc))<br>    <br>    def normalize(text):<br>        return &quot; &quot;.join(text)<br>    <br>    ## Stemmer object<br>    stemmer = PorterStemmer()<br><br>    ## stemming and normalizing the text<br>    data[&quot;stemmed&quot;] = data[&#39;selected&#39;].map(lambda xs:[stemmer.stem(x) for x in xs])<br>    data[&quot;normalized&quot;] = data[&#39;stemmed&#39;].apply(normalize)<br>    <br>    return data<br><br>def embeddings(data, tokenizer = None):<br>    ## Tokenizer object for text to vector conversion<br>    if tokenizer is None:<br>        tokenizer = Tokenizer(num_words=1000)<br>        tokenizer.fit_on_texts(data[&#39;normalized&#39;])<br>        tokenized_train = tokenizer.texts_to_sequences(data[&#39;normalized&#39;])<br>    else:<br>    ## text to vector/sequence conversion<br>        tokenized_train = tokenizer.texts_to_sequences(data[&#39;normalized&#39;])<br><br>    ## adding padding if required<br>    train_padded = pad_sequences(tokenized_train, maxlen=15, padding=&quot;pre&quot;)<br>    <br>    return tokenizer, train_padded</pre><p>above we have two functions:</p><ol><li>data_preprocess(): which is doing text cleaning and text preprocessing like removing stop words, punctuations and other special symbols which are not needed and converting each word to its root word using Stemming process.</li><li>embeddings():this function is creating numerical vector for the text data so we can build model on top of this data.</li></ol><pre>ticket_data = data_preprocess(ticket_data)<br>tokenizer, train_padded = embeddings(ticket_data)</pre><p>Now we have padded data and a tokenizer, we can using this tokenizer in future to get the embeddings of future data.</p><pre>def transform_x(data, tokenizer):<br>    output_shape = [data.shape[0],<br>                    data.shape[1],<br>                    tokenizer.word_index.keys().__len__()]<br>    results = np.zeros(output_shape)<br><br>    for i in range(data.shape[0]):<br>        for ii in range(data.shape[1]):<br>            results[i, ii, data[i, ii]-1] = 1<br>    return results</pre><p>Now, what is this function doing?</p><p>So the answer is, this function is transforming the input in more simplified form to help the model in training.</p><pre>xtr_transformed = transform_x(train_padded, tokenizer)<br><br>## doing one hot encoding on output variable<br>y_encoder = OHE().fit(np.array(ticket_data.Team).reshape(-1, 1))<br>ytr_encoded = y_encoder.transform(np.array(ticket_data.Team).reshape(-1, 1)).toarray()</pre><p>in above code block we have trasformed input and one hot encoded target variable.</p><pre>class LSTMModel(object):<br><br>    def build_model(self, input_dim, output_shape, steps, dropout_rate, kernel_regularizer, bias_regularizer):<br>        <br>        ## ADDING INPUT LAYER<br>        input_layer = Input(shape=(steps, input_dim))<br>        # ADDING LSTM LAYER<br>        lstm = LSTM(units=steps)(input_layer)<br>        <br>        # ADDING DENSE LAYER<br>        dense_1 = Dense(output_shape, kernel_initializer=he_uniform(),<br>                        bias_initializer=&quot;zeros&quot;,<br>                        kernel_regularizer=l2(l=kernel_regularizer),<br>                        bias_regularizer=l2(l=bias_regularizer))(lstm)<br>        <br>        # DOING NORMALIZATION<br>        x = BatchNormalization()(dense_1)<br>        x = relu(x)<br>        <br>        # ADDING DROPOUT LAYER TO AVOID OVERFITTING<br>        x = Dropout(rate=dropout_rate)(x)<br>        <br>        # ADDING DENSE LAYER<br>        o = Dense(output_shape, kernel_initializer=glorot_uniform(),<br>                  bias_initializer=&quot;zeros&quot;,<br>                  kernel_regularizer=l2(l=kernel_regularizer),<br>                  bias_regularizer=l2(l=bias_regularizer))(dense_1)<br>        o = BatchNormalization()(o)<br>        <br>        ## ADDING OUTPUT LAYER<br>        output = softmax(o, axis=1)<br>        <br>        # DEFINING LOSS<br>        loss = CC()<br>        <br>        # DEFINING METRIC<br>        metrics = AUC()<br>        <br>        # DEFINING OPTIMIZER<br>        optimizer = Adam()<br>        <br>        # ASSEMBLING INTO A MODEL<br>        self.model = Model(inputs=[input_layer], outputs=[output])<br>        <br>        # COMPILING A MODEL <br>        self.model.compile(optimizer=optimizer, loss=loss, metrics=[metrics])<br><br>    def train(self, x, y, validation_split, epochs):<br>        ## MODEL TRAINING<br>        self.model.fit(x, y, batch_size=8, validation_split=validation_split, epochs=epochs)<br>        self.model.save(f&quot;ticket_model.h5&quot;)<br><br>    def predict(self, x):<br>        return self.model.predict(x)</pre><p>this is where we are creating ANN model using LSTM.</p><p>Once we are done with model building and data preprocessing then why to delay in its training!!!</p><p>Lets begin with this model training.</p><pre>steps = xtr_transformed.shape[1]<br>dim = xtr_transformed.shape[2]<br>output_shape = ytr_encoded.shape[1]<br><br>model = LSTMModel()<br>model.build_model(input_dim=dim,<br>                  output_shape=output_shape,<br>                  steps=steps,<br>                  dropout_rate=0.5,<br>                  bias_regularizer=0.3,<br>                  kernel_regularizer=0.3)</pre><pre>model.train(xtr_transformed, ytr_encoded, 0.1, 30)</pre><p>So now we are ready with our model, but not sure how well it is fitted or how accurate it is?</p><p>Wanna see its accuracy, so lets see!!</p><pre>test_data = pd.read_csv(&#39;data/test.csv&#39;).head(100)<br>test_data = data_preprocess(test_data)<br>tokenizer, test_padded = embeddings(test_data, tokenizer)<br>test_transformed = transform_x(test_padded, tokenizer)<br><br>preds = []<br><br>for x in test_transformed:<br>#     print(.shape)<br>    preds.append(y_encoder.inverse_transform(model.predict(np.array([x])))[0][0])<br><br>from sklearn.metrics import classification_report<br>print(classification_report(test_data[&#39;Team&#39;], preds))</pre><pre>precision    recall  f1-score   support<br><br>        DB Team       1.00      1.00      1.00        20<br>  Hardware Team       1.00      1.00      1.00        18<br>Networking Team       1.00      1.00      1.00        15<br>  Software Team       1.00      1.00      1.00        22<br>   Support Team       1.00      1.00      1.00        25<br><br>       accuracy                           1.00       100<br>      macro avg       1.00      1.00      1.00       100<br>   weighted avg       1.00      1.00      1.00       100</pre><p>We can see classification report that, trained model is able to identify all teams correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4cc30f6232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some basics from “Prompt Engineering”]]></title>
            <link>https://medium.com/@gagangupta_82781/some-basics-from-prompt-engineering-a5e679c1326f?source=rss-40313f7b41a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e679c1326f</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Gagan Gupta]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 08:21:51 GMT</pubDate>
            <atom:updated>2024-04-30T10:04:43.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is prompt engineering?</h3><p>It is a process of designing and optimizing text inputs(prompts) to deliver quality and consistent responses.</p><blockquote>Prompt is any form of text, question, information, or coding that communicates to AI what response you’re looking for.</blockquote><h3>Why prompt engineering?</h3><p>For these reasons we require prompt to be engineered:</p><ol><li>Model responses are stochastic.</li><li>Models can fabricate response.</li><li>Models capabilities will vary.</li></ol><h3>Types of prompts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*eLxOPCmV0zEJaLbAKfkPFg.png" /></figure><h3><strong>Prompt templates</strong></h3><p>It is a predefined recipe of a prompt that can be stored and reused as needed to drive more consistent user experience at scale.</p><blockquote>Limitations of <strong>simple</strong> <strong>prompt</strong> <strong>engineering</strong>:<br>You may or may not get the desired output.</blockquote><h3><strong>Techniques of prompt engineering</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*n-bg2sIsH47orgqBpT8utQ.png" /></figure><h3>How to vary our output ?</h3><p>LLMs are non deterministic by nature, meaning that you will get different results each time you run the same prompt.</p><h4>So is this a problem?</h4><p>It depends on what you are trying to do.</p><ul><li>If you want a specific response then its not a problem.</li><li>If you are okay with the response then its not a problem.</li></ul><h4>Now How?</h4><ul><li>If we want to limit the output to be more predictable, that is more deterministic, we can do it using the temperature.</li><li>Temperature is a value between 0 and 1, where 0 is the most deterministic &amp; 1 is the most varied.</li></ul><blockquote><strong>. Note: </strong>Default value of temperature is 0.7</blockquote><h4>Good Practices</h4><p>There are many practices you can apply to try to get what you want, you will find your own style as you use prompting more and more.</p><p><strong>Some Practices:</strong></p><ul><li>Specify context</li><li>specify both what and how</li><li>use templates</li><li>spell correctly</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e679c1326f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG(Retrieval Augmented Generation)]]></title>
            <link>https://medium.com/@gagangupta_82781/rag-retrieval-augmented-generation-5b332a4b7b7f?source=rss-40313f7b41a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b332a4b7b7f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gagan Gupta]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 12:49:32 GMT</pubDate>
            <atom:updated>2024-04-02T12:53:21.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is RAG?</h3><p>RAG stands for Retrieval Augmented Generation. It is an evolution in Gen AI methodology which enhances the capability of Gen AI in generating the optimized output with targeted information. And that targeted information can be more up-to-date than LLM as well as specific to a particular domain.</p><p>In RAG:</p><p><strong>R → </strong>Lookup the external data sources (Web Pages, APIs &amp; Dynamic DBs, Databases etc..) to retrieve the relevant information.</p><p><strong>A → </strong>Add the retrieved information to the user prompt.</p><p><strong>G → </strong>Use LLM to generate response to user prompt with the context.</p><h4>How does RAG overcome the limitations of LLMs?</h4><p>There are two major limitations of Large Language Models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*oThzKHxxJNP_7ETMVfMulg.png" /></figure><h4>How does RAG work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*dn5j67NMs28M_0GdGJquqw.png" /></figure><h4><strong>RAG System Working Mechanism</strong></h4><p>From above image we can easily understand the working mechanism of RAG that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9PDfLjs9dLMoch2o1nVGQ.png" /></figure><h4>RAG comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*AQSTIAcVX3hDPXKDg-Pu5g.png" /></figure><p>This radar chart is a graphical representation of multidimensional data in which each method is evaluated against several criteria, shown as axes on the chart. The criteria include</p><ul><li>Cost,</li><li>Complexity,</li><li>Domain-specific knowledge,</li><li>Actuality,</li><li>Explainability and</li><li>Avoidance of hallucinations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*GeIyJCdcYxzVRqfNGS-b4w.png" /></figure><h4>RAG Use-cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*fheERE-FnVgQTZJeSRUqmg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b332a4b7b7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>