<?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 Veer Khot on Medium]]></title>
        <description><![CDATA[Stories by Veer Khot on Medium]]></description>
        <link>https://medium.com/@khotveer1?source=rss-9858f58e8e8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kxd0mYXCf2oGZbaTZV4Ryw.jpeg</url>
            <title>Stories by Veer Khot on Medium</title>
            <link>https://medium.com/@khotveer1?source=rss-9858f58e8e8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:23:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khotveer1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering LoRA: Fine-Tuning GPT-2 for Domain-Specific Texts]]></title>
            <link>https://medium.com/data-science-collective/mastering-lora-fine-tuning-gpt-2-for-domain-specific-texts-61847bef4732?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/61847bef4732</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[lora]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Thu, 29 May 2025 18:00:23 GMT</pubDate>
            <atom:updated>2025-06-05T00:32:35.750Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step-by-step tutorial to unlock the power of PEFT LoRA on GPT-2 models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhIybzw0D4TbPoe9qqT6WQ.png" /></figure><p>In the <a href="https://medium.com/data-science-collective/llm-fundamentals-training-gpt-from-scratch-with-pytorch-ad1425a0ae05">previous article</a> , we walked through the process of <strong>training a GPT-like model from scratch</strong> using a custom dataset — <a href="https://github.com/khotveer/gpt2-lora-finetuning-shakespeare/tree/main/data">Shakespearean </a>dialogues. We covered everything from tokenization, dataset preparation, and model architecture, to training a Transformer from the ground up using PyTorch.</p><p>While this was a powerful learning experience, it’s clear that <a href="https://medium.com/data-science-collective/llm-fundamentals-training-gpt-from-scratch-with-pytorch-ad1425a0ae05"><strong>training large language models from scratch</strong></a> can be computationally expensive and resource-intensive, especially for those without access to <strong>high-end GPUs or large datasets.</strong></p><p>That’s where <strong>PEFT (Parameter-Efficient Fine-Tuning)</strong> methods, and more specifically <strong>LoRA (Low-Rank Adaptation)</strong>, come into play.</p><p>Let’s dive in.</p><h3>Introduction to PEFT and LoRA</h3><h4>What is PEFT?</h4><p><strong>Parameter-Efficient Fine-Tuning (PEFT)</strong> is a set of techniques designed to fine-tune large pre-trained language models without modifying all of their parameters. Instead of retraining the entire model — which can be expensive in terms of computation and storage — PEFT approaches allow you to <strong>freeze most of the model</strong> and update only a small subset of new, added parameters.</p><p>The key idea? <strong>Leverage the power of large pre-trained models</strong> without paying the full cost of retraining them from scratch.</p><p>Some common PEFT methods include:</p><ul><li><strong>Adapters</strong></li><li><strong>Prefix Tuning</strong></li><li><strong>Prompt Tuning</strong></li><li><strong>LoRA (Low-Rank Adaptation)</strong></li></ul><p>Among these, <strong>LoRA</strong> has become one of the most popular due to its simplicity, efficiency, and strong performance.</p><h4>What is LoRA?</h4><p><strong>LoRA (Low-Rank Adaptation)</strong>, introduced in the paper <em>“</em><a href="https://arxiv.org/abs/2106.09685"><em>LoRA: Low-Rank Adaptation of Large Language Models</em></a><em>”</em>, is a technique where <strong>low-rank matrices are inserted into transformer layers</strong> (typically attention or MLP blocks). These low-rank matrices are the only ones updated during training and all the original model weights remain frozen.</p><p>This approach significantly reduces:</p><ul><li>The number of trainable parameters</li><li>Training time and cost</li><li>Risk of overfitting (especially with small datasets)</li></ul><h4>Here’s a simplified intuition:</h4><p>Instead of modifying the full weight matrix W (say, a 768×768 attention weight), LoRA represents the update as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*965EaxTzBx94RZlFzSvCjw.png" /><figcaption>LORA equation</figcaption></figure><p>Where:</p><ul><li>A is a <strong>low-rank</strong> matrix of size (768 × r)</li><li>B is another <strong>low-rank</strong> matrix of size (r × 768)</li><li>r is a small rank value (e.g., 4 or 8)</li></ul><p>You only train A and B, drastically reducing the number of parameters and saving compute.</p><h4>Example</h4><p>Let’s say we have a weight matrix <strong>W</strong> in a neural network:</p><h4>Step 1: Full Weight Matrix (8x8)</h4><p>This is our <strong>original weight matrix</strong> (frozen during LoRA):</p><pre>W = [[ 1,  2,  3,  4,  5,  6,  7,  8],<br>  [ 9, 10, 11, 12, 13, 14, 15, 16],<br>  [17, 18, 19, 20, 21, 22, 23, 24],<br>  [25, 26, 27, 28, 29, 30, 31, 32],<br>  [33, 34, 35, 36, 37, 38, 39, 40],<br>  [41, 42, 43, 44, 45, 46, 47, 48],<br>  [49, 50, 51, 52, 53, 54, 55, 56],<br>  [57, 58, 59, 60, 61, 62, 63, 64]]</pre><h4>Step 2: LoRA Low-Rank Matrices (Rank = 2)</h4><p>Now we introduce two <strong>trainable matrices A and B</strong>:</p><p><strong>A ∈ ℝ²ˣ⁸ (2 rows, 8 columns)</strong></p><pre>A = [[ 1,  0,  1,  0,  1,  0,  1,  0],<br>    [ 0,  1,  0,  1,  0,  1,  0,  1]]</pre><p><strong>B ∈ ℝ⁸ˣ² (8 rows, 2 columns)</strong></p><pre>B = [[ 1,  0],<br>     [ 0,  1],<br>     [ 1,  0],<br>     [ 0,  1],<br>     [ 1,  0],<br>     [ 0,  1],<br>     [ 1,  0],<br>     [ 0,  1]]</pre><p>These total <strong>32 parameters (16 in A + 16 in B)</strong> — half of full fine-tuning.</p><h4>Step 3: Compute LoRA Update — ΔW = B × A (Matrix Multiplication)</h4><p>calculate ΔW = B × A (shape: 8×8):</p><p>Each row in ΔW is formed by multiplying one row of <strong>B</strong> (1×2) with <strong>A</strong> (2×8).</p><p>Let’s compute first few rows manually:</p><p><strong>Row 1 of B: </strong><strong>[1, 0]</strong></p><pre>ΔW[0] = [1, 0] × A = A[0]  <br>       = [1, 0, 1, 0, 1, 0, 1, 0]</pre><p><strong>Row 2 of B: </strong><strong>[0, 1]</strong></p><pre>ΔW[1] = [0, 1] × A = A[1]  <br>       = [0, 1, 0, 1, 0, 1, 0, 1]</pre><p><strong>Row 3 of B: </strong><strong>[1, 0] → same as Row 1</strong></p><p><strong>Row 4 of B: </strong><strong>[0, 1] → same as Row 2</strong></p><p>…and so on…</p><p><strong>Final ΔW (8×8):</strong></p><pre>ΔW =<br>[[1, 0, 1, 0, 1, 0, 1, 0],<br> [0, 1, 0, 1, 0, 1, 0, 1],<br> [1, 0, 1, 0, 1, 0, 1, 0],<br> [0, 1, 0, 1, 0, 1, 0, 1],<br> [1, 0, 1, 0, 1, 0, 1, 0],<br> [0, 1, 0, 1, 0, 1, 0, 1],<br> [1, 0, 1, 0, 1, 0, 1, 0],<br> [0, 1, 0, 1, 0, 1, 0, 1]]</pre><h4>Step 4: Add LoRA Update to Frozen Weights</h4><p>Now add ΔW to W:</p><p><strong>Final Updated Weights (W_lora = W + ΔW):</strong></p><pre>W_lora =<br>[[ 2,  2,  4,  4,  6,  6,  8,  8],<br> [ 9, 11, 11, 13, 13, 15, 15, 17],<br> [18, 18, 20, 20, 22, 22, 24, 24],<br> [25, 27, 27, 29, 29, 31, 31, 33],<br> [34, 34, 36, 36, 38, 38, 40, 40],<br> [41, 43, 43, 45, 45, 47, 47, 49],<br> [50, 50, 52, 52, 54, 54, 56, 56],<br> [57, 59, 59, 61, 61, 63, 63, 65]]</pre><p>Only <strong>A and B are trained</strong> — W remains frozen. At inference, we use W_lora.</p><h4>Real-World GPT-2 Medium Example (Rank = 4)</h4><h4>Facts:</h4><ul><li>GPT-2 Medium has 24 layers.</li><li>Each self-attention head uses matrices like q_proj, v_proj of size <strong>768×768</strong>.</li><li>Updating one such matrix requires 768×768 = <strong>589,824 parameters</strong>.</li></ul><h4>With LoRA (Rank = 4):</h4><ul><li>A: <strong>4×768</strong>, B: <strong>768×4</strong> → only <strong>6,144 trainable params</strong> per matrix.</li><li>Two matrices per layer (q_proj, v_proj):<br> 6,144 × 2 = 12,288 per layer</li><li>Total across 24 layers:<br> <strong>12,288 × 24 = 294,912 parameters</strong></li></ul><p>That’s <strong>~1%</strong> of full model tuning (vs. 28M+ params), but with comparable performance — and much cheaper!</p><h3>LoRA Configuration in Code</h3><p>Here’s how we configured LoRA in our notebook using Hugging Face + peft:</p><pre>from peft import get_peft_model, LoraConfig, TaskType<br># 3. Apply LoRA<br>lora_config = LoraConfig(<br>    r=8,<br>    lora_alpha=16,<br>    target_modules=[&quot;c_attn&quot;],  # GPT-2 specific<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=TaskType.CAUSAL_LM<br>)<br>model = get_peft_model(model, lora_config)<br>print_model_stats(model)</pre><h4><strong>Config Breakdown:</strong></h4><ul><li>r: Rank of low-rank matrices (smaller = more efficient)</li><li>lora_alpha: Scaling factor (like learning rate multiplier)</li><li>target_modules: Attention/MLP modules where LoRA is applied</li><li>task_type: Specifies task (Causal LM here for GPT-style model)</li></ul><h4>What Does It Actually Do?</h4><p>For every target_module, LoRA adds two trainable matrices inside the forward pass. These matrices:</p><ul><li>Are initialized to zero (so the model starts unchanged)</li><li>Are added to the original output in the attention layer</li><li>Learn task-specific updates during training</li></ul><p>This gives you <strong>task adaptability</strong> with <strong>minimal tuning</strong>.</p><h3>Training the LoRA Model Using PyTorch</h3><p>Once we configured our LoRA adapters and wrapped the GPT-2 model, training it using PyTorch was straightforward. PyTorch’s flexibility made it easy to integrate PEFT into our existing training loop — whether on Kaggle or Colab.</p><p><strong>Training Snippet from Our Notebook</strong></p><pre>import torch<br>from torch.amp import autocast, GradScaler<br>from transformers import get_linear_schedule_with_warmup<br><br><br>scaler = GradScaler()  # device=&#39;cuda&#39; is default if cuda available<br><br># Scheduler setup for 10 epochs<br>num_training_steps = len(train_dataloader) * 10<br>scheduler = get_linear_schedule_with_warmup(<br>    optimizer,<br>    num_warmup_steps=100,<br>    num_training_steps=num_training_steps<br>)<br><br>patience = 5<br>min_delta = 0.001<br>best_val_loss = float(&#39;inf&#39;)<br>patience_counter = 0<br><br>model.to(device)<br>model.train()<br><br>for epoch in range(10):  # 10 epochs<br>    total_loss = 0<br>    for batch in train_dataloader:<br>        input_ids, attention_mask, labels = [x.to(device) for x in batch]<br><br>        optimizer.zero_grad()<br><br>        with autocast(&quot;cuda&quot;):<br>            outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)<br>            loss = outputs.loss<br><br>        scaler.scale(loss).backward()<br><br>        scaler.unscale_(optimizer)<br>        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)<br><br>        scaler.step(optimizer)<br>        scaler.update()<br><br>        scheduler.step()<br><br>        total_loss += loss.item()<br><br>    avg_train_loss = total_loss / len(train_dataloader)<br><br>    # Validation<br>    model.eval()<br>    total_val_loss = 0<br>    with torch.no_grad():<br>        for batch in test_dataloader:<br>        <br>            input_ids, attention_mask, labels = [x.to(device) for x in batch]<br><br>            outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)<br>            val_loss = outputs.loss<br>            total_val_loss += val_loss.item()<br><br>    avg_val_loss = total_val_loss / len(test_dataloader)<br><br>    # Early stopping (optional)<br>    if best_val_loss - avg_val_loss &gt; min_delta:<br>        best_val_loss = avg_val_loss<br>        patience_counter = 0<br>        print(f&quot;Epoch {epoch+1}: Validation loss improved to {avg_val_loss:.4f}, resetting patience.&quot;)<br>    else:<br>        patience_counter += 1<br>        print(f&quot;Epoch {epoch+1}: No improvement in validation loss. Patience {patience_counter}/{patience}&quot;)<br><br>    if patience_counter &gt;= patience:<br>        print(f&quot;Early stopping triggered at epoch {epoch+1}.&quot;)<br>        break<br><br>    model.train()<br>    print(f&quot;Epoch {epoch+1} - Train Loss: {avg_train_loss:.4f} - Val Loss: {avg_val_loss:.4f}&quot;)</pre><p>This training loop:</p><ul><li>Loads batches from our Shakespeare dataset</li><li>Fine-tunes only the <strong>LoRA adapters</strong></li><li>Logs and evaluates after each epoch</li></ul><h4>Observed Loss Curve During Training</h4><p>We trained for 10 epochs on Shakespeare with the following validation trend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ybyCAvamK_O8mn3Y.png" /><figcaption>Loss Curve</figcaption></figure><p>This shows smooth convergence — indicating LoRA adapted quickly with minimal overfitting.</p><h3>Inference Pipeline and Pushing Model to Hugging Face</h3><p>Once training was complete, we moved on to using the model for text generation — Shakespeare-style!</p><h4>Inference with the Fine-Tuned Model</h4><p>We kept inference simple and reproducible. Here’s the exact code we used to generate text from a prompt using our <a href="#"><strong>LoRA fine-tuned GPT-2 model</strong></a><strong> </strong>pushed to Hugging Face Hub:</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;khotveer1/gpt2-medium-lora-finetuned-shakespeare&quot;)<br>model = AutoModelForCausalLM.from_pretrained(&quot;khotveer1/gpt2-medium-lora-finetuned-shakespeare&quot;)<br><br>prompt = &quot;ACT I, SCENE I\nfirst citizen:&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)<br><br>outputs = model.generate(<br>    **inputs,<br>    max_length=80,<br>    do_sample=True,<br>    top_k=40,<br>    temperature=0.80,<br>    repetition_penalty=1.15,<br>)<br><br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><p>This generates beautiful, stylistically consistent Shakespearean dialogue.</p><h4>Output Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96m2hC0s8QdbsSfs.png" /><figcaption>Example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d_Y0oxYnXud4uNvx.png" /><figcaption>Example 2</figcaption></figure><p>The model generates poetic and scene-appropriate continuation resembling Shakespearean tone. <a href="https://huggingface.co/spaces/khotveer1/gpt2-shakespeare-ui">Click here</a> to try yourself.</p><p>After all of this what i can say for sure is:</p><ul><li><strong>Training Time</strong>: Full model took <strong>16+ hours</strong> on Kaggle (~5000+ epochs), while LoRA fine-tuning completed in just <strong>~1.5 hours</strong> (10 epochs).</li><li><strong>Parameters Updated</strong>: Full training updated <strong>all model weights (~44M)</strong>, whereas LoRA updated only <strong>adapter layers (~3M)</strong>, making it highly efficient.</li><li><strong>Flexibility</strong>: LoRA’s <strong>quick convergence</strong> makes <strong>multiple fine-tuning attempts feasible</strong>, unlike full training which is resource- and time-intensive.</li></ul><h3>Conclusion</h3><p>PEFT LoRA is a <strong>powerful and efficient technique</strong> to enhance large pretrained language models with <strong>domain-specific knowledge</strong> — without the need for retraining the entire model. By updating only a <strong>small set of parameters</strong>, it dramatically reduces computational requirements, training time, and storage costs.</p><p>In our case, we fine-tuned gpt2-medium on Shakespearean text using LoRA. This allowed us to <strong>leverage the full power of GPT-2’s pretrained capabilities</strong> while injecting it with the stylistic nuances of classical literature—all in a fraction of the time and compute needed to train from scratch.</p><p>Stay tuned for the next article, where we’ll deploy our fine-tuned model using <strong>Gradio</strong> and <strong>Hugging Face Spaces</strong> to create a free, <a href="https://huggingface.co/spaces/khotveer1/gpt2-shakespeare-ui">interactive UI</a>!</p><h3>Resources</h3><ul><li><strong>Hugging Face Model</strong>: <a href="https://huggingface.co/khotveer1/gpt2-medium-lora-finetuned-shakespeare">khotveer1/gpt2-medium-lora-finetuned-shakespeare</a></li><li><strong>GitHub Code</strong>: <a href="https://github.com/khotveer/gpt2-lora-finetuning-shakespeare">LoRA Fine-Tuning Project</a></li><li><strong>Interactive UI App</strong>: <a href="https://huggingface.co/spaces/khotveer1/gpt2-shakespeare-ui">Gradio Shakespeare Generator</a></li></ul><p>Happy learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61847bef4732" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/mastering-lora-fine-tuning-gpt-2-for-domain-specific-texts-61847bef4732">Mastering LoRA: Fine-Tuning GPT-2 for Domain-Specific Texts</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Fundamentals: Training GPT from Scratch with PyTorch]]></title>
            <link>https://medium.com/data-science-collective/llm-fundamentals-training-gpt-from-scratch-with-pytorch-ad1425a0ae05?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1425a0ae05</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[gpt-from-scratch]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Mon, 26 May 2025 16:21:45 GMT</pubDate>
            <atom:updated>2025-05-26T21:51:14.409Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything You Need to Know to Go from Raw Text to a Functional GPT-2 Mini — No Pretrained Models Required</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GPcL_UUP4kQoO640JhisSA.jpeg" /></figure><p>In recent years, <strong>transformers</strong> have revolutionized the field of natural language processing (NLP). At a high level, a transformer is a type of neural network built to handle sequences of data, like text, by understanding how each word in a sentence relates to every other word — this is achieved using a mechanism called <strong>self-attention</strong>. In this article, we’ll learn how to train a <strong>Chat-GPT like model</strong> using the <strong>GPT-2 architecture</strong>, completely from scratch, and entirely <strong>for free</strong> using open-source tools and cloud GPUs.</p><p>So, let’s start with <strong>why it’s important to understand the training process from scratch</strong>:</p><ol><li><strong>Solve Small Problems Efficiently</strong><br>You don’t always need huge pretrained models.<br>Small models trained from scratch can handle simple or niche tasks well.<br>These models are lightweight, easier to deploy, and cost-effective — ideal for limited hardware or free compute resources.</li><li><strong>Build a Strong Foundation for Fine-Tuning</strong><br>Understand every step of training, from tokenization to loss.<br>Gain insight into what happens behind the scenes.<br>This knowledge helps you fine-tune large models more confidently and effectively.</li><li><strong>Move from Using to Creating Models</strong><br>Get hands-on experience with all model components.<br>Experiment with custom architectures and training setups.<br>This skill opens doors to research and innovation beyond just applying existing models.</li></ol><h3><strong>Understanding the Dataset</strong></h3><p>To train our model from scratch, we’re using the Shakespeare dataset — a lightweight and text-rich dataset perfect for learning and experimentation.</p><ul><li>It’s small in size, which makes it ideal for quick training and testing.</li><li>Great for building and debugging the full training pipeline using PyTorch.</li><li>Enables us to implement GPT-style tokenization from the ground up (covered in the next section).</li><li>Serves as a flexible foundation — once your pipeline works here, you can easily adapt it for other datasets by just tweaking a few parameters.</li><li>The simplicity of the Shakespeare dataset makes it a perfect choice for anyone learning to build and train transformer models from scratch.</li></ul><h3>Tokenization: Breaking Text into Learnable Units (GPT-Style with BPE)</h3><p>Tokenization is a crucial first step in training a GPT model. It converts raw text into numerical tokens that the model can understand and learn from.</p><p><strong>What is GPT-Style Tokenization?</strong></p><p>GPT models use <strong>Byte Pair Encoding (BPE)</strong>— a sub word tokenization method that:</p><ul><li>Learns common character pairs from the text to form sub words.</li><li>Efficiently represents both common and rare words.</li><li>Keeps the vocabulary compact and avoids unknown tokens.</li></ul><p>This approach allows the model to handle new or rare words by breaking them into familiar sub word units.</p><p><strong>Our Tokenization Pipeline</strong></p><p>To replicate GPT-2’s tokenizer, we use a custom ‘<strong>BPE’ </strong>class in our project. This class uses OpenAI’s publicly available files:</p><ul><li><strong>‘encoder.json’</strong> — maps text fragments to unique token IDs.</li><li><strong>‘vocab.bpe’ </strong>— defines merge rules to build sub words from characters.</li></ul><p>These files are downloaded automatically from the official [<a href="https://openai.com/research/better-language-models"><em>GPT-2 124M model</em></a>] and stored locally.</p><p><strong>How the BPE Class Works</strong></p><ul><li>Downloads the tokenizer files if not present.</li><li>Parses and loads the encoder and merge rules.</li><li>Initializes an <strong>‘Encoder’</strong> object to handle encoding/decoding.<br>Exposes two methods:</li></ul><p>encoder(text) — Converts text to tokens.<br>decoder(tokens) — Converts tokens back to text.</p><p>This implementation mirrors GPT-2’s behavior, making it ideal for learning and experimentation.</p><p><strong>Why It Matters</strong></p><ul><li><strong>Reusability</strong>: The same tokenizer logic can be reused across datasets or models.</li><li><strong>Compatibility</strong>: Aligns with GPT-2’s tokenizer used in tools like Hugging Face.</li><li><strong>Learning Value</strong>: You gain hands-on understanding of how raw text becomes model-ready input.</li></ul><p><strong>Example Usage</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*7HQZ1mIF6XduepIQGlTYSQ.png" /></figure><h3>Splitting the Dataset (90:10 Ratio)</h3><p>After tokenization, the dataset is split into two parts: 90% for training and 10% for validation. The training set helps the model learn patterns from the data, while the validation set allows us to evaluate how well the model generalizes to unseen text. This split ensures the model isn’t just memorizing but actually learning meaningful representations.</p><h3>Custom GPT-2 Mini: Lightweight Transformer Architecture</h3><p>To train our model efficiently from scratch, we use a custom variant of the GPT-2 architecture, designed to reduce complexity and training time while still capturing the essence of transformer-based language models.</p><p>We define our model with the following configuration:<br>“n_layer”: 8,<br>“n_head”: 16,<br>“n_embd”: 512</p><p>This model is <strong>as light as ~50 million parameters</strong>, making it ideal for experimentation and learning purposes on limited compute.</p><h4><strong>Why a Custom Architecture?</strong></h4><p><strong>Smaller and faster:</strong> Fewer layers and a reduced embedding size make training feasible on limited hardware (Google Colab GPUs &amp; Kaggle notebooks).<br><strong>Efficient experimentation:</strong> Helps prototype and debug the full training pipeline without long runtimes.<br><strong>Flexible and modular:</strong> By simply modifying these hyperparameters (n_layer, n_head, n_embd), we can scale this up to mimic larger GPT models:</p><ul><li>GPT-2 Small → 12 layers, 12 heads, 768 embedding</li><li>GPT-2 Medium → 24 layers, 16 heads, 1024 embedding</li><li>GPT-2 Large/XL → further scaled versions</li></ul><p>This custom GPT-2 Mini serves as a great foundation to understand how transformer-based models are structured and trained from scratch — with the flexibility to grow as needed.</p><h3>Training Loop: How Our GPT Learns</h3><p>Once the model architecture is ready and the data is tokenized, it’s time to train the GPT model. Below is an overview of the key components and behaviors of our training loop:</p><h4><strong>Infinite Training Loop (Manual Stop)</strong></h4><p>We use a while True loop for training, which means the training will continue <strong>indefinitely</strong> until we manually interrupt it. This is <strong>intentional</strong> — since we’re using free platforms like Google Colab &amp; Kaggle, which have time limits, we:</p><ul><li>Manually stop training <strong>when the loss drops below ~1</strong>.</li><li>Often run the notebook <strong>overnight</strong>, and stop it in the <strong>early morning</strong> before the session gets terminated.</li><li>Always <strong>save the model</strong> before exiting to prevent losing progress.</li></ul><p>This gives us flexibility to fine-tune training based on real-time observations.</p><h4>Key Training Components</h4><h4>1. Optimizer</h4><p>We configure the optimizer using model.configure_optimizers(config), usually a variant of <strong>AdamW</strong>, commonly used in training transformers. It adjusts model weights to minimize loss.</p><h4>2. Learning Rate</h4><p>The learning rate is defined in the config and passed to the optimizer. It&#39;s a crucial hyperparameter controlling <strong>how fast the model learns</strong>. A learning rate too high causes instability, while too low slows down training.</p><h4>3. Gradient Clipping</h4><p>We apply <strong>gradient clipping</strong> using:</p><pre>torch.nn.utils.clip_grad_norm_(model.parameters(), config[&#39;grad_norm_clip&#39;])</pre><p>This ensures gradients do not explode, which is essential for stable training, especially in deep networks like GPT.</p><h4>Validation Logic</h4><p>Every 100 steps, we compute <strong>validation loss</strong> using the validate() method. This helps us monitor how well the model is generalizing on unseen data. If validation loss improves consistently, we know the model is learning properly.</p><h4>Example Termination Conditions</h4><pre>if self.iter_num &gt;= config[&#39;max_iters&#39;]:<br>    break</pre><p>Though the loop is infinite, we can optionally set a max_iters value in the config to stop training automatically after a certain number of iterations.</p><h4>Recap: What Happens in Each Step?</h4><ol><li>A batch of data is fetched.</li><li>Inputs and targets are passed through the model to compute logits and loss.</li><li>The model’s gradients are calculated and clipped.</li><li>The optimizer updates the weights.</li><li>Callbacks (like logging) are triggered.</li><li>Every 100 steps, validation loss is printed and monitored.</li></ol><p>This setup makes training <strong>flexible, modular, and compatible with Colab-like environments</strong>, where sessions can expire and require manual interruption.</p><h3>Loss Convergence</h3><p>The training and validation losses show a smooth and consistent convergence, highlighting the model’s effective learning:</p><ul><li><strong>Initial phase (Epoch 0–1000):</strong><br> Sharp drop in both train (from <strong>~5.0</strong> to <strong>2.4</strong>) and val loss (from <strong>~4.9</strong> to <strong>2.2</strong>), indicating rapid early learning.</li><li><strong>Middle phase (1000–2500):</strong><br> Model continues improving, with train loss reducing to <strong>~0.4</strong> and val loss to <strong>~0.2</strong>. Generalization gap remains small — evidence of a well-regularized model.</li><li><strong>Final phase (2500–5300):</strong><br> Losses plateau and gradually stabilize around <strong>0.2 (train)</strong> and <strong>0.13 (val)</strong>. Minor fluctuations are expected due to mini-batch variance.</li></ul><p>The narrowing <strong>gap between training and validation loss</strong> signals minimal overfitting and excellent generalization on unseen bios.</p><h4><strong>Loss Curve</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tmb8wo_gnfCgQK7ipg8Lug.png" /><figcaption>Loss Curve</figcaption></figure><p>The loss curve graph shows a <strong>steady decline</strong> in both training and validation loss, indicating smooth and consistent learning. The <strong>validation loss closely follows the training loss</strong>, suggesting good generalization with minimal overfitting. The gradual <strong>plateau in later epochs</strong> reflects convergence as the model fine-tunes its understanding.</p><h4><strong>Save Model and Encoder object</strong></h4><ul><li>torch.save(model.state_dict(), ...) saves the trained model&#39;s weights (not the full model structure).</li><li>pickle.dump(bpe, ...) saves your custom tokenizer/encoder object (bpe) to be reloaded during inference.</li></ul><h3>Prediction Pipeline</h3><h4>generate_text()</h4><ul><li>Encodes input using the tokenizer and generates tokens one by one, appending to the sequence.</li><li>Uses the model’s logits to sample the next token probabilistically.</li></ul><h4><strong>Key Generation Parameters</strong></h4><ul><li><strong>temperature</strong> (controls randomness):<br> Higher values (e.g., 1.5) make output more diverse/unpredictable, while lower values (e.g., 0.7) make it more deterministic.</li><li><strong>top_k</strong> (limits options):<br> Filters to the top <em>k</em> probable tokens before sampling, adding control and reducing unlikely completions.</li><li><strong>torch.multinomial()</strong>:<br> Samples from the probability distribution (softmax over logits), introducing stochasticity.</li></ul><h4>Conclusion</h4><p>The code for this entire article can be found <a href="https://github.com/khotveer/custom-gpt-using-pytorch"><strong>here on GitHub</strong></a>. Detailed execution instructions are provided in the README file.</p><p>Enjoy building your <strong>first GPT model from scratch</strong>!</p><p>In the next article, we’ll dive into <strong>fine-tuning a pretrained model using LoRA</strong>, exploring its components and implementation on the same dataset using PyTorch.</p><p>Stay tuned! and, Happy learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1425a0ae05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/llm-fundamentals-training-gpt-from-scratch-with-pytorch-ad1425a0ae05">LLM Fundamentals: Training GPT from Scratch with PyTorch</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Data Science to Predict Attrition: Retaining people using Artificial Intelligence]]></title>
            <link>https://medium.com/up-engineering/attrition-8a716982a7a8?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a716982a7a8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hr]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Wed, 15 May 2019 07:13:22 GMT</pubDate>
            <atom:updated>2019-05-15T17:10:24.359Z</atom:updated>
            <content:encoded><![CDATA[<h4>Identifying attrition way before attrition identifies you</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*q1Ei1og4Vzi54Vn_Gk10PQ.jpeg" /></figure><p>What happens when someone leaves?</p><p>You as a leader are stressed out. You have to <strong>advertise, interview, screen </strong>and <strong>hire</strong>.</p><p>A new member joins after a month or two, but they do not know about what the job entails.</p><p>So more time is spent <strong>training </strong>and <strong>onboarding</strong>. It takes <strong>even more time</strong> for the new member <strong>to get acclimated</strong> to the new job and reach the same productivity as the previous employee.</p><p>Simultaneously you are managing the <strong>disengagement</strong> in the team. Why did their colleague leave? Is this going to happen to them as well?</p><p>What about you as a leader? How much time has this consumed from your work? How many <strong>dollars </strong>has it <strong>cost your company</strong>?</p><h3>Cost of Attrition</h3><p>A study by the <a href="https://www.americanprogress.org/wp-content/uploads/2012/11/CostofTurnover.pdf">Centre of American Progress</a> found that the average<strong> cost to replace</strong> an employee is <strong>20% of the annual salary</strong> of that employee.</p><p>According to a Deloitte study, in FY15, the highest voluntary attrition across sectors was seen in the IT services sector at <strong>21.9%</strong>, whereas the lowest was in the energy and natural resources sector at <strong>10.5%</strong>.</p><p>The high cost of attrition, combined with high attrition rates, makes attrition one of the most <strong>economically costliest problems </strong>for companies.</p><p>In the <strong>United States</strong> alone the <strong>cost of attrition</strong> is <strong>$536 billion</strong> per year.</p><p><em>What can we do?</em></p><blockquote><strong>Enter Artificial Intelligence</strong></blockquote><p>Artificial intelligence has been rapidly adopted as a revolutionary tool for tasks involving prediction and has profoundly transformed several industries.</p><p>Hence it is no surprise that several companies are trying to predict attrition using data science and artificial intelligence.</p><h3>IBM’s Attrition analysis</h3><p>According to <a href="https://en.wikipedia.org/wiki/Ginni_Rometty">Ginni Rometty</a> IBM receives more than 8,000 resumes a day, but roughly 35,000 workers, know who in the workforce is currently searching for a new position. IBM artificial intelligence technology is now 95 percent accurate in predicting workers who are planning to leave their jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QssSuW5J4Qrc-mr2aEdIew.png" /></figure><p>As we can see in the above graph they got this accuracy using many data points like employee job satisfaction, age, job role and etc. AI has so far saved IBM nearly $300 million in retention costs, <a href="https://en.wikipedia.org/wiki/Ginni_Rometty">Ginni Rometty</a> claimed.</p><p>So there’s our solution!</p><blockquote>Collect a ton of data and analyze it! Easy right?</blockquote><p>Not so fast…</p><h3>Problems faced in Attrition analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*v5dymaDzkQ6PQd3vaqhgtQ.png" /></figure><p>The two most important factors to have an accurate prediction of attrition is to have a high volume of attrition data, which is also feature rich.</p><p>However, these are some challenges that most organizations face while collecting this information:</p><h4>Lack of Volume</h4><p>It is not always possible for all the companies to collect this huge amount of feature-rich data about their employee&#39;s insufficient historic data of attrition to predict future attrition.</p><h4>Financial Constraints</h4><p>Collecting data requires financial investment to hire quality data scientists and domain experts who understand the factors that involve attrition.</p><h4>Time Constraints</h4><p>Collecting data involves interviews, questionnaires, forms, etc. So individuals have to dedicate their time if they do not possess rich data or do not have automated tools to collect it.</p><p>This can be time-consuming, which increases the cycle time of predictions, and reduces the accuracy as a result.</p><h4><strong>Employee Privacy</strong></h4><p>Not all employees will consent to have their data collected and analyzed. This leads to inconsistent sets of data, and as a result, also impacts data volume.</p><h3>How we are collecting data</h3><blockquote>Our simple solution to the data collection conundrum</blockquote><p>The <a href="https://www.up-ai.com/">platform</a> we have built at <a href="https://www.up-ai.com/">Up Your Game</a> collects feature-rich performance data on an ongoing basis.</p><p>Performance data can give you a myriad of features such as employee sentiment &amp; employee workload etc. that can predict not only attrition but also engagement and burnout.</p><p>We believe that performance data, combined with employee characteristics can give a robust model to predict attrition.</p><h3>We’ve tackled the problems. Now what?</h3><blockquote>Analyzing attrition data</blockquote><p>Analyzing data is the easier part.</p><h4>AI Tools</h4><p>Artificial intelligence has become so democratized that there are several tools today that help you build predictive models by barely writing any code. Here are some:</p><p><a href="https://uber.github.io/ludwig/">Ludwig</a></p><p><a href="https://www.h2o.ai/">H2O</a></p><p><a href="https://cloud.google.com/automl/">Google Cloud AutoML</a></p><h4>AI-powered HR Platforms</h4><p>The other alternative is to utilize HR tools with this intelligence baked in.</p><p>The <a href="https://www.up-ai.com/">platform</a> we have built at <a href="https://www.up-ai.com/">Up Your Game</a> not only collects data from employee performance, but also has an artificial intelligence engine that is constantly analyzing that data, and making predictions whenever it achieves a high enough accuracy.</p><p>Once you have selected your weapon, all that has to be done is to specify your problem statement.</p><p>For this case that would mean:</p><blockquote>Predict whether an employee <strong>is going to leave</strong> <em>OR</em> <strong>not</strong></blockquote><p>Thus your data would have to have a column that displays whether or not your employees have left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfomVRdX5OGjz03ssLSgzQ.png" /></figure><p>Then we can use this variable to predict whether your current employees are likely to leave.</p><h3>But we have a Data Science team</h3><blockquote>Choosing the right AI algorithms for the job</blockquote><p>So based on our experience at <a href="https://www.up-ai.com/">Up Your Game</a> we have tried and tested several models for attrition prediction using a number of predictors. We have found that certain models work better than others in certain cases:</p><h4><strong>Small amounts of data</strong></h4><p>Ensemble models like Random Forest and XGBoost work best for smaller but diverse amounts of data. While these give an <strong>accurate prediction</strong> they are <strong>harder to interpret </strong>i.e. harder to know what patterns are picked from the data.</p><h4><strong>Large diverse data</strong></h4><p>Using <strong>Deep learning models </strong>will more useful for large data sets.</p><p>Moreover, they are easily interpretable i.e. will also allow you to see how and why the prediction has been achieved.</p><p>The only constraint is that deep learning models need more data otherwise they cause problems like overfitting and they end up giving inaccurate results.</p><h3>Conclusion</h3><p>We can conclude that the most important thing in attrition prediction is <strong>collecting the relevant feature-rich data</strong> while <strong>utilizing robust tools</strong> to analyze it assuring an accurate prediction.</p><p>If you like this article then kindly give claps and if you have any questions please fill free to ask in comments.</p><p>Until my next blog</p><p>Happy Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a716982a7a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/up-engineering/attrition-8a716982a7a8">Using Data Science to Predict Attrition: Retaining people using Artificial Intelligence</a> was originally published in <a href="https://medium.com/up-engineering">Up Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving ML and DL models in MongoDB using python.]]></title>
            <link>https://medium.com/up-engineering/saving-ml-and-dl-models-in-mongodb-using-python-f0bbbae256f0?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0bbbae256f0</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Fri, 04 Jan 2019 10:07:43 GMT</pubDate>
            <atom:updated>2019-01-04T10:28:17.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python tutorial for saving and fetching models from MongoDB.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*eNvgdjHuBBUZ5p31KmX17w.jpeg" /></figure><p>As we know when we train machine learning or deep learning models we have to save trained models for future predictions. Saving machine learning models means saving the intelligence created for business satisfaction. Training models are very expensive these days, so if we can save them and reuse that intelligence for solving some other problems which are also called transfer learning. For example, a trained neural network which can recognize cars can be used to identifying trucks after fine tuning it using transfer learning method.</p><p>Saving models in a database and loading them using python is easy. We choose MongoDB because it is an open-source document database and leading NoSQL database. Now let’s implement this step-by-step using python.</p><p>First, install pymongo using pip as shown below,</p><blockquote>pip install pymongo</blockquote><p>Make sure that you have MongoDB installed in your system if you want to install it <a href="https://docs.mongodb.com/v3.2/administration/install-community/">click here</a>.</p><p>We will first train the xgboost model on iris dataset and then dump it into the database and load it back and use it for predictions. Import important libraries as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQO-Nu9nXP8spwR09Eqotw.png" /></figure><p>Now we will train xgboost on iris dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3nYe2ebDLE4uf15iakmfQ.png" /></figure><p>After training, we will write a helper function to save the model which will first pickle the model. Pickling is just converting any objects to bytes. We have to pickle our model because we cannot save objects directly into MongoDB. This function also creates a connection, database, and collection and then save the model with the name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLXZrKAzpDT4xPQvISEjBQ.png" /></figure><p>Now we will write another helper function for loading saved model. This function first unpickles the saved model and then returns the model. Here, we are using find() function and passing it model name to fetch model from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHcfO80eu162aDm0xIFBqg.png" /></figure><p>After writing helper functions for saving and loading model we just have to call them as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7AQsBEWtwwuljYbF73plg.png" /></figure><p>So, saving and loading model in the database is easy using python. After saving these models we can use them in the future whenever we want. For full notebook <a href="https://github.com/khotveer/Saving_models_in_MongoDB">click here</a>. If you find this article helpful give claps or response see you in the next blog until then happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0bbbae256f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/up-engineering/saving-ml-and-dl-models-in-mongodb-using-python-f0bbbae256f0">Saving ML and DL models in MongoDB using python.</a> was originally published in <a href="https://medium.com/up-engineering">Up Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build the Artificial Intelligence for detecting diabetes using Neural Networks and keras.]]></title>
            <link>https://medium.com/@khotveer1/build-the-artificial-intelligence-for-detecting-diabetes-using-neural-networks-and-keras-89962097f0b0?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89962097f0b0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 17:03:57 GMT</pubDate>
            <atom:updated>2018-12-21T17:07:47.742Z</atom:updated>
            <content:encoded><![CDATA[<h4>Neural Networks tutorial using keras and python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*U0e9wDFjHxDP9RH0qCY1rg.jpeg" /></figure><h3>Deep learning</h3><p>Deep learning is the most important part of artificial intelligence which takes a huge amount of data and provides the solution to any problem. Deep learning used to be a part of machine learning but because of the availability of high computing power and data now it achieved its own place in the field of artificial intelligence. Deep learning is nothing but different applications and architectures of the neural network in different fields.</p><p><em>The neural network is a mathematical model inspired by working of the human brain. According to Wikipedia Warren McCulloch and Walter Pitts (1943) created a computational model for neural networks based on mathematics and algorithms called threshold logic. This model paved the way for neural network research to split into two approaches. One approach focused on biological processes in the brain while the other focused on the application of neural networks to artificial intelligence.</em></p><h3>Simple Neural Network</h3><p>The simple neural network is a mathematical model which simply takes <em>Xn</em> as inputs, multiply inputs with weights <em>Wn</em> and add bias <em>b</em> and pass it from activation function and returns <em>Y</em> as output as shown in below. Single layer simple neural network also called as perceptron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*UA30b0mJUPYoPvN8yJr2iQ.jpeg" /></figure><p>From the above diagram, the activation function is nothing but nonlinear function like sigmoid and relu to achieve nonlinearity. For example, all negative values are assigned to zero in sigmoid function. The purpose of using activation function in the neural network to get the smooth loss function means loss function has to be a convex function or concave function then we can apply gradient descent on it. We will talk about that ahead while implementation.</p><h3>python Implementation</h3><p>It is easy to implement the neural network in python using keras library. Keras is a python library built on top of tensorflow which is a very powerful tool for performing deep learning developed by Google. We will use <a href="https://github.com/khotveer/Neural_network_for_pima_dibeties">Pima diabetes dataset</a> and built a neural network which will predict if a patient is diabetic or not given inputs X like Glucose, blood pressure, skin thickness, etc. First, install keras and tensorflow using pip. For full code and data <a href="https://github.com/khotveer/Neural_network_for_pima_dibeties">click here</a>.</p><p>Now we will load the data using pandas and visualize first five rows or records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpRrF9D-7wa4RkNbhOxdMQ.png" /></figure><p>Then we will choose dependent variable y and independent variables X. After choosing X and y we will scale the data and split them into training and testing sets respectively. Also, we will do one-hot encoding to our target variable y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8o5w9YaIMtSBMpl2RCmqrg.png" /></figure><p>After this, we will move towards designing and building the neural network model using keras. Here we are using one input layer with 12 neurons, one hidden layer with 8 neurons and one output layer with 2 neurons. Hidden Layer is nothing but simple layer which takes the input layer output as input an pass it on to next layer. Here we are using two activation functions relu and sigmoid. Sigmoid takes all negative values and maps them to zero and relu is also similar activation function which can be defined as <em>y = max(0, x).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnmMnLcR7JOAPArPCyahxg.png" /></figure><p>Now we will compile our model and assign optimization method which will perform backpropagation for us. Backpropagation is nothing but it updates weights to optimize our loss function. Here we are using adam optimizer to perform backpropagation. Also, we are using binary cross-entropy as our loss function and accuracy metrics. Accuracy metrics is just the difference between actual values and predicted values. Because this article is just an into to deep learning we will discuss different optimization methods and loss functions in detail in upcoming blogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXCTFUBNrwXBPEPocRa07w.png" /></figure><p>Now finally we will train our model. Here we are using 150 epochs if you train this model with 1000 epochs or more then the model will become more accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xupIMvC14ysK9VzttBDAGQ.png" /></figure><p>After training model, we will predict and evaluate our model using the accuracy score. Also, we will plot out loss function to see if the model is converged correctly or not. If the graph gets more elbow shaped that means model have achieved maximum accuracy and it does not need more training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD8h7FsapnWUpTH-s90p9w.png" /></figure><p>Currently, most used neural networks are CNNs (Convolution neural networks) and RNNs (Recurrent neural networks) which are specifically used for computer vision and for sequential data like time series data respectively. This was our simple introduction to deep learning and neural networks using keras. If you like the article then please give claps and if you have any suggestions or question give comments below, see you in the next article until then happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89962097f0b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get a glimpse of future using time series forecasting using Auto-ARIMA and Artificial Intelligence]]></title>
            <link>https://medium.com/@khotveer1/get-a-glimpse-of-future-using-time-series-forecasting-using-auto-arima-and-artificial-intelligence-273efabec6aa?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/273efabec6aa</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[auto-arima]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 11:33:28 GMT</pubDate>
            <atom:updated>2018-12-15T16:10:16.245Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time Series Forecasting using Auto-ARIMA in python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rhKFE4Pi-m900Rii9fpiQ.jpeg" /></figure><h3>AI and future</h3><p>Currently, there is a lot of development going on in Artificial intelligence research to get an accurate glimpse of the future. If any mathematical model predicts future data taking input as only time then that terminology called as time series forecasting. There are many machine learning and deep learning algorithms which can perform time series predictions like LSTM and ARIMA. Before going into technical part we will see the need of time series forecasting.</p><h4>The need of Time Series Forecasting</h4><p>When it comes to time series forecasting everyone’s dream is predict stock prices and become rich in one day. But there are lots of other important applications of time series forecasting some of them are listed below,</p><h4>Risk Management</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*zzX4K4RlaRHTwcj9IBHHbw.jpeg" /></figure><p>In short in any small or big business risk management is very important. Which means if any company know when unplanned and unwanted events will occur they can manage the resources accordingly to avoid loss. For example, suppose a company wants to know how much attrition will happen in next month or next quarter so that they can allocate essential human resources required. This will saves the companies time and resources.</p><h4>Climate change</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*xW2aRQMRkd1wC56rqxLJ4A.jpeg" /></figure><p>Predicting climate change is one of the most important applications of time series forecasting because we can manage unwanted natural disasters like floods, drought, volcano eruptions, etc. In short, we can save millions of lives using time series forecasting.</p><h3>What is ARIMA?</h3><p>ARIMA is an acronym that stands for AutoRegressive Integrated Moving Average. This is one of the easiest and effective machine learning algorithm to performing time series forecasting. This is the combination of Auto Regression and Moving average. First, let’s understand AR part of ARIMA. Autoregression is a time series model that uses observations from previous time steps as input to the regression equation to predict the value at the next time step. In simple words, it performs regression in previous time step t-1 to predict t. Now MA stands for moving average which is also called as rolling mean. Basically, we are calculating the simple average in a particular time frame and dividing it with the total number of time frames taken.</p><h3>What is Auto-ARIMA?</h3><p>Before training simple ARIMA model we have to figure out p(AR), q(MA), d(Back Timeshift) which is not as easy as fine-tuning other machine learning models. We have to reduce stationarity and get those values which so time-consuming as well as boring.</p><p>Auto-ARIMA uses brute force and tries different combinations of p, q, and d and then returns the best model after evaluation. It uses mean squared error to evaluate the best model. It also uses Akaike Information Criteria (AIC) and Bayesian information criterion (BIC) which are statistical measures of goodness of fit and the simplicity of the model.</p><h3>Implementation of Auto-ARIMA in python</h3><p>There is a python library called the pyramid which is required for performing auto arima on <a href="https://github.com/khotveer/time_series_forecasting_ARIMA">AirPassanger</a> data to predict no of passengers in next month. Simply use pip to install pyramid as shown below,</p><p><em>pip install pyramid-arima</em></p><p>First, we will import important libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJiSZ9xO1GSqoLEYxJUaIQ.png" /><figcaption>importing libraries</figcaption></figure><p>After that, we will load data and convert it into time series data by setting the index of the data frame to time as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS6r2cdAZHpLWCwjlgMZOA.png" /></figure><p>Plotting the time series data is also important to see the trend and seasonality in data. We will plot our data using matplotlib function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWDXd2I4V8m4RfPS-Ax_Yw.png" /></figure><p>After this, we will split data into training and testing set for validation and evaluation purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBIrUPeE9tC8K3lPu6o5_A.png" /></figure><p>Now we will train ARIMA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEeRKvmSGB_ZkN48kJf0pg.png" /></figure><p>After this simply we will do prediction and evaluation of the model using traditional r2score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQX_Dy2rx0HLr4LbspePsg.png" /></figure><p>And we are done for today, for greater accuracy try set max values to more higher numbers. For full code is <a href="https://github.com/khotveer/time_series_forecasting_ARIMA">click here</a>.</p><p>So that’s it if you want to have the glimpse of future you have to do the above steps and then draw the final conclusion. There are lots of good models out there to perform time series forecasting like LSTM, SARIMAX, etc we will see them soon in my upcoming articles until then if you like this article don’t forget to give claps and if you have any questions write a comment until then happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273efabec6aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build the story around data using Exploratory data analysis and pandas.]]></title>
            <link>https://medium.com/data-science/build-the-story-around-data-using-exploratory-data-analysis-and-pandas-c85bf3beff87?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85bf3beff87</guid>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 07:17:42 GMT</pubDate>
            <atom:updated>2018-10-06T05:40:53.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build the story around data using Exploratory data analysis and pandas. The art part of data science.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8aAUWjO7HrLPb8hCAFPrQ.png" /></figure><p>Exploratory data analysis, in short, known as EDA, is the secret sauce for winning data science competitions. EDA is the creative part of data science, a story composed around data using statistical tools. EDA also enables the scientist to do a metaphorical archaeological dig on the data, to unearth any underlying insights. It takes less than five lines of code to train a basic machine learning algorithm. EDA and data preparation in comparison take longer and comprise of 80% of the data scientist’s time.</p><p><strong>What is EDA?<br></strong>In simple words, EDA is a set of statistical approaches to explore and understand data beyond hypothesis testing and experimentation.</p><p><strong>Performing EDA using python</strong><br>Implementing EDA using python is very easy because python has a myriad of statistical analysis packages (e.g numpy, pandas, matplotlib, etc). There are mainly three kinds of analysis done in EDA namely:</p><p>Univariate analysis<br>Bivariate analysis<br>Multivariate analysis</p><p>We will perform all of these three types of analysis step by step using python and draw some conclusions. Download dataset from <a href="https://github.com/khotveer/Exploratory-data-analysis">here</a> and full code from <a href="https://github.com/khotveer/Exploratory-data-analysis">here</a>.</p><p>Loading data using pandas and checking dimensionality of the data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2aVoY8FZaZ6OqoalY7Lmw.png" /><figcaption><strong>reading Employee.csv file</strong></figcaption></figure><h3>Univariate analysis</h3><p>Once we load data we are good to go for the first type of EDA called as univariate analysis. “Uni” means one and “Variate” means variable hence univariate analysis means analysis of one variable or one feature. Univariate basically tells us how data in each feature is distributed and also tells us about central tendencies like mean, median, and mode.</p><p><strong>Descriptive Statistics</strong></p><p><strong>Continuous features</strong><br>First thing first, check measures of central tendencies mean, median, and mode, check min and max values and quantiles of each feature. To do all those things we just have to use pandas “describe()” function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOv3zbmnOntOVqxx4Om2Yg.png" /><figcaption><strong>statistical description</strong></figcaption></figure><p>From the above table, we can see that the average satisfaction level among employees is just 61.12% where it deviates by 24% which means there is lots of variation between employee satisfaction which directly affect productivity. Also, we can see that 50% of employees working on 4 different projects at a time. Here 50% quantile also known as median, we use median because the median cannot be affected by outliers. Where mean is easily affected by outliers.</p><p><strong>Categorical features<br></strong>Descriptive statistics in categorical variables use frequency tables and mode techniques for analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7qxwHpcLpHlTr-SKhWv9A.png" /><figcaption><strong>frequency tables</strong></figcaption></figure><p>From the above image, we can say that almost 48% of employees have a low salary and only 8% employee has a high salary.</p><p><strong>Visualization</strong></p><p><strong>Histogram<br></strong>In<strong> </strong>the univariate analysis, we use histograms for analyzing and visualizing frequency distribution. Plotting histograms in pandas are very easy and straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YT7U3BSMud90R-vefaJFYA.png" /></figure><p>From the above image we see data is not normally distributed so we cannot perform many statistical operations on this data.</p><p><strong>Box-plot<br></strong>Second visualization tool used in the univariate analysis is box-plot, this type of graph used for detecting outliers in data. Data points fall above three standard deviations normally called as outliers. Outliers affect the statistical analysis directly so we have to first detect it and then remove (or fix) it from the data. Box-plot in matplotlib shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9X47LGe9vb1TYzhZUFtlg.png" /><figcaption><strong>box-plot for time spent in the company</strong></figcaption></figure><p>From the above image, we can see that there are four employees spent more time in the company than all other employees. So treatment given to those employees is different than normal employees. Therefore we have to take care of outliers separately.</p><p><strong>Outliers</strong><br>The whole point of using the median is median cannot be affected by outliers, where mean is easily affected by outliers. There are many techniques to handle outliers one of them takes all data between three standard deviations. According to <a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule">empirical rule</a>, almost 99.97% data fall under three standard deviation as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCMZh7xGtjnSXwxyvuEzkg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule"><strong>empirical rule</strong></a></figcaption></figure><p>Data point lies above three standard deviations called as outliers, therefore we take data between three standard deviations to get rid of outliers. The area under curve called as p-value and the measure of distance from the mean is given by standard deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFv74eYqUad96bBdCbuiiQ.png" /><figcaption><strong>python function for removing outliers</strong></figcaption></figure><p>This python function takes input as pandas data frame and returns outliers and data frame with data between three standard deviations this technique called as 3-sigma technique.</p><p>Now EDA called as art part of data science because everyone has a different approach to view data and dig some patterns from it. That set we did quite a lot of EDA using python. In upcoming blogs, I will show you how to perform inferential statistics in python. If you like this blog please like and comment, until then happy learning.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F7b0181%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F7b0181%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/748a06e9019942f2677bba917ef55804/href">https://medium.com/media/748a06e9019942f2677bba917ef55804/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85bf3beff87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-the-story-around-data-using-exploratory-data-analysis-and-pandas-c85bf3beff87">Build the story around data using Exploratory data analysis and pandas.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Machine learning. Build driverless Artificial Intelligence in a few steps.]]></title>
            <link>https://medium.com/@khotveer1/automate-machine-learning-build-driverless-artificial-intelligence-in-a-few-steps-a5382d501479?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5382d501479</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 13:22:57 GMT</pubDate>
            <atom:updated>2018-10-06T13:26:53.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAnbHfLtAF7VwWjG4uOM8w.jpeg" /></figure><p>Recently there are many new developments in the field of machine learning and data science. Now one more thing is trending in this field called driverless-AI or Auto machine learning. So this blog teaches you how to implement auto-ml using python and what to expect from auto-ml.</p><p><strong>Why and what driverless AI?</strong><br>First, understand what exactly is driverless AI and why we need it? So if we want to build any machine learning model, we have to go through certain steps like data cleaning, feature encoding, feature engineering, model building, model selection, etc. Going through all these steps takes more time and efforts, still, we didn’t get an efficient model always. Also, the demand for the data scientist is high but we don’t have the much human resources to fill that demand. To solve these problems we need driverless AI.</p><p>The basic idea of driverless AI is to input raw and unstructured data get the solution for a given problem. For example, if I pass iris dataset with target name as species then it should return me an efficient model with good accuracy. So basically driverless AI should handle feature engineering, data cleaning, model-selection task by its own.</p><p><strong>What we except from driverless AI now?</strong><br>Now there are many companies working on different parts of driverless AI, for example, <a href="https://www.featurelabs.com/">Feature labs</a> working on automated feature engineering they developed opensource python library called <a href="https://github.com/Featuretools/featuretools">feature tools</a>, H2O working on full driverless AI, etc.</p><p><strong>TPOT<br></strong>TPOT is python open source library for model selection and model optimization, they also said that consider TPOT as data scientist assistant. TPOT is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming. Now we will see step by step how to use this library using simple datasets and in next blog, I will show how to automate feature engineering using feature tools.</p><p>For this tutorial, we will use built-in breast-cancer and Boston-housing datasets from the scikit-learn library. First load data in the jupyter notebook using following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nzr39FhBtA4OP1f0rToMg.png" /><figcaption>code</figcaption></figure><p>After deciding independent variables and target variable we will split data into train and test as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*II2Jt-BuyJ7c2tIT633ppQ.png" /><figcaption>splitting data</figcaption></figure><p>Now we will fit TPOT classifier and this will apply different machine learning algorithms automatically and return efficient model. This library built on top of scikit-learn so applying this model is pretty state forward and easy. The syntax is exactly similar like scikit-learn models as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwS15vA5dKIHIqYqv2cXsw.png" /></figure><p><strong>From above,</strong><br><strong>generations</strong>: Number of iterations to run the pipeline optimization process. Generally, TPOT will work better when you give it more generations (and therefore time) to optimize the pipeline.</p><p><strong>population_size</strong>: Number of individuals to retain in the GP population every generation. Generally, TPOT will work better when you give it more individuals (and therefore time) to optimize the pipeline. Basically batch-size.</p><p><strong>cv</strong>: Number of folds to evaluate each pipeline over in k-fold cross-validation during the TPOT optimization process.</p><p><strong>verbosity</strong>: How much information TPOT communicates while it is running. <br>0 = none, 1 = minimal, 2 = high, 3 = all.</p><p>After fitting model, TPOT also provides methods like score and predict to evaluate the model and predict future respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*0XxFx3I0_xM9hX347remlA.png" /></figure><p>Congratulation we built our first classification model using driverless AI library TPOT and now we will see our second example where we will build a regression model using Boston-housing prices dataset. First, we will load the data set and split data train and test using scikit-learn as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyFHOooEUGyM_JfZVSZdPg.png" /></figure><p>Now we will define and fit regressor model and validate it using TPOT and also scikit-learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlKmitLE-GTweNFKiMVnew.png" /></figure><p>So now we have seen how to perform classification and regression using TPOT. You can download full notebook from <a href="https://github.com/khotveer/Driverless-AI-TPOT-">here</a>. In an upcoming blog, I will show you how to perform automated feature engineering using feature tools. If you like this blog then please clap and if you have any queries comment them below. Until then happy learning.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F7b0181%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F7b0181%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/748a06e9019942f2677bba917ef55804/href">https://medium.com/media/748a06e9019942f2677bba917ef55804/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5382d501479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build engaging conversational chat-bot using context management in Dialogflow. Context is king!]]></title>
            <link>https://medium.com/up-engineering/context-management-in-dialogflow-39bac1be38ea?source=rss-9858f58e8e8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/39bac1be38ea</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Veer Khot]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 12:18:52 GMT</pubDate>
            <atom:updated>2018-10-06T06:16:26.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*cMY93mrmy68taOb2FD3iUg.jpeg" /></figure><p>In recent years chatbots are trending, but there is a vacuum in the availability of sophisticated bots that understand context. Most chatbots are only capable of basic request — response conversations. They have a limited ability to understand the context of the conversation, as shown in the example below. The chatbot doesn’t understand I am asking for another joke when I say “one more please”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yGSJ4dloh8r-IZkTJqIYw.png" /></figure><p>Basically the bot doesn’t understand that the context of the conversation is not merely returning a joke but entertaining the user. This is important for making conversation more engaging and meaningful and not sound, for the better choice of a word, … robotic.</p><h3>Steps for context management in dialogflow</h3><p><strong>Create intent</strong></p><p>Intent means simply what the conversation is about. For example intent can be joke , small-talks, help, support, eating, watching-movie, etc. Name given to intent should be short and meaningful. To know more about creating intents. To know more about creating intents read our <a href="https://medium.com/up-engineering/building-conversational-ux-for-your-app-in-10-minutes-using-api-ai-and-python-backend-87dfea167463">first article</a> that walks you through the basics of Dialogflow.</p><p><strong>Add some Training phrases</strong></p><p>Training phrases are the question or request we will make to chatbots. For example “tell me a joke”, “entertain me”, etc. The larger the corpus of training phrases more accurate will the understanding of the bot be (E.g. “what is a joke” or “tell me something about a joke”). The creation of training phrases is explained in <a href="https://medium.com/p/39bac1be38ea/edit">this article</a>. The meaning of both these statements is the same. So add more and more diverse training phrases to make bot more understandable.</p><p><strong>Add some responses</strong></p><p>Responses are answers to the requests mentioned in training phrases. Add more than one responses and make them simple and meaningful. Here is an <a href="https://medium.com/p/39bac1be38ea/edit">article</a> that explains adding responses.</p><p><strong>Add follow-up intent to our main intent</strong></p><p>Here all context management happens. So basically if you ask chatbot “tell me a joke” it replies with joke and then you say “one more” then bot should know you are asking for another joke, that is context (asking for another joke). Context is added because bot should remember the purpose of chat and also what it said in previous sentences. Remembering previous sentences is called context management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*br2k7qHkYthr6l7ImhMOvA.png" /></figure><p>Adding follow-up intent means you are adding context. Adding output context remembers past four sentences of chat. It is very easy to change how much lines context should remember.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJRl-Mm0rY2XNW3Jd13KSg.png" /></figure><p>From above diagram jokesget-followup is name of context and the “5” is the number of statements context should remember. This number can be changed easily and set to any number developer wanted. But setting up context memory at “100” statement is not good idea because even human cannot remember what they said 2 years back. So setting up smaller context memory is good practice based on use of chatbot. Memory of context also called as lifespan.</p><p>Building a chatbot is easy these days but if context management is not that great then it is useless. Because most of the statements human use for chatting or conversations are small like “ok” , “yes” , “No” , “Naa..” , “bravo bravo” , etc. It is not possible for bot to reply on these statement without understanding the context. Bot will simply say “can you say that again?” or “I didn’t get that” which not as natural as human conversation. So having context in chat-bot then it will understand why user said statements like “wow”, “thank you”, “bye”,etc.</p><h3>Sentiment analysis on context</h3><p>Performing sentiment analysis on phrases like “Damm!” , “ok”, “bye” is not possible. So here rather performing sentiment analysis in individual phrase we can perform that on hole conversation happened in one lifespan of context.</p><p>For example assume that we have following conversation</p><p>Conversation A:<br>user1 : “you are too good in natural language processing”<br>user2 : “Dammm!”</p><p>Conversation B:<br>user1 : “you are worst in natural language processing”<br>user2 : “Dammm!”</p><p>If you see conversation A then “Dammm!” phrase used by user2 have positive sentiment because user1 is paying complement to the user2 and that is why user2 is excited and said “Dammm!”. But if you see conversation B then you can see same phrase have negative sentiment because user1 is simply being rude to user2. So using sentiment of hole context we can analyse the intention of user for using phrases like these. Also we can say that if hole context is have more negative or positive sentiment.</p><h3>So conclusion is “context is king!!!”</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39bac1be38ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/up-engineering/context-management-in-dialogflow-39bac1be38ea">Build engaging conversational chat-bot using context management in Dialogflow. Context is king!</a> was originally published in <a href="https://medium.com/up-engineering">Up Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>