<?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 Kaushik Jagini on Medium]]></title>
        <description><![CDATA[Stories by Kaushik Jagini on Medium]]></description>
        <link>https://medium.com/@kaushikjagini95?source=rss-e2a0771b153c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hp0ffF-ljicihhJEXGmimQ@2x.jpeg</url>
            <title>Stories by Kaushik Jagini on Medium</title>
            <link>https://medium.com/@kaushikjagini95?source=rss-e2a0771b153c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:53:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaushikjagini95/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[Attention: Prefill, Decode and KV Cache Variants (MHA, MQA, GQA, MLA) from Scratch in Python on…]]></title>
            <link>https://kaushikjagini95.medium.com/attention-prefill-decode-and-kv-cache-variants-mha-mqa-gqa-mla-from-scratch-in-python-on-3ff83e9269c1?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff83e9269c1</guid>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 02:00:49 GMT</pubDate>
            <atom:updated>2026-11-10T02:00:49.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Attention: Prefill, Decode and KV Cache Variants (MHA, MQA, GQA, MLA) from Scratch in Python on A100 GPU</h3><p>We keep hearing these fancy terms like Prefill, Decode, KV Cache, MQA, GQA, MLA. In the next 10 minutes, we will learn about them in detail.</p><p>You don’t need to know any GPU details. If you know that an LLM predicts one token at a time, you have enough.</p><h3>First, the two phases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JSf98RYM3jODb8c2z0XPQA.gif" /></figure><p><strong>Prefill </strong>is the process of processing all the tokens of your prompt in parallel. The GPU processes them all in one big batch. Lots of arithmetic, done in parallel. The GPU is busy, so we call it <strong><em>compute-bound</em></strong>.</p><p><strong>Decode</strong> is the model writing its answer. Each new token depends on the one before it, so it has to go one at a time. For each new token, the model needs the Keys and Values (K and V) of every earlier token. Recomputing them would be wasteful, so it saves them in a <strong>KV cache</strong> and re-reads that cache on every step.</p><p>Look at the right side of the animation: the tokens are processed one at a time. The computation required for each step is minimal, therefore, it is not compute-bound. However, every step has to read a lot of data from memory: all the model weights plus the whole KV cache. Memory speed, not arithmetic, sets the pace, so decode is <strong><em>memory bound</em></strong>.</p><p>A simple way to picture it: prefill is a chef cooking 2,000 dishes at once, so the chef&#39;s speed is what matters. Decode is cooking one dish at a time, where every dish needs a walk to the pantry. The walking, not the cooking, takes most of the time.</p><p><strong>Decode is a major reason why output tokens cost more than input tokens.</strong></p><h3>What the KV cache actually is</h3><p>Each token produces three vectors: a <strong>Query</strong> (what am I looking for?), a <strong>Key</strong> (what do I offer?) and a <strong>Value</strong> (what do I carry?). To generate the next token, the newest token’s Query is compared against the Keys of every earlier token, and the matching Values are blended together.</p><p>Here’s the useful part: the Key and Value of an <em>earlier</em> token never change, because they depend only on that token. So there’s no reason to compute them twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*s0yje1pEUPXZO_sNXGveyw.gif" /></figure><p>On the left, with no cache, every step recomputes K and V for every token so far, so the work grows with each new token. On the right, we compute K and V only for the newest token (red), append them to the cache, and reuse the rest (orange). The old entries are just read from memory.</p><p>In my bare-bones code, the cache is a plain Python dict holding one K tensor and one V tensor. Each decode step computes K and V for the single new token.</p><p><strong>Size: </strong>Per token, per layer, you store K and V: 2 × d_model × 4 bytes in float32 (d_model is the model’s width, also called the hidden size: how many numbers describe each token). For the large model (d_model=4096) that’s 32 KiB per token per layer. A 2,048-token prompt plus 64 generated tokens comes to about <strong>66 MiB</strong>, which matches what I measured. That is one layer. A real model stacks dozens: 32 layers would mean roughly 2 GiB for a single 2k-token sequence (simple arithmetic, not something I measured).</p><p>That’s the whole story of this article. <strong>Anything that makes the cache smaller should help decode.</strong> Different attention variants do it differently, let’s dig deeper.</p><h3>The setup (just Python and PyTorch)</h3><ul><li>Two combinations. <strong>Small:</strong> d_model=512, 8 heads. <strong>Large:</strong> d_model=4096, 32 heads.</li><li><strong>Hardware</strong>: a CPU, then a Modal <strong>A100-SXM4–40GB</strong>.</li><li><strong>Metrics</strong>: <strong>TTFT</strong> (time to first token, i.e. prefill), <strong>ITL</strong> (inter-token latency, i.e. time per decoded token), and KV cache size.</li><li><strong>Batch</strong>: how many conversations the GPU generates at the same time. b1 means one, b8 means eight.</li><li><strong>tok/s</strong>: generated tokens divided by the total time, prefill included. That&#39;s why it is lower than 1 ÷ <strong>ITL</strong>.</li><li><strong>Prompts</strong>: 128 tokens for the small model, 2,048 or 8,192 tokens for the large one. Each run then generates 64 tokens.</li></ul><p>The animations below draw just 4 query heads so the arrows are readable. The real models have 8 or 32.</p><h3>Method 1: MHA (Multi-Head Attention), the baseline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Bc-O5HZEHTlRQGy8JadBXA.gif" /></figure><p><strong>The mechanism.</strong> Each attention head has its own query (Q), its own key (K) and its own value (V). So the cache stores a separate K,V pair per head. Every decode step, every head reads its own entry.</p><p><strong>The cache is big.</strong> For every token you keep 2 × (number of heads) × (head size) numbers.</p><p><strong>Numbers (A100, large model):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbEJWim5KFLUmmL_GJyf9Q.png" /></figure><p>Small model on the A100, batch 1: TTFT 0.61 ms, ITL 0.65 ms, 1,550 tok/s.</p><p>Keep in mind one thing from this table: at batch 1, the time per token goes from <strong>0.65 ms to 0.96 ms</strong> when the prompt grows from 2k to 8k tokens. The model is the same. Only the cache got longer. That’s decode paying for reading it.</p><p><strong>MHA:</strong></p><ul><li>Example model: GPT-2, GPT-3, BERT and the original Llama 1 models.</li><li>When to use it: when quality matters most and the cache is not your bottleneck, such as training, encoder models, short contexts or small batches. It is the simplest choice and the baseline for the others.</li></ul><h3>Method 2: MQA (Multi-Query Attention)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nVhEuEtNsQ281QH-oUNIaA.gif" /></figure><p><strong>The mechanism.</strong> Keep all the query heads, but make every head share <strong>one</strong> K and <strong>one</strong> V. In the animation, the four arrows now all come from the same box.</p><p><strong>The cache shrinks</strong> by the number of heads: <strong>32×</strong> in our large model. The cost is quality: all heads now look at the same keys, so they have less to specialise on. I did not measure quality here.</p><p><strong>Numbers (A100, large model), and the change versus MHA:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pflBDKKtUecU7xwh41zsOw.png" /></figure><p><strong>MHA vs MQA</strong>:</p><ul><li>Throughput is about <strong>15–25% higher</strong> in every large config.</li><li>Prefill is faster too (27 → 15 ms at 2k tokens). Fewer K and V values to compute and write.</li><li>The biggest tell: MQA’s time per token is <strong>flat</strong> as context grows (0.642 → 0.680 ms), while MHA’s climbed from 0.65 to 0.96. MQA barely notices the longer cache because there’s so little of it to read.</li></ul><p>On the small model on the A100, MQA and MHA were <em>identical</em> (0.648 vs 0.646 ms per token). I’ll come back to that.</p><p><strong>MQA</strong>:</p><ul><li>Example model: PaLM, Falcon-7B, StarCoder and Gemma 2B.</li><li>When to use it: latency-sensitive, high-throughput serving where memory is tight, such as code completion or small models on limited hardware. It gives the smallest cache and the flattest per-token time, at some cost in quality.</li></ul><h3>Method 3: GQA (Grouped-Query Attention)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9YJjX7fHP7wpAOQ-dM-LAg.gif" /></figure><p><strong>The mechanism.</strong> Instead of 1 K,V for everyone (MQA) or 1 per head (MHA), split the heads into <strong>groups</strong>, and each group shares one K,V. Here, 4 heads form 2 groups. In the large model, 32 heads share 8 K,V sets, so the cache is <strong>4× smaller</strong> than MHA.</p><p>This is why GQA is popular in practice: you keep some of the specialisation and still cut the cache.</p><p><strong>Numbers (A100, large model):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WgUBAA2hqkGx_PGnhjLqg.png" /></figure><p><strong>MHA vs MQA vs GQA:</strong></p><ul><li>Cache: MHA 258 MiB → GQA 64.5 → MQA 8.1 (at 8k tokens). GQA sits in the middle, as designed.</li><li>Throughput: GQA gets <strong>about 5–15% over MHA</strong>, MQA gets 15–25%. Also in the middle.</li><li>GQA’s <em>per-token</em> time was slightly <strong>worse</strong> than MHA’s in my runs (1.07 vs 0.96 ms at 8k), but that gap is within noise (one run, 5 repeats), so treat them as about the same. My guess is that my code expands the shared K,V back to the full head count on every step. The throughput gain comes from faster prefill.</li></ul><p><strong>GQA:</strong></p><ul><li>Example model: Llama 3 (8B and 70B), Llama 2 70B, Mistral 7B and Qwen2.5.</li><li>When to use it: the sensible default for general-purpose LLMs. It keeps most of MHA’s quality with a 4x to 8x smaller cache, which helps with long prompts and many concurrent users.</li></ul><h3>Method 4: MLA (Multi-head Latent Attention)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tCeGxevvsqAlxz1pvTNv0w.gif" /></figure><p><strong>The mechanism.</strong> A different idea. Instead of sharing K,V between heads, <strong>compress</strong> them. Store a small “latent” vector per token (green box). At each step, <strong>rebuild</strong> the K and V for every head from that latent (dashed boxes), then attend as usual. Heads keep their own K,V. You pay a bit of extra compute to rebuild them, and you store much less.</p><p>In our large model the latent is 512 numbers, against 8,192 for MHA’s K and V together. That’s <strong>16× smaller</strong>.</p><p><strong>Numbers (A100, large model):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3qQQd7bWBfXtQ9cT3whcw.png" /></figure><p><strong>MHA vs MLA, what I see:</strong></p><ul><li>The cache is 16× smaller, yet MLA was the <strong>slowest</strong> at batch 1. Prefill at 8k tokens took 323 ms against MHA’s 174 ms.</li><li>One exception: at batch 8 its per-token time (1.20 ms) beat everything else, MHA’s 1.65 ms included. That’s the one place the smaller cache won.</li></ul><p><strong>Why the slowdown?</strong> My honest guess: this implementation rebuilds full K and V from the latent every step, which is extra arithmetic that grows with context. Real MLA implementations (as in DeepSeek models) fold that rebuilding into the attention math so it doesn’t happen explicitly. I did not do that. So the numbers here show MLA’s <strong>memory saving</strong> but not its intended <strong>speed</strong>. Treat the slowdown as a limit of my code, not of MLA.</p><p><strong>MLA:</strong></p><ul><li>Example model: DeepSeek-V2, V3 and R1.</li><li>When to use it: very long contexts and large-scale serving where the cache limits how many users fit on a GPU. Quality stays close to MHA, but the implementation is more complex.</li></ul><h3>Putting the four side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMXF7CJKmhH74JzEwfd1Og.png" /></figure><p>The cache sizes are exact, not measured noise: MHA 258 MiB, GQA 64.5, MLA 16.1, MQA 8.1 (batch 1, 8k tokens).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hed2oMcZlasaKaew14k3Lw.png" /></figure><p>This chart is the one I’d keep. As context grows from 2k to 8k, MHA slows down by about 48% and GQA by about 57% (in this implementation), while MQA barely moves (+6%). MLA is flat too (+4%), but from a higher starting point. Smaller cache, less to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7bYhIOQi2ptcfG3w3I_7Q.png" /></figure><h3>Some interesting findings:</h3><p><strong>1. A decoded token costs 45 to 135× more than a prefilled one.</strong> Prefill at 8k tokens took 174 ms, so about <strong>21 µs per token</strong>. Decode took 960 µs per token. That’s roughly <strong>45×</strong> more per token, with the same weights. On the small model it was even bigger: 4.8 µs per prefilled token against 646 µs per decoded token, about <strong>135×</strong>. This is the core of why output tokens cost more than input tokens on API price lists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkndX0SUWc9xYbzca1KRrg.png" /></figure><p><strong>2. Small model on a GPU: all attention variants look the same.</strong> On the small model, every method took about 0.65 ms per token regardless of cache size (MLA a bit more). With a 128-token prompt the cache is only 764 KiB, so reading it takes almost no time. What you’re measuring is the fixed cost of launching GPU operations. The tricks only start paying off when the cache is large enough to matter: bigger models, longer prompts, bigger batches.</p><p><strong>3. CPU vs GPU.</strong> On the CPU, MQA and MLA looked much faster than MHA (up to about 2.5× for MLA at batch 4). On the GPU that vanished. The small MHA model even ran faster on the CPU (about 4,500 tok/s) than on the A100 (1,550 tok/s). CPU timings moved 20–50% between runs, and a CPU has a very different balance of compute and memory. I’d take the CPU speed ranking as noise. The cache sizes were the same on both, since they’re just arithmetic.</p><p><strong>4. Cache savings don’t turn into speed one-for-one.</strong> MQA’s cache is 32× smaller but its throughput is only ~15–25% better. Decode still has to read the model weights, launch kernels and handle the projections. And in my code the cache grows via torch.cat, which copies it on every step. A preallocated cache would make the cache differences show up more.</p><p><strong>5. The cache savings matter most for capacity.</strong> At 8k tokens, MHA needs 258 MiB of cache per sequence for <em>one layer</em>. A real model has dozens of layers, and servers batch many sequences. A 4× to 32× smaller cache lets up to 4× to 32× more sequences fit in the GPU memory left for the cache (the model weights still take their share). That benefit isn’t visible in a single-layer timing test, and probably matters more than the speedup.</p><p><em>Code for all four attention variants, the benchmark and the Modal runner is in the repo: </em><a href="https://github.com/kjagini/attention-kv-cache-bench">https://github.com/kjagini/attention-kv-cache-bench</a></p><p>Thanks for reading, and if you are still here, I’m sure we both have something in common.</p><p>We can connect on <a href="https://www.linkedin.com/in/kaushik-jagini-b76ba2139">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff83e9269c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What If We Swapped Lives With the Luckiest Person We Know?]]></title>
            <link>https://kaushikjagini95.medium.com/what-if-we-swapped-lives-with-the-luckiest-person-we-know-30a597ed8b0d?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a597ed8b0d</guid>
            <category><![CDATA[self-help]]></category>
            <category><![CDATA[luck]]></category>
            <category><![CDATA[thinking]]></category>
            <category><![CDATA[mindset]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 02:20:39 GMT</pubDate>
            <atom:updated>2026-07-18T02:20:39.428Z</atom:updated>
            <content:encoded><![CDATA[<p>There are certain ideas that sit quietly in the back of your mind for years. You hear them often enough that they become familiar, but not meaningful. Then one day, seemingly out of nowhere, they connect with another idea you’ve been carrying around. Suddenly, both make perfect sense.</p><p>That happened to me recently.</p><p>Growing up, my dad would often say, “Nobody can steal your luck.”</p><p>I always took it as one of those reassuring things parents say when life doesn’t go your way. I appreciated it, but I never stopped to ask what it actually meant.</p><p>Years later, I found myself thinking about another phrase that appears everywhere in books, podcasts, and conversations about success: You make your own luck.</p><p>Individually, both ideas sounded reasonable. Together, they became something much more powerful.</p><p>What we call luck is often just the final scene of a much longer story.</p><p>When someone lands an incredible opportunity, starts a successful company, or seems to be exactly where they need to be at the perfect time, it’s tempting to describe them as lucky. Sometimes they genuinely are. Randomness exists. Timing matters.</p><p>But randomness rarely tells the whole story.</p><p>Being in the right place at the right time is only half the story. Getting there in the first place, that’s on you. That’s a decision, made deliberately, long before luck ever shows up.</p><p>Small choices that looked insignificant at the time but quietly changed the trajectory of a life.</p><p>Choosing to learn instead of staying comfortable.</p><p>Taking a role that didn’t pay the most but offered the steepest learning curve.</p><p>Starting a project before feeling completely ready.</p><p>Having difficult conversations instead of avoiding them.</p><p>Remaining curious after failing instead of becoming cynical.</p><p>None of these decisions guarantee success. Yet together, they dramatically increase the chances of recognizing and acting on opportunity when it eventually appears.</p><p>Perhaps that’s what we mistake for luck.</p><p>Then a thought experiment occurred to me.</p><p>Imagine the luckiest person you know.</p><p>Not someone famous. Someone real.</p><p>Now imagine another person waking up tomorrow having inherited that exact life. The same career. The same relationships. The same network. The same resources. The same opportunities waiting ahead.</p><p>At first glance, it feels as though the outcome should remain unchanged.</p><p>But would it?</p><p>Probably not.</p><p>Because lives aren’t shaped by opportunities alone. They’re shaped by how people respond to those opportunities.</p><p>The same difficult conversation might be avoided.</p><p>The same risk might feel too uncomfortable.</p><p>The same mentor might never receive a phone call.</p><p>The same rejection might convince one person to quit while pushing another person to improve.</p><p>No single decision changes everything.</p><p>But thousands of them do.</p><p>Over months and years, those two lives would slowly begin to drift apart until they no longer looked anything alike.</p><p>That’s when it struck me.</p><p>Maybe luck isn’t something a person possesses.</p><p>Maybe it’s something that emerges from the accumulation of countless decisions.</p><p>You can inherit someone’s circumstances.</p><p>You cannot inherit the thinking that created them.</p><p>That’s why I’ve slowly stopped thinking about luck as something to chase.</p><p>I think of it as something to prepare for.</p><p>Every good decision is a small investment in a future that doesn’t exist yet. Most of those investments never pay off immediately. Some never do.</p><p>But every so often, one of them compounds into what everyone else calls a lucky break.</p><p>The promotion.</p><p>The introduction.</p><p>The business idea.</p><p>The opportunity that seemed to appear out of nowhere.</p><p>Except it didn’t.</p><p>It arrived after years of invisible preparation.</p><p>That’s also when my dad’s words finally made sense.</p><p>“Nobody can steal your luck.”</p><p>If luck is built through judgment, character, resilience, and the willingness to keep learning, then nobody can actually take it away.</p><p>People can take positions.</p><p>They can take clients.</p><p>They can take opportunities.</p><p>They can even beat you today.</p><p>But they can’t take the habits that made those opportunities possible in the first place.</p><p>And because they can’t take those habits, they can’t take your ability to create new opportunities tomorrow.</p><p>The bottom line is, we all must be obsessed with the process of getting lucky. That means to be obsessed with the process of creating chances for ourselves.</p><p>To begin with, just ask:</p><p>“What decisions can I make today that my future self will one day call luck?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a597ed8b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat with your podcast using RAG — Part 2]]></title>
            <link>https://kaushikjagini95.medium.com/chat-with-your-podcast-using-rag-part-2-364af68cf707?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/364af68cf707</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 22:01:42 GMT</pubDate>
            <atom:updated>2024-01-22T17:20:24.271Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat with your podcast using RAG — Part 2</h3><p>Now that we have understood how RAG works in <a href="https://kaushikjagini95.medium.com/chat-with-your-podcast-using-rag-part-1-3db15e4772ad">Part 1</a>. This article is going to be straight up code with less theory and more code.</p><p>Let’s start off with package installations:</p><pre>! pip install openai panel python-dotenv langchain</pre><p>We are heavily going to be using langchain to build our RAG system. Other than that, it is important to have the openAI API to play around with the video.</p><p>If we recall, we split the text into chunks and then store those chunks in the vector database. To do that, we use <em>chroma </em>to store our vectors<em>.</em></p><h3>Step 1: Extract the audio from the video</h3><pre>from langchain.document_loaders.generic import GenericLoader<br>from langchain.document_loaders.parsers import OpenAIWhisperParser<br>from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader<br><br><br>url=&quot;https://www.youtube.com/watch?v=P7gDP0M9T7Q&amp;pp=ygUTaHViZXJtYW4gMTAgbWludXRlcw%3D%3D&quot;<br>save_dir=&quot;docs/youtube/huberman&quot;<br>loader = GenericLoader(<br>    YoutubeAudioLoader([url],save_dir),<br>    OpenAIWhisperParser()<br>)<br>documents = loader.load()</pre><p>Create a GenericLoader instance, which is a generic document loader. It takes two arguments:</p><ul><li>YoutubeAudioLoader: A loader specifically designed for loading audio from YouTube videos.</li><li>OpenAIWhisperParser: A parser used for processing the loaded content.</li></ul><h3>Step 2: Splitting the text into different chunks and</h3><pre>from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)<br>docs = text_splitter.split_documents(documents)</pre><p>In future articles, we will delve into the detailed meanings and significance of each parameter and function. For instance, we’ll explore the various <strong>TextSplitters</strong> available and why we specifically opted for <strong>RecursiveCharacterTextSplitter</strong>.</p><p>We’ll also discuss the rationale behind choosing 1000 as the <strong>chunk_size</strong> and 150 as the <strong>chunk_overlap</strong>. These considerations will provide a comprehensive understanding of our approach and decision-making process in utilizing these components.</p><p>chunk_size: The size of each chunk of text. In this case, it&#39;s set to 1000 characters.</p><p>chunk_overlap: The overlap between consecutive chunks. It helps in maintaining context between chunks. Here, it&#39;s set to 150 characters.</p><p>The chunk_overlap of 150 denotes that the last 150 words of the first chunk will share similarity with the initial 150 words of the subsequent chunk. This approach ensures a smooth transition between adjacent chunks, maintaining context and coherence in the divided text.</p><h3>Step 3: Vectorizing the Data</h3><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import DocArrayInMemorySearch<br><br># define embedding<br>    embeddings = OpenAIEmbeddings()<br>    # create vector database from data<br>    db = DocArrayInMemorySearch.from_documents(docs, embeddings)</pre><h3>Step 4: Create a Chatbot Chain</h3><pre>from langchain.chains import RetrievalQA,  ConversationalRetrievalChain<br><br>retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: k})retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: k})<br>qa = ConversationalRetrievalChain.from_llm(<br>        llm=ChatOpenAI(model_name=llm_name, temperature=0), <br>        chain_type=chain_type, <br>        retriever=retriever, <br>        return_source_documents=True,<br>        return_generated_question=True,<br>    )</pre><p>Here we are setting up a pipeline for conversational retrieval-based question answering, utilizing a language model (ChatOpenAI) for question generation and a retriever for document retrieval.</p><p>A little more information about the code:</p><p><strong>Retriever Configuration</strong>: Use db.as_retriever() to configure a retriever for vector similarity search.</p><p><strong>ConversationalRetrievalChain Configuration</strong>: Create an instance of ConversationalRetrievalChain for question answering. The configuration involves:</p><ul><li>llm: The language model used for generating questions. In this case, it&#39;s an instance of ChatOpenAI with specified parameters such as model name (llm_name) and temperature.</li><li>chain_type: The type of conversational retrieval chain.</li><li>retriever: The configured retriever from the vector database.</li><li>return_source_documents: Whether to include the source documents in the output.</li><li>return_generated_question: Whether to include the generated question in the output.</li></ul><h3>Step 5: Create a Chatbot</h3><p>Creating a chatbot has less to do with RAG and more to do with Engineering, hence, I skip the detail explanation of the chatbot in this article to make sure we are keeping this RAG focused. However, a short explanation of the code is provided followed by the code below:</p><pre>import panel as pn<br>import param<br><br>class cbfs(param.Parameterized):<br>    chat_history = param.List([])<br>    answer = param.String(&quot;&quot;)<br>    db_query  = param.String(&quot;&quot;)<br>    db_response = param.List([])<br>    <br>    def __init__(self,  **params):<br>        super(cbfs, self).__init__( **params)<br>        self.panels = []<br>        self.qa = load_db(self.loaded_file,&quot;stuff&quot;, 4)<br>    <br>    def call_load_db(self, count):<br>        if count == 0 or file_input.value is None:  <br>            return pn.pane.Markdown(f&quot;Loaded File: {self.loaded_file}&quot;)<br>        else:<br>            file_input.save(&quot;temp.pdf&quot;)  # local copy<br>            self.loaded_file = file_input.filename<br>            button_load.button_style=&quot;outline&quot;<br>            self.qa = load_db(&quot;temp.pdf&quot;, &quot;stuff&quot;, 4)<br>            button_load.button_style=&quot;solid&quot;<br>        self.clr_history()<br>        return pn.pane.Markdown(f&quot;Loaded File: {self.loaded_file}&quot;)<br><br>    def convchain(self, query):<br>        if not query:<br>            return pn.WidgetBox(pn.Row(&#39;User:&#39;, pn.pane.Markdown(&quot;&quot;, width=600)), scroll=True)<br>        result = self.qa({&quot;question&quot;: query, &quot;chat_history&quot;: self.chat_history})<br>        self.chat_history.extend([(query, result[&quot;answer&quot;])])<br>        self.db_query = result[&quot;generated_question&quot;]<br>        self.db_response = result[&quot;source_documents&quot;]<br>        self.answer = result[&#39;answer&#39;] <br>        self.panels.extend([<br>            pn.Row(&#39;User:&#39;, pn.pane.Markdown(query, width=600)),<br>            pn.Row(&#39;ChatBot:&#39;, pn.pane.Markdown(self.answer, width=600, style={&#39;background-color&#39;: &#39;#F6F6F6&#39;}))<br>        ])<br>        inp.value = &#39;&#39;  #clears loading indicator when cleared<br>        return pn.WidgetBox(*self.panels,scroll=True)<br><br>    @param.depends(&#39;db_query &#39;, )<br>    def get_lquest(self):<br>        if not self.db_query :<br>            return pn.Column(<br>                pn.Row(pn.pane.Markdown(f&quot;Last question to DB:&quot;, styles={&#39;background-color&#39;: &#39;#F6F6F6&#39;})),<br>                pn.Row(pn.pane.Str(&quot;no DB accesses so far&quot;))<br>            )<br>        return pn.Column(<br>            pn.Row(pn.pane.Markdown(f&quot;DB query:&quot;, styles={&#39;background-color&#39;: &#39;#F6F6F6&#39;})),<br>            pn.pane.Str(self.db_query )<br>        )<br><br>    @param.depends(&#39;db_response&#39;, )<br>    def get_sources(self):<br>        if not self.db_response:<br>            return <br>        rlist=[pn.Row(pn.pane.Markdown(f&quot;Result of DB lookup:&quot;, styles={&#39;background-color&#39;: &#39;#F6F6F6&#39;}))]<br>        for doc in self.db_response:<br>            rlist.append(pn.Row(pn.pane.Str(doc)))<br>        return pn.WidgetBox(*rlist, width=600, scroll=True)<br><br>    @param.depends(&#39;convchain&#39;, &#39;clr_history&#39;) <br>    def get_chats(self):<br>        if not self.chat_history:<br>            return pn.WidgetBox(pn.Row(pn.pane.Str(&quot;No History Yet&quot;)), width=600, scroll=True)<br>        rlist=[pn.Row(pn.pane.Markdown(f&quot;Current Chat History variable&quot;, styles={&#39;background-color&#39;: &#39;#F6F6F6&#39;}))]<br>        for exchange in self.chat_history:<br>            rlist.append(pn.Row(pn.pane.Str(exchange)))<br>        return pn.WidgetBox(*rlist, width=600, scroll=True)<br><br>    def clr_history(self,count=0):<br>        self.chat_history = []<br>        return<br><br><br><br><br><br><br><br><br>cb = cbfs()<br><br>file_input = pn.widgets.FileInput(accept=&#39;.pdf&#39;)<br>button_load = pn.widgets.Button(name=&quot;Load DB&quot;, button_type=&#39;primary&#39;)<br>button_clearhistory = pn.widgets.Button(name=&quot;Clear History&quot;, button_type=&#39;warning&#39;)<br>button_clearhistory.on_click(cb.clr_history)<br>inp = pn.widgets.TextInput( placeholder=&#39;Enter text here…&#39;)<br><br>bound_button_load = pn.bind(cb.call_load_db, button_load.param.clicks)<br>conversation = pn.bind(cb.convchain, inp) <br><br>jpg_pane = pn.pane.Image( &#39;./img/convchain.jpg&#39;)<br><br>tab1 = pn.Column(<br>    pn.Row(inp),<br>    pn.layout.Divider(),<br>    pn.panel(conversation,  loading_indicator=True, height=300),<br>    pn.layout.Divider(),<br>)<br>tab2= pn.Column(<br>    pn.panel(cb.get_lquest),<br>    pn.layout.Divider(),<br>    pn.panel(cb.get_sources ),<br>)<br>tab3= pn.Column(<br>    pn.panel(cb.get_chats),<br>    pn.layout.Divider(),<br>)<br>tab4=pn.Column(<br>    pn.Row( file_input, button_load, bound_button_load),<br>    pn.Row( button_clearhistory, pn.pane.Markdown(&quot;Clears chat history. Can use to start a new topic&quot; )),<br>    pn.layout.Divider(),<br>    pn.Row(jpg_pane.clone(width=400))<br>)<br>dashboard = pn.Column(<br>    pn.Row(pn.pane.Markdown(&#39;# ChatWithYourPodcast&#39;)),<br>    pn.Tabs((&#39;Conversation&#39;, tab1), (&#39;Database&#39;, tab2), (&#39;Chat History&#39;, tab3),(&#39;Configure&#39;, tab4))<br>)<br></pre><p>The provided code creates an interactive dashboard named “ChatWithYourPodcast” using the panel library in Python. The dashboard integrates a conversational chatbot with a document database for question answering. The cbfs class defines parameters and methods for loading the database, handling user queries, and displaying relevant information. The dashboard includes tabs for &quot;Conversation,&quot; &quot;Database,&quot; &quot;Chat History,&quot; and &quot;Configure,&quot; offering users a straightforward interface to interact with the chatbot, load the database, and visualize chat history and database interactions.</p><p>The core functionality involves user input handling, database loading, and chatbot responses displayed in an organized format. The dashboard provides a user-friendly environment for exploring the chatbot’s capabilities, managing interactions, and gaining insights from the database in a structured manner.</p><p>Demo of what we were able to accomplish so far:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F899689775%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F899689775&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1777459600-e0121dbf35babe2bb0f254a650a3b6e544d689a3442a2b4b14305b8466dead2d-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/673c946ec5a573f24d2408d9b52125b0/href">https://medium.com/media/673c946ec5a573f24d2408d9b52125b0/href</a></iframe><p><strong>References and Acknowledgments:</strong></p><p><em>Inspired by Harrison Chase’s “Chat with your data” (</em><a href="https://github.com/hwchase17"><em>https://github.com/hwchase17</em></a><em>), I’ve adapted and shaped this concept to suit my objectives.</em></p><p><a href="https://sophiamyang.medium.com/how-to-build-your-own-panel-ai-chatbots-ef764f7f114e"><em>Chatbot panel design by Sophia Yang</em></a></p><p>If you’ve read until here, thank you. I’m sure you and I have something in common.</p><p>Let’s connect on <a href="https://www.linkedin.com/in/kaushik-jagini-b76ba2139">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364af68cf707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat with your podcast using RAG — Part 1]]></title>
            <link>https://kaushikjagini95.medium.com/chat-with-your-podcast-using-rag-part-1-3db15e4772ad?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db15e4772ad</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 17:35:50 GMT</pubDate>
            <atom:updated>2024-01-22T17:20:04.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat with your podcast using RAG — Part 1</h3><p>As pointed out in deeplearning.ai, we no longer search the internet, we chat with it. Similarly, in 2024, we would no longer listen to the podcasts for several hours (thanks to low attention span). Instead, there could be a rising interest in chatting with podcasts to quickly get the information we need.</p><p>We’ll choose a YouTube podcast and engage in a conversation with it by posing questions to our chatbot, which will provide answers. I’ll be selecting a segment from my preferred podcaster, Andrew Huberman. You can find the link to the video we’ll be interacting with here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP7gDP0M9T7Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP7gDP0M9T7Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP7gDP0M9T7Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/243d9514372ddbedd9d171692f7855c3/href">https://medium.com/media/243d9514372ddbedd9d171692f7855c3/href</a></iframe><p>A brief overview of what we’ll showcase in this series: (it does not require any account, you can directly watch the video by clicking on the link below)</p><p><a href="https://vimeo.com/899689775?share=copy">https://vimeo.com/899689775?share=copy</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F899689775%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F899689775&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1777459600-e0121dbf35babe2bb0f254a650a3b6e544d689a3442a2b4b14305b8466dead2d-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/673c946ec5a573f24d2408d9b52125b0/href">https://medium.com/media/673c946ec5a573f24d2408d9b52125b0/href</a></iframe><p>Alright, now that you’ve understood the magic of RAG, let’s now get into the intricacies of it.</p><p>This marks the beginning of our series, and in Part 1, I’ll offer a brief intuition about RAG before diving into the solution. If you’re already familiar with RAG, feel free to skip ahead to the coding in <a href="https://kaushikjagini95.medium.com/chat-with-your-podcast-using-rag-part-2-364af68cf707">Part 2</a>.</p><p>Imagine a student has an exam tomorrow but the lectures span an extensive 3–5 hours. Given the time constraints, engaging in a chat-based interaction with these lectures could offer a more efficient and accessible way to learn, compared to watching the entire duration.</p><p><strong>RAG(Retrieval Augmented Generation):</strong></p><p>Picture this: you’re running a fever, and you decide to see your general physician. In this scenario, the doctor promptly prescribes medications or suggests tests based on their assessment of your condition, relying on their “expertise”.</p><p>If you approach the same doctor with an issue related to your nervous system, they would promptly acknowledge their limitation, stating, “I’m not an expert in this field, and I will direct you to the Neurologist.” By taking this approach, the Neurologist, armed with their specialized knowledge, can provide the context needed for the specific problem. This ability to navigate and direct to the relevant source of knowledge mirrors the concept of obtaining the appropriate “context retrieval” in RAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*YIcx_IfSohKhppM5PevUPw.png" /></figure><p>Up until now, Language Models (LLMs) such as ChatGPT are proficient in a broad spectrum of knowledge. While they excel at addressing general inquiries, their performance may falter when dealing with highly specialized domains. For instance, ChatGPT can generate generic code, craft narratives, or propose travel itineraries effectively. However, when confronted with a specific issue related to a particular product, its ability to provide assistance may be limited. This is where Retrieval Augmented Generation (RAG) comes into play, allowing us to incorporate the specific context or information about that product. Much like our analogy with the Neurologist, RAG enhances the model’s capacity to offer <strong>targeted and domain-specific solutions</strong>.</p><blockquote>To simplify, when Language Models (LLMs) like ChatGPT generate an answer (the “G” of RAG) in response to a query, the process involves retrieving (the “R” of RAG) the pertinent context related to that query. This retrieved information is then augmented (the “A” of RAG) to the LLM as input, along with the original query. This integration of generation, retrieval, and augmentation enhances the model’s ability to provide contextually relevant and accurate responses.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*CdL3h5N-4krzSWZ4jImA-A.png" /></figure><p>How is RAG performed?</p><ol><li><strong>Data Retrieval:</strong> The data can be in the form of PDF’s, .txt files, jsons, videos, audio, URL.</li><li><strong>Data Splitting</strong>: This brings us to a fascinating challenge. Consider having a substantial amount of information stored across multiple documents, each potentially lengthy — for instance, 10 PDFs, each comprising 4000 words, documenting resolved issues for a product. When a user poses a query, the task is to identify and match it to the most relevant issue within these documents. Now, if two pdf documents appear to be suitable matches, we’re faced with the dilemma of supplying a considerable amount of data to our Language Model (LLM) — say, 8000 words. However, within this expanse, only 500 words might pertain to the specific issue, while the rest relates to other matters. The question arises: Can we efficiently pinpoint and supply only the relevant chunks, those crucial 500 words, instead of the entire 8000 words? The answer is affirmative. Hence, the need for a method to break down these documents into different parts, allowing us to discern which segment is most applicable to the user’s query. This process, known as document splitting, enables us to divide the document into distinct chunks, facilitating a more precise and focused retrieval of information.</li></ol><p>The splitting of documents into chunks is just not straight forward. This is the most crucial part! We will discuss about them in our future parts of the series but for now just imagine that the text is being split into different chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*neUs748uwOMhYqMFbkoldQ.png" /></figure><p>We can clearly observe from the figure above how we are able to cut it short from 4000 to 400 words of context! That’s a lot of reduction.</p><p>Following document splitting, the next step involves obtaining numerical representations or embeddings for these individual chunks. Subsequently, these embeddings are stored in a vector database. This process allows for efficient retrieval and matching of relevant information based on the numerical characteristics of each chunk. The vector database serves as a repository for these embeddings, facilitating quick and accurate access to the specific content aligned with user queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*lk11_SbVGHX4i7QPG65cOQ.png" /></figure><p>3. <strong>Document Retrieval</strong>:</p><p>Upon receiving a query, let’s take an example: “How to resolve the blue screen error on my laptop?”, the system proceeds to evaluate all the document chunks, identifying the k most relevant ones (where k is a predetermined value, often 5 or 10). The query, along with these k relevant chunks, is then presented to our Language Model (LLM).</p><p>What does this achieve? If the LLM lacks prior knowledge on resolving the blue screen error, it now has access to these pertinent chunks, enabling it to comprehend and formulate a solution to address the query. This approach proves powerful, as it allows the LLM to tap into a wealth of domain-specific information and offer intelligent responses. We can anticipate the widespread adoption of Retrieval Augmented Generation (RAG) solutions across various industries, leading to enhanced capabilities in conventional chatbots and the delivery of more informed and sophisticated responses.</p><p>We’ve understood several parts in separate flow charts, let’s now put all of them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*_69EEogyw7wC2hChfayaMg.png" /></figure><p>I hope we now understood what RAG is, in detail!</p><p>Let’s move on to knowing more about why RAG is highly preferred.</p><p>Benefits of RAG:</p><ol><li><strong><em>RAG vs Finetuning:</em></strong></li></ol><p>Traditional machine and deep learning algorithms were employed to create numerous state-of-the-art (SOTA) models, that rely on labeling or annotation which is an expensive and exhaustive task.</p><p>We didn’t invest all that effort only to develop LLMs and then engage in finetuning once again. RAG is very cost effective. There’s no need to gather extensive data points and fine-tune layers.</p><p>2<strong><em>. Retraining or change in data:</em></strong></p><p>Given that fine-tuning is inherently expensive, dealing with data drift or model drift incurs high costs for retraining the model. In contrast, RAG, operating in real-time predictions, is less impacted by changes in data. While a complete shift in data may influence chunk size and splitting, this remains a minor and affordable adjustment compared to the costly fine-tuning of LLMs.</p><p>Now that we’ve grasped the essence of RAG and its advantages, let’s transition to <a href="https://medium.com/@kaushikjagini95/chat-with-your-podcast-using-rag-part-2-364af68cf707">Part 2</a>, where we delve into the coding aspect of <strong>Chatting with your Podcast</strong>!</p><p><strong>References and Acknowledgments:</strong></p><p><em>Inspired by Harrison Chase’s “Chat with your data” (</em><a href="https://github.com/hwchase17"><em>https://github.com/hwchase17</em></a><em>), I’ve adapted and shaped this concept to suit my objectives.</em></p><p><a href="https://sophiamyang.medium.com/how-to-build-your-own-panel-ai-chatbots-ef764f7f114e"><em>Chatbot panel design by Sophia Yang</em></a></p><p>If you’ve read until here, thank you. I’m sure you and I have something in common.</p><p>Let’s connect on <a href="https://www.linkedin.com/in/kaushik-jagini-b76ba2139">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db15e4772ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read & write multiple images from a directory in Python (skimage, opencv)]]></title>
            <link>https://towardsdev.com/read-write-multiple-images-from-a-directory-in-python-3a0e01e39bc7?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0e01e39bc7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 11:25:54 GMT</pubDate>
            <atom:updated>2024-01-15T02:15:30.870Z</atom:updated>
            <content:encoded><![CDATA[<p>This article focuses mainly on giving that initial direction to make the life easy while working with images in python. Initially, it would be a daunting task to explore two or three libraries and understand how things work in each.</p><p>Hence, I’ve consolidated a code for myself. Wanted to share here the same so that it could help any beginners.</p><h4>Read/Import the images:</h4><p><strong><em>skimage</em></strong>:</p><pre>from skimage import io</pre><pre>img = io.imread(<br>    r&quot;brain.png&quot;)</pre><p><strong><em>opencv</em></strong>:</p><pre>import cv2</pre><pre># to read the image as color</pre><pre>cv2_img = cv2.imread(<br>    r&quot;brain.png&quot;,<br>    1)</pre><pre># to read the image as black &amp; white</pre><pre>cv2_img = cv2.imread(<br>    r&quot;brain.png&quot;,<br>    0)</pre><pre>If neither 0 nor 1 is specified, then the image is read as is. This is helpful when particular batch of images are all of same type. </pre><p>Sometimes, especially while working with MRI scans or 3 dimensional MRI scans, it gets difficult to use open cv or skimage because the data is in the form of dicom. Hence, we can use this library called pydicom to read the dicom images.</p><p><strong><em>pydicom</em></strong></p><pre>import pydicom as dicom<br>ds = dicom.dcmread(<br>    r&quot;0002.dcm&quot;)</pre><h4>Write/Save the Images:</h4><p><strong><em>skimage</em></strong></p><pre>from skimage import io</pre><pre>io.imsave(&quot;write_brain_image.png&quot;, img)</pre><p><strong><em>opencv</em></strong></p><pre>import cv2</pre><pre>cv2.imwrite(&quot;write_brain_image.jpg&quot;, img)</pre><p><strong><em>pyplot</em></strong></p><pre>from matplotlib import pyplot as plt</pre><pre>plt.imsave(&quot;write_brain_image.jpg&quot;, img)</pre><pre>#This is especially used when we make plots of images dynamically and want to save them offline.</pre><p><strong><em>tifffile</em></strong></p><pre>import tifffile</pre><pre>#This library is highly useful while working with tiff files.</pre><pre>tifffile.imwrite(&quot;write_brain_image.tiff&quot;, img)</pre><p>Alright, we have seen enough of reading and writing the images. Now let’s see how do we visualize the loaded image.</p><p><strong><em>skimage</em></strong></p><pre>import matplotlib.pyplot as plt</pre><pre>img = io.imread(<br>    r&quot;brain.png&quot;,<br>    as_gray=True)</pre><pre>plt.imshow(img)</pre><p>To change the color of the display while visualizing, can use the parameter cmap as shown below:</p><pre>plt.imshow(img, cmap=&quot;hot&quot;)</pre><pre>plt.imshow(img, cmap=&quot;jet&quot;)<br>plt.imshow(img, cmap=&quot;Blues&quot;)<br>plt.imshow(img, cmap=&quot;nipy_spectral&quot;)</pre><p><strong><em>opencv</em></strong></p><pre>import cv2</pre><pre>img = cv2.imread(<br>    r&quot;brain.png&quot;<br>)</pre><pre>cv2.imshow(&quot;pic&quot;, img)</pre><pre>cv2.waitkey(0)<br>cv2.destroyAllWindows()</pre><pre><br>## Do not ever forget to add the waitkey or destroy all windows lines as shown above. If not added, open cv runs an infinite loop to open the image in a separate window.</pre><h4><strong><em>Read Multiple files from a directory:</em></strong></h4><p><strong><em>glob</em></strong></p><pre>import glob<br>from skimage import io</pre><pre>file_list = glob.glob(<br>    r&#39;Images\*.*&#39;<br>)</pre><pre>print(file_list)</pre><pre>[&#39;C:\\Users\\Desktop\\Projects\\ImagePractise\\img_practise\\Images\\brain_001.jfif&#39;,<br> &#39;C:\\Users\\Desktop\\Projects\\ImagePractise\\img_practise\\Images\\brain_002.jfif&#39;]</pre><pre># Once all the paths are retrieved, read the images one by one in a loop.</pre><pre>my_list = []</pre><pre>for file in file_list:<br>    im = io.imread(file)<br>    my_list.append(im)</pre><p><strong><em>os.listdir()</em></strong></p><pre>import os</pre><pre>path = r’C:\Users\Desktop\Projects\ImagePractise\img_practise\Images’</pre><pre>for image in os.listdir(path):<br> print(image)</pre><pre>brain_001.jfif<br>brain_002.jfif</pre><p><strong><em>os.walk()</em></strong></p><p>This is my favorite while working with images in multiple folders.</p><p>It creates a generator object which iterates through all the folders present in the path and gives us the path for the desired extension. This is very useful because a dataframe of the paths along with corresponding file locations can be then used anytime.</p><pre>import os</pre><pre>for root, dirs, files in os.walk(<br> r”C:\Users\kaushik.jagini\Desktop\Projects\ImagePractise\img_practise\Images”<br>):<br> path = root.split(os.sep)<br> print(path)</pre><pre> print(((len(path) — 1)) * ‘==’, os.path.basename(root))<br> for file in files:<br>   print(len(path) * ‘====’, file)<br>   print(os.path.dirname(os.path.realpath(file)))</pre><pre>[&#39;C:&#39;, &#39;Users&#39;, &#39;kaushik.jagini&#39;, &#39;Desktop&#39;, &#39;Projects&#39;, &#39;ImagePractise&#39;, &#39;img_practise&#39;, &#39;Images&#39;]<br>============== Images<br>================================ brain_001.jfif<br>C:\Users\kaushik.jagini\Desktop\Projects\ImagePractise\img_practise\Untitled Folder<br>================================ brain_002.jfif<br>C:\Users\kaushik.jagini\Desktop\Projects\ImagePractise\img_practise\Untitled Folder</pre><p>That’s it. It really is that easy to read/write images in python which is exactly why I love python. It makes our job easier.</p><p>If you’ve read until here, thank you. I’m sure you and I have something in common.</p><p>Let’s connect on Linkedin:</p><p>https://www.linkedin.com/in/kaushik-jagini-b76ba2139</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0e01e39bc7" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/read-write-multiple-images-from-a-directory-in-python-3a0e01e39bc7">Read &amp; write multiple images from a directory in Python (skimage, opencv)</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Digital Minimalism should be your top priority]]></title>
            <link>https://kaushikjagini95.medium.com/why-digital-minimalism-should-be-your-top-priority-a689a5f46b5c?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a689a5f46b5c</guid>
            <category><![CDATA[lifehacks]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[minimalism]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 10:08:44 GMT</pubDate>
            <atom:updated>2021-08-26T10:08:44.738Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me start off with something that makes a lot of sense in the current digital era:</p><blockquote>You are not the average of the 5 people you spend the most time with. You are the average of the 5 apps that you use the most.</blockquote><p>In this digital era, where people talk to their phones more than the person next to them, it’s important to pay conscious attention to where our time is going. You can pick up your phone just like that and instagram/facebook or any app that works on user engagement more than user experience can hook you up for hours with it’s never ending intelligent recommendation.</p><p>This is just bad! I personally feel there’s a cc-camera type of device out there that’s continuously screening my thoughts.</p><p>Hey, isn’t it great?? I’m only getting to see what I’m interested in. Why the fuss?</p><p>Well, it is the most useless thing. It <strong>drains your time</strong> without your knowledge. It <strong>drains your mental capacity</strong>. Let me give you an example, you randomly had a thought about something say a trip to a beach city. You didn’t really have a serious intention to travel but it was just one though out of the million other thoughts we go through each day. However, you take one step ahead and search about the beach cities near by your place and check out few photos and close it. This moment never ends with you closing the chrome browser. The thought never ends there. These applications get the information that you have a thought of going to a beach from your cookies, and start recommending. You open youtube, there’s a beach recommendation. Instagram yes. Facebook yes. It’s everywhere. Being a developer, I’m seeing such ads on the stack overflow page too.</p><p>The reason to point this out is that, what was a normal thought amongst million other thoughts, <strong>the moment you digitalized the thought</strong> by searching it on the web, it is amplified. This is just totally unnecessary.</p><p>While there are 100’s of apps that track the time spent on social media and send alerts, well, it’s not about how much time you’ve spent on the social media but about how many times are you picking it up? So you spend an hour a day on digital media but how many pick ups?</p><p>While it’s important to keep in touch with the current trends and people through digital/social media, just ask yourself <strong>is it really necessary to use/open those applications for 10 times a day?</strong> We can just do fine with a weekly twice or thrice catch up with friends or the current trends.</p><p>Don’t let these apps steal your valuable time. The key is to cut down number of times the phone is being picked up.</p><blockquote>The number of times you pick up a phone is directly proportional to your distraction quotient.</blockquote><p>Be conscious of how or where the time is going. It’s totally okay even if the day is boring, try to pass time with some other means. In fact, put yourself into the shoes of being bored. You’ll eventually find a hobby.</p><p>In conclusion, by using digital medium as a means to pass time:</p><p><strong>1. There’s a device screening your thoughts.</strong></p><p><strong>2. Negativity is amplified.</strong></p><p><strong>3. Your time is stolen.</strong></p><p>Few immediate things that you can start practising, these are tangible and practical steps that can help achieve the goal:</p><ol><li>Start using any web search engine that is <strong>not hungry for cookie data</strong>. Ex – DuckDuckGo (I’ve been using this since a year now)</li><li>Sign off from your Youtube accounts and just use the browser on your phone for Youtube. Don’t let Youtube decide how you are going to spend an hour in your day ( if you can’t sign off, then at least pause the search and watch history in the settings)</li><li>Do not use remember me option on Instagram, Facebook, Linkedin etc. make sure you got to type in each time you pick up your phone and use it. Log off immediately once you are done.</li><li>Keep cleaning your browser cache periodically. (Ideally, once every 3 days if it’s your work laptop, otherwise everyday if it’s your phone or personal laptop)</li><li>Be conscious of how many times in a day are you picking up the phone. This explains how we are part of a distracted world.</li><li>Stop being available for the notifications and turn them off for all your apps unless the extremely important ones like the bank related apps. Use them when you need not when they notify you.</li></ol><p>Be mindful. Follow a <strong>minimalistic approach towards digital media</strong>. I’ve followed it and reaped numerous benefits. I’ll probably write another post on how it helped me but I’ll confine this post to the “why” part of practicing digital minimalism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a689a5f46b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Important Lessons From My Fitness Journey]]></title>
            <link>https://medium.com/in-fitness-and-in-health/lessons-from-my-fitness-journey-7bfae03911ad?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bfae03911ad</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[fitness]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 02:51:03 GMT</pubDate>
            <atom:updated>2020-12-09T14:46:50.039Z</atom:updated>
            <content:encoded><![CDATA[<p>Before getting into the matter, a short piece of advice about consuming information via blogs.</p><p>There are two ways to consume information via blogs:</p><ol><li>Quickly skim through the headings/bullet points.</li><li>Read the entire article.</li></ol><p>The problem with the first approach is that <strong>the information is just as gone as you gain</strong>. I recommend the second approach if you are looking to expand your knowledge. Not just for this post but for any information you are interested to consume.</p><p>Okay, enough of that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q14yZlsjZZ5vLIGrZ9cGLA.jpeg" /><figcaption>Image source: Google</figcaption></figure><p>Coming from a school where the students were brutally divided into sections only based on the grades, did not have the chance to learn any of these things from the teachers at school/college. However, fitness has been that teacher for me.</p><p>While there are obvious benefits if you exercise regularly, following are the lessons that I’ve inadvertently picked up in the process.</p><h3><strong>1. The why should be clear</strong></h3><blockquote>Something that majority of them miss out! The clarity of why behind doing a thing is important. If you only start your fitness journey to reduce your weight or bulk up, it’s going to be temporary. You will stop working out once you achieve your goal. There are very few who continue to go above and beyond their goals. However, if the why is to only get better with each passing day, sky is the limit. Similarly, take any aspect in life for example — career, if one does not have the clarity, they might get through but not in the way they would be proud of. Once we get the clarity of what needs to be done and why, how is always the easiest part.</blockquote><h3><strong>2. Let your younger self be the inspiration </strong>(<strong><em>my personal favorite</em></strong>)</h3><blockquote>I’m sure everyone must have listened to speeches from their favorite people and got inspired in some ways. The next time you need a push, make sure you look back at yourself and not some random talk on Youtube! Now is the time to analyze how you, in the future, would be inspired by you, now! Act accordingly. When you are into 30’s, the goal should be to look back at your 20’s for some inspiration.</blockquote><h3><strong>3. Always take the onus</strong></h3><blockquote>The common reason that people give as an excuse is that they don’t have enough time. The habits won’t change unless you stop making excuses and start taking up the onus. Say it with me.. “i’m responsible for everything that happens in my life.” It took me some time to get used to this but when I finally started to have this mindset, I was able to make time for my fitness. I soon incorporated this same mindset to other aspects of life and now I have enough time for my friends, books, binge watching, work and for the travel too. :)</blockquote><h3><strong>4. Either all in or all out never works</strong></h3><blockquote>A couple of years back, during an intense gym session, I was asked by the trainer to do a plank for 3 minutes. Either the scale up(advanced version) or the scale down(beginner version). I chose to do the former, because you know, being ambitious. I was able to do it for only 2 minutes and I gave up. When I questioned myself as to why I did not pick the scale down version? The answer is that I’ve always been the all-in or all-out kind of person. But then, my trainer said it’s not a good attitude <strong>if you are aiming to achieve something over a long period of time</strong>. He said, “first be okay with not being perfect and that itself will get you to perfection”.</blockquote><h3><strong>5. Every effort matters, trust the process! (my second favourite :D)</strong></h3><blockquote>I get it. We all need instant gratification. At times, we are left with no results despite putting in a lot of efforts. Trust me, everything counts. 8 years back I went to the gym for the first time for about 6 months and left it because I was not bulking up big time. But those 6 months of training gave my body a good shape. Which, in turn, is helping me now in more ways than I could think of. Back then, I didn’t even realize if it mattered. The same is with whatever you do. Every effort counts. <strong>Trust the process! Sooner or later the results will come, definitely!</strong></blockquote><h3><strong>6. Be grateful</strong></h3><blockquote>Honestly, a couple of years back I used to be the bug lazing around the house all the time. Suddenly, due to a few medical issues I had to go through a surgery and was advised by the doctor to not exercise for 6 months. And that’s when I missed sweating out in the gym. I didn’t realize before how grateful I were to have the energy, time and opportunity to workout. Once I realized it, there’s no going back! Now I look at my weekly fitness reports and just be grateful!</blockquote><blockquote>Isn’t it the same with other things in life? When was the last time you thanked life for everything you have? Make some time, pick a paper and write down all that you are grateful for(it can be about things, friends, family etc). Additionally, question yourself as to how would it be if you did not even have them in the first place.</blockquote><h3><strong>7. Life is a game of you vs your will power</strong></h3><blockquote>Every ted speaker or a monk asks to clean up your bed first. But why? Because it is the first instance in your day where your will power is challenged. When you successfully accomplish it, that’s a major booster to your will power and it can shape your day. Similarly, workout challenges your will power throughout the day. To workout everyday, body needs good rest. Good rest needs good sleep. Good sleep requires sleeping on time. Which eventually means you can’t watch that extra episode on Netflix etc etc etc.. your will power is challenged throughout the day. Hence, workout improves your will power exponentially. <strong>Resist your excuse like you resist a rep at the gym.</strong></blockquote><h3><strong>8. Motivation dies, discipline lives on</strong></h3><blockquote>Never make a decision when you are highly motivated by something. Yes, you read it right! But why? Because it dies!! The blame game will be back cursing why you made that choice in the first place. Hence, never trust your motivation quotient. Practically speaking, if you really are motivated by something and want to do it, wait for a day or two and then do it. How badly you want a thing is determined by what you do when you have zero motivation levels. Motivation can come and go anytime but discipline will stay with you. It will stay with you for so strong that it becomes a habit. This is all you need. It will take you to places you’ve never dreamt off! (figuratively :p)</blockquote><p>I hope you enjoyed reading. If you also have something similar to share, do so. I’ll be definitely interested to know. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jwCo9Dygzz7IR0Ji.jpeg" /></figure><p><strong>You just read another post from In Fitness And In Health:</strong> a health and fitness community dedicated to sharing knowledge, lessons, and suggestions to living happier, healthier lives.</p><p>If you’d like to join our newsletter and receive more stories like this one, <a href="https://scottmayer.substack.com/"><strong>tap here</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bfae03911ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/in-fitness-and-in-health/lessons-from-my-fitness-journey-7bfae03911ad">8 Important Lessons From My Fitness Journey</a> was originally published in <a href="https://medium.com/in-fitness-and-in-health">Second Nature (formerly In Fitness &amp; In Health)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do We Need an Intercept in Regression Models?]]></title>
            <link>https://medium.com/swlh/why-do-we-need-an-intercept-in-regression-models-76485a98d03c?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/76485a98d03c</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[intercepts]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 04:04:06 GMT</pubDate>
            <atom:updated>2024-01-15T02:15:53.936Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s understand the intuition behind the role of an intercept in regression models.</p><p>The caveat for this article is that you are familiar with the simple equation of a straight line <strong>y = mx + c</strong>.</p><p>However, to understand how it plays a role in regression problems, the familiarity with regression models such as linear regression is required.</p><p>Well, there are way too many articles to help us understand what regression models are and how linear regression’s been traditionally popular. However, if you want to understand the same at a granular level, there are very few. Furthermore, there’s no one stop place to understand what’s the role of an intercept in linear regression. Which is exactly my why for writing this.</p><p>In this post, I will start off with explaining how it plays a role geometrically and then move on to develop the intuition behind the role of an intercept. I will conclude by giving a few examples after which <strong>you will be able to tell if intercept is required or not.</strong></p><p>Alright, let’s dive in.</p><p>Consider the equation below:</p><p>Y = 3x. (A line with no intercept)</p><p>For the above equation, if:</p><p>x = 0 then y =0;</p><p>x=1 then y=3;</p><p>x=2 then y =6;</p><p>x=3 then y = 9 and so on…</p><p>Let’s plot the above co-ordinates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*HzNCURrSSi0DHDLxEkMhHA.png" /></figure><p>The key observation from the figure above is that the line passes through origin.</p><p>If you do not have the intercept, the line will <strong>ALWAYS</strong> pass through the origin.</p><p>Okay, so what happens if the line always pass through origin??</p><p>If I ask you to join point A and B in the figure below, you can simply draw a straight line that can pass through them. ( On one condition — This line should pass through the origin)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*MEqIUWZ0nOCsUeXmzu2Mgw.png" /></figure><p>Again, what If I ask you to draw a line that can pass through C and D in the figure below? ( Same condition — the line should pass through the origin)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*eSNR8hxylIAfZIPUpP-4ig.png" /></figure><p>There’s no possibility. But, if you do not place that extra condition, then you can simply draw as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*btQM34w-gskEZtCxeKxi-Q.png" /></figure><p>So, what did just happen here? If we put an extra condition that the line should pass through the origin, there are certain situations where we won’t be able to draw a line to join two points. But, if we remove that condition, we can.</p><p>That condition is nothing but the intercept.</p><p><strong>Can</strong> pass through origin — A line <strong>without</strong> intercept.</p><p><strong>Cannot</strong> pass through origin — A line <strong>with</strong> intercept.</p><blockquote>Having an intercept gives our model the freedom to capture ALL the linear patterns while a model with no intercept can capture only those patterns that pass through origin.</blockquote><p>Oh, that’s great! Now we understood how intercept plays a role in capturing the patterns.</p><p>But how do we interpret it? What can we infer from the linear model equation that the intercept value is 0.745 or 0.2 or -0.34 etc?</p><p>Do we always need to have an intercept?</p><p>Well, let’s understand the above two with examples.</p><p><strong>Example — 1:</strong></p><p>Consider you are working for any ed-tech startup. Since there is a lot of marketing campaign going on right now, you want to predict the number of course enrollment based on the marketing campaign. So the dependent variable is <strong>course_enrollment</strong> and the independent variable is <strong>marketing</strong>.</p><p>The equation here is,</p><p>course_enrollment = (slope * marketing) + intercept. [of the form y=mx+c ]</p><p>If the intercept = 0,</p><p>Y = (slope*marketing)</p><p>Now, what if the marketing campaign was stopped i.e marketing = 0, will the course enrollment be totally 0? Nope, there will definitely be a minimum number of enrollments. <strong>This, in other words indicate the trend</strong>. What will be my sales if I stop marketing right now? This question can be answered only if we use intercept. Hence, we definitely need to have intercept in this case. Now you know what it means for an intercept with a value <strong>0.745. </strong>For this example, the intercept value of 0.745 indicate the trend when all other variables are 0.</p><p><strong>Example — 2:</strong></p><p>In this second example consider you are predicting the number of people who are cured from the coronavirus based on their age. Hence, the equation will be -</p><p>Cured = (Slope*age) + intercept</p><p>In the previous example we went ahead with the condition that intercept = 0 and then proved that it cannot be 0. Here we do vice versa.</p><p>The condition is, the intercept is not equal to 0.</p><p>In such cases, what if the input to the equation is such that the age = 0?</p><p>Since age = 0 and intercept is not equal to 0, it does not make sense that with age 0, number of people cured is a non-zero.</p><p>Hence, we do not require intercept in such cases.</p><p>That’s how crucial is the role of an intercept! I hope you got a better idea of it.</p><blockquote>Note — If and only if you are confident that the output should be zero if all of the input variables are 0, only then can you get rid of using an intercept. Ideally, it’s preferable to always and always use an intercept in the regression models.</blockquote><p><em>Finally, feel free to add in any points I might have missed. Happy Learning!</em></p><p>If you’ve read until here, thank you. I’m sure you and I have something in common.</p><p>Let’s connect on Linkedin:</p><p>https://www.linkedin.com/in/kaushik-jagini-b76ba2139</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76485a98d03c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-do-we-need-an-intercept-in-regression-models-76485a98d03c">Why Do We Need an Intercept in Regression Models?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The paradox of mental health.]]></title>
            <link>https://kaushikjagini95.medium.com/the-paradox-of-mental-health-ed459967d5af?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed459967d5af</guid>
            <category><![CDATA[depression]]></category>
            <category><![CDATA[pandemic]]></category>
            <category><![CDATA[stress]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[anxiety]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 04:06:32 GMT</pubDate>
            <atom:updated>2020-08-12T04:06:32.866Z</atom:updated>
            <content:encoded><![CDATA[<p>Crisis is an opportunity that cannot be wasted!</p><p>Such has been the current trend due to the worst ever pandemic that’s hit the planet in the last 100 years. We all are staying home more than ever. There’s no chance of happily going to a bar on a Friday night or as simple as watching your favorite movie in a nearby theatre or for a matter of fact even have a peaceful visit to a temple/church/mosque. With no absolute possibility to burst the stress off, people, as I observe, find this as an opportunity to focus on mental health more than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*62Bp7l20oMfhWPtzTuRA5Q.jpeg" /></figure><p>While it’s a positive sign, I am writing this to express my concern over the way it’s being handled.</p><p>Imagine the vaccine for covid is really out and things get back to normalcy. If you are someone like me, the first thing you do is plan to go on a good holiday. Let’s just assume that’s exactly what you are doing now at this very moment where in you have a flight to catch in the next one hour. Upon reaching the airport, you make sure that there are no items which are made of glass or any other fragile material in the check-in baggage. Even if you happen to have a bag with one, you make sure to inform the concerned person to apply a <strong>FRAGILE </strong>tag. By doing so, you <strong>accept </strong>that the glass is easily breakable.</p><p>We do this because even small amounts of mishandling can break the glass. Hence, by adding the tag FRAGILE, we are making sure that the bag will not be mishandled. In fact, we expect it to be handled with extra care. I personally find nothing wrong here. This only looks good as long as you apply to objects. But I see the same thing’s happening now with people and mental health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*_sF-jbxy29KbXWZMbL4AmA.png" /></figure><p>In the process of taking care of mental health, many are involuntarily adding a FRAGILE tag to it. Similar to our glass example stated above, the minute the FRAGILE tag is added to mental health, we already <strong>accept </strong>that this can be easily breakable too. While it’s one thing to take good care, <strong>it’s inappropriate to give more attention to it than required</strong>.</p><p>Does it mean we all should stop prioritizing mental health? No! That’s not the crux of my perspective. I myself am a firm believer in becoming mentally fit. I prioritize it enough such that I meditate regularly and even maintain a diary to often pen down my emotions. The point is that, instead of treating it as a fragile object in an overly cautious way, think of it as a resource. A resource that’s eager to get tough and better everyday. <strong>Having the courage that it can be repaired even if it breaks </strong>is extremely crucial.</p><p>The mental health quotient can improve only when one believes that there is a possibility that it can improve.<strong><em> By adding the fragile tag, I am not sure if people believe in that possibility anymore and that’s the major concern</em></strong>. Do not add a fragile tag and get succumbed to every little problem. It is okay to be cautious but it drains you in more ways than you can think of if you are overly cautious. Treat it with priority but don’t take it so very seriously to an extent that people out there are now trying to commercialize the very concept of mental health.</p><p>You might ask..<em> ‘hey kaushik, are you saying that by not giving </em><strong><em>extra importance</em></strong><em> to mental health, we can indirectly benefit out of it?’</em></p><blockquote>Yes, that’s exactly my point. You can’t protect yourself from hardships. You can only be prepared for it.</blockquote><p>As they say mindful living is the way forward, let it flow. Let there be problems. What ever is it that you are currently going through is not the only problem that you might face for the rest of your life. This is just another one. Learn to deal with it, get better in the process, and that’s how you <strong>prepare</strong> yourself for the next one.</p><blockquote>The bottom-line is that, mental health, is not about taking that extra care and reaching to a state of nirvana. But, to be open and okay for hardships because you are already strong enough mentally in handling them.</blockquote><p>Do let me know your thoughts. I’ll be really interested to discuss about it. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed459967d5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The power of Aspect Based Sentiment Analysis]]></title>
            <link>https://medium.com/swlh/the-power-of-aspect-based-sentiment-analysis-18c3908ac53d?source=rss-e2a0771b153c------2</link>
            <guid isPermaLink="false">https://medium.com/p/18c3908ac53d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Kaushik Jagini]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 17:43:01 GMT</pubDate>
            <atom:updated>2020-11-24T06:29:23.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>The power of Aspect Based Sentiment Analysis (with code)</h3><p>I’ve ever been a silent reader here. This time I decided to write on this topic because I could not find a comprehensive guide on how Aspect Based Sentiment Analysis can be done. So, hoping that this could serve the purpose.</p><p>The first half of this article consists of the general intuition and the remaining half is of the technical details with code.</p><p>Alright! Let’s get started.</p><p>Well, by now, there are thousands of firms round the globe using Sentiment Analysis to understand the voice of the customer. In my personal opinion, it’s ubiquity will only increase with time.</p><p>To those who are not aware of sentiment analysis, in a nutshell it is nothing but the review/feedback which is in the text form is analysed and classified with a sentiment as <strong>positive/negative</strong>. Today, we will explore it’s next level of analysis which is — <strong><em>Aspect Based Sentiment Analysis(A.B.S.A)</em></strong>.</p><p>To help give you an overview of <strong><em>A.B.S.A</em></strong>, below is an example of the same:</p><p><strong>E.g</strong> :</p><blockquote>Consider this review for the famous show ‘YOU’ on netflix:</blockquote><blockquote>“<strong>I really liked the <em>narrative style</em> of the show. The <em>acting was amazing</em>. It was unique in the present era of TV shows. However, the <em>climax could have been better</em>.</strong>”</blockquote><p>I ran the sentiment analysis model with the help of the library <strong><em>textblob </em></strong>and it classified the review on a whole as <strong>POSITIVE</strong>.</p><p>That’s good. By reading that review anyone can say that it was more of a positive feedback. This’s where the traditional sentiment analysis ends with an overall view if a review is positive or negative.</p><p>Let’s see how would <strong><em>A.B.S.A</em></strong> help in achieving better results.</p><p>The same review gave the results as shown below using <strong><em>Aspect Based Sentiment Analysis</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5B9eJUhhA_f84FjhbCSXw.png" /></figure><p>How cool is that? It lets us know at a granular level which aspect of a review is positive or negative. Using the first approach where it was analysed on a whole as a positive sentiment, would have missed out on the information about the “climax ”which is the negative aspect here. Moreover, there would be no clear information as to what in specific are the positive drivers.</p><p><strong>The advantages of <em>A.B.S.A</em></strong>:</p><ul><li>In this digital era, there are thousands of reviews pouring in every day. It is a humongous task to read through all of them. <strong><em>A.B.S.A</em></strong> helps achieve this objective by extracting only the important aspects.</li><li>Majority of the users write reviews in a constructive style which in turn yields the sentiment as positive though there is negative element in it (as shown above in the example of “YOU” review ). Hence, there is a possibility of missing out on crucial information.</li></ul><p>I hope you now understood the “why” behind the <strong><em>A.B.S.A</em></strong>.</p><p>In simple words,</p><blockquote>The idea to understand what in specific the users are trying to communicate via reviews/feedback? If they are happy, what is the top driver that they are happy about? If they are not, then what is the top driver that is affecting the user’s experience?</blockquote><p>Appropriate action can be taken only when these are understood at a granular level. This helps in improving the quality of Business Intelligence.</p><p>Below is the solution I’ve implemented:</p><blockquote>In a nut shell, I have used the spacy’s linguistic abilities to understand the underlying grammar of the language used in writing the reviews and then, I have written few text based rules to extract the aspects.</blockquote><p>Don’t worry if it sounds confusing. Read along and you will find it really easy after going through an example.</p><p>Okay, so imagine 2 of your close friends bought the same product on Amazon.</p><p>If you ask them to write a review about the product, there could be 2 different styles of reviews. The vocabulary used by each of them might be <strong><em>UNIQUE</em></strong>. But here’s the catch, the underlying parts of speech of the vocabulary will be <strong><em>COMMON </em></strong>across the reviews. This, in turn, helps in capturing the generic linguistic pattern.</p><p>I hope it makes sense now. If not, the below example will make it crystal clear.</p><p>Let’s just consider that the below are the reviews given by your friends:</p><p><strong>Friend 1</strong>: The product design was really comfortable but the product quality was extremely annoying.</p><p><strong>Friend 2: </strong>The product design was amazing but overall it was a disappointing buy.</p><p>Following are the aspects extracted for the above two reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*0CCVV0ySuNT5Ha1xj8ZiNw.png" /></figure><p>From the results above, I can confidently say that the users are happy with the design of the product but they are not happy with it’s quality. Hence, the emphasis can be given to improve the quality while maintaining the same consistency with the design. I personally feel this level of granularity is insightful and improves the ability to take better decisions.</p><p>Let’s understand the linguistic pattern for each of these aspects :</p><blockquote>1.) disappointing buy: [disappointing — <strong>Adjective</strong>, buy — <strong>Noun</strong>]</blockquote><blockquote>2.) design amazing: [design — <strong>Adjective</strong>, amazing — <strong>Noun</strong>]</blockquote><p>What is the pattern here? Extract the aspect from the text if a <strong>noun </strong>is followed by an <strong>adjective</strong>.</p><p>Below is a simple python code that will extract the aspects for the above two:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82fcc62f0ce01f490e8a51040789481e/href">https://medium.com/media/82fcc62f0ce01f490e8a51040789481e/href</a></iframe><p>How easy was that? Similarly, the aspects for the remaining reviews were extracted using the below rule:</p><blockquote>1.) product design — really comfortable:</blockquote><blockquote>(Product — NOUN, design- NOUN, really — ADV, comfortable — ADJ)</blockquote><blockquote>2.) product quality — extremely annoying.</blockquote><blockquote>(Product — NOUN, quality — NOUN, extremely — ADV, annoying — ADJ)</blockquote><p>What is the pattern here?</p><p>Extract the aspect from the text if an <strong>adjective </strong>is followed by an <strong>adverb </strong>followed by a <strong>compound noun(noun followed by a noun)</strong>.</p><p>Below is the code snippet of the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/347fae9486fcdc62197d38909442f103/href">https://medium.com/media/347fae9486fcdc62197d38909442f103/href</a></iframe><p>I am sure you must be wondering how dynamic is this approach? How many rules would you write to capture all the the aspects with thousands of reviews.</p><p>It is an honest doubt. When I started doing this project, I didn’t think I would go ahead with this keeping in mind the dependency of the rules on training data. My question was, <strong>what if we have a data point in real time which exhibits pattern that was not part of the training sample used to write the rules?</strong></p><p>The solution is simple:</p><ul><li>If you followed this article thoroughly, you must have understood that the vocabulary might be different but the underlying grammar pattern is hardly any different.</li><li>There would certainly be a few aspects left out. Treat this in terms of accuracy — not even the regular regression/classification problems using the deep neural networks would give an accuracy of 100%. Even here, there will definitely be outliers the rules can’t account for. However, majority of the aspects can be extracted.</li></ul><p>In my project, I have used about 14 rules based on a sample of 100 reviews as my training set and I was able to extract 1500 aspects from 800 reviews. I can’t share the code due to the compliance reasons but I’m sure you have understood by now about how easy it is to extract the aspects.</p><p><strong>The next part of this article explains a bit more of technical details. You can reach to the end of this article <em>if you want to skip and relax!</em></strong></p><h4><strong><em>Few steps to keep in mind that can help improve the results</em>:</strong></h4><ol><li><strong>Stop Words</strong> : They play a very important role in extracting the aspects. Sometimes the parts of speech tagging can create a lot of ambiguity. &gt;<strong>Example</strong>: Words like “actually”, “basically”, “initially” etc. People use them frequently! Since these are the Adverbs, it might create noise in the aspect extraction. Hence, it is important to carefully curate the stop-words which in turn can give us neat aspects without the noise.</li><li><strong>Tokenize the sentence</strong>: Each review/feedback obviously contains more than one sentence. When the special characters are removed, the entire review will now become a single sentence which creates ambiguity. Hence, tokenize the text into sentences and then extract the aspects from each sentence.</li><li><strong>Aspect should make sense</strong>: At times, you get aspects in such a way that verb-adverb or noun-adjective (i.e) the important words are very next to each other without the supporting stop words. This way, it is not that intuitive for the readers to grab much information from the aspect.</li></ol><p><strong>Example</strong>:</p><p>Consider this review “<strong>I was very happy with the communication throughout</strong>.” Aspect extracted post removal of stop words is — “<strong>very happy communication</strong>”.</p><p>Is it intuitive enough? Could be! But imagine reading 100’s of aspects with broken English. Hence, extract the text between the first and last word of the aspect. This will result in sensible aspects such as “<strong>very happy with the communication</strong>” instead of “<strong>very happy communication</strong>”.</p><p>Isn’t this better?</p><p>Below is the code of the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8657c7e9b834e240439d2b719adf2698/href">https://medium.com/media/8657c7e9b834e240439d2b719adf2698/href</a></iframe><p>4.) <strong>Remove Redundant Aspects</strong>:</p><p>There could be few redundant aspects like <strong>[“narrative style”, “liked narrative style”, “really liked narrative style”].</strong></p><p>To overcome this problem, I have written the below function that removes these similar aspects and retains the most important one. <strong>(Note : This can also be used to remove the redundant bi grams from the tri-grams)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/111cd4a9e3e1eb82c49f57139edcc705/href">https://medium.com/media/111cd4a9e3e1eb82c49f57139edcc705/href</a></iframe><blockquote>That’s it!!</blockquote><blockquote>With that said, we have now understood the power of Aspect Based Sentiment Analysis and how can it be leveraged to get valuable insights from the text data.</blockquote><blockquote>Thanks for reading and I hope you found this article useful. Do let me know in case of any doubts, I will be happy to answer!</blockquote><blockquote>Since this is my first article on Medium, I would appreciate your feedback which in turn would help me in my future posts.</blockquote><blockquote>Have a good day! Happy Learning! :)</blockquote><p>We can connect on Linkedin — <a href="https://www.linkedin.com/in/kaushik-jagini-b76ba2139">https://www.linkedin.com/in/kaushik-jagini-b76ba2139</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18c3908ac53d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-power-of-aspect-based-sentiment-analysis-18c3908ac53d">The power of Aspect Based Sentiment Analysis</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>