<?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 Preethi Prakash on Medium]]></title>
        <description><![CDATA[Stories by Preethi Prakash on Medium]]></description>
        <link>https://medium.com/@preethi_prakash?source=rss-c072bb0dc6ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5FClFiTRdS2wRdoTA1yU2Q@2x.jpeg</url>
            <title>Stories by Preethi Prakash on Medium</title>
            <link>https://medium.com/@preethi_prakash?source=rss-c072bb0dc6ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:33:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@preethi_prakash/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[Cleaner Git History, Zero Effort]]></title>
            <link>https://medium.com/@preethi_prakash/cleaner-git-history-zero-effort-1229665aed9e?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/1229665aed9e</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 16:55:02 GMT</pubDate>
            <atom:updated>2025-09-02T16:55:02.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_vz00ozkyPMRB4bC" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I first started working on side projects, my Git history looked like a teenager’s text messages:</p><pre>wip  <br>fix stuff  <br>update again  <br>final final (this time fr)</pre><p>Yeah… not exactly inspiring.</p><p>I knew commit messages were supposed to tell the story of a codebase, but when I was in the middle of coding, the last thing I wanted to do was stop and craft the perfect sentence. So I’d just type something quick, hit save, and move on.</p><p>Fast forward a few months, and going back through old commits felt like reading hieroglyphics. What did <em>“update again”</em> even mean? Which bug did “fix stuff” actually fix? I had no clue.</p><p>That’s when it hit me: writing meaningful commit messages isn’t just good practice, it’s essential if you want your future self (or teammates) to understand the journey your code has taken.</p><p>But here’s the problem: even knowing that, I still wasn’t doing it.</p><p>So, instead of forcing myself to “try harder,” I decided to automate the whole thing.</p><p>Now, whenever I run git commitMy editor doesn’t open with a blank message. It opens with a clean, AI-generated commit message, written in the <strong>Conventional Commits</strong> style.</p><p>It’s like having a helpful teammate who watches what I changed and then writes the message for me. If I want to tweak it, I can. But 90% of the time, I just hit save and move on.</p><p>No more “fix stuff.” No more “wip.” Just clear, consistent commit history without the guilt trip.</p><h3>How It Works</h3><p><strong>Git Hook (</strong><strong>prepare-commit-msg)</strong></p><ul><li>Runs automatically every time you commit.</li><li>Calls a Python script that generates the commit message.</li></ul><p><strong>Python Script (</strong><strong>scripts/ai_commit_msg.py)</strong></p><ul><li>Reads the staged diff (git diff --staged).</li><li>Sends it to OpenAI (gpt-4o-mini).</li><li>Writes the AI-generated message directly into .git/COMMIT_EDITMSG.</li></ul><p><strong>Environment Variables (</strong><strong>.env)</strong></p><p>Keeps your API key and settings safe and configurable:</p><pre>OPENAI_API_KEY=&quot;sk-xxxx&quot;<br>OPENAI_COMMIT_FALLBACK=&quot;1&quot;</pre><h3>Example</h3><p>Let’s say you staged the following change:</p><pre>def main():<br>  print(&quot;Hello, World!&quot;)</pre><p>When you commit, Git will open the editor with something like this:</p><pre>feat(test): add hello world script<br><br>This commit introduces a new Python script that prints &quot;Hello, World!&quot; <br>when executed.</pre><h3>Why This Is Useful</h3><ul><li><strong>Automation</strong> → Stop wasting brainpower on typing “update” or “fix.” The AI does the heavy lifting for you.</li><li><strong>Consistency</strong> → Every commit follows the <strong>Conventional Commit</strong> standard (feat, fix, docs, refactor, etc.), which makes your history cleaner and easier to navigate.</li><li><strong>Flexibility</strong> → Not happy with the suggestion? You can always tweak it before saving. The AI gives you a starting point.</li></ul><h3>Setup Guide</h3><p>Here’s how to set it up in your repo.</p><h3>1. Add Git Hook (.git/hooks/prepare-commit-msg)</h3><pre>#!/usr/bin/env sh<br># AI commit message prefill using OpenAI (Python version)<br>MSG_FILE=&quot;$1&quot;<br>COMMIT_SOURCE=&quot;$2&quot;<br><br>REPO_ROOT=&quot;$(git rev-parse --show-toplevel)&quot;<br>if [ -f &quot;$REPO_ROOT/.env&quot; ]; then<br>  while IFS=&#39;=&#39; read -r key value; do<br>    case &quot;$key&quot; in &#39;&#39;|\#*) continue ;; esac<br>    value=&quot;$(printf &#39;%s&#39; &quot;$value&quot; | sed &#39;s/^\&quot;\(.*\)\&quot;$/\1/&#39;)&quot;<br>    if printf &#39;%s&#39; &quot;$key&quot; | grep -Eq &#39;^[A-Za-z_][A-Za-z0-9_]*$&#39;; then<br>      export &quot;$key=$value&quot;<br>    fi<br>  done &lt; &quot;$REPO_ROOT/.env&quot;<br>fi<br><br># Skip merge/squash commits<br>case &quot;$COMMIT_SOURCE&quot; in<br>  merge|squash) exit 0 ;;<br>esac<br><br>git diff --staged --quiet &amp;&amp; exit 0<br><br># Don&#39;t override if commit message already exists<br>if grep -q &#39;^[^#[:space:]]&#39; &quot;$MSG_FILE&quot;; then<br>  exit 0<br>fi<br><br>if [ -z &quot;$OPENAI_API_KEY&quot; ]; then<br>  echo &quot;prepare-commit-msg: OPENAI_API_KEY not set&quot; &gt;&amp;2<br>  exit 0<br>fi<br><br>PY_HELPER=&quot;$REPO_ROOT/scripts/ai_commit_msg.py&quot;<br>if [ ! -x &quot;$PY_HELPER&quot; ]; then<br>  echo &quot;prepare-commit-msg: $PY_HELPER not found or not executable&quot; &gt;&amp;2<br>  exit 0<br>fi<br>python3 &quot;$PY_HELPER&quot; &quot;$MSG_FILE&quot; 2&gt;/tmp/ai_commit_msg.stderr || {<br>  echo &quot;prepare-commit-msg: AI generation failed&quot; &gt;&amp;2<br>  if [ -s /tmp/ai_commit_msg.stderr ]; then<br>    sed &#39;s/^/  /&#39; /tmp/ai_commit_msg.stderr &gt;&amp;2<br>  fi<br>  if [ &quot;${OPENAI_COMMIT_FALLBACK:-0}&quot; = &quot;1&quot; ]; then<br>    {<br>      printf &quot;chore: update files\n\n&quot;<br>      printf &quot;# Fallback message used because AI generation failed.\n&quot;<br>    } &gt; &quot;$MSG_FILE&quot;<br>  fi<br>}</pre><h3>2. Add Python Script (scripts/ai_commit_msg.py)</h3><p>This script fetches your staged diff, sends it to OpenAI, and writes back the commit message:</p><pre>#!/usr/bin/env python3<br>import os<br>import subprocess<br>import sys<br>from openai import OpenAI<br>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>if not api_key:<br>    print(&quot; ERROR: OPENAI_API_KEY not set&quot;, file=sys.stderr)<br>    sys.exit(1)<br>client = OpenAI(api_key=api_key)<br>def sh(cmd: str) -&gt; str:<br>    return subprocess.check_output(cmd, shell=True, text=True, stderr=subprocess.DEVNULL).strip()<br>def get_staged_diff() -&gt; str:<br>    try:<br>        return sh(&quot;git diff --staged&quot;)<br>    except subprocess.CalledProcessError:<br>        return &quot;&quot;<br>def main():<br>    if len(sys.argv) &lt; 2:<br>        sys.exit(0)<br>    msg_file = sys.argv[1]<br>    diff = get_staged_diff()<br>    if not diff:<br>        sys.exit(0)<br>    prompt = f&quot;&quot;&quot;<br>    You are an assistant that writes Git commit messages in the Conventional Commit style.<br>    Rules:<br>    - Subject line format: &lt;type&gt;(&lt;scope&gt;): &lt;subject&gt;<br>    - Valid types: feat, fix, docs, refactor, test, chore, build, ci.<br>    - Subject ≤ 72 characters, imperative mood.<br>    - After subject, add a blank line.<br>    - Then provide a bullet list of key changes (one per line, starting with &quot;- &quot;).<br>    - No code fences, no markdown except &quot;- &quot; for bullets.<br>    Example:<br>    feat(auth): add JWT-based login<br>    - Introduced JWT authentication flow<br>    - Updated middleware to validate tokens<br>    - Added tests for expired tokens<br>    Now, generate a commit message for this diff:<br>        {diff}<br>    &quot;&quot;&quot;<br>    try:<br>        response = client.chat.completions.create(<br>            model=&quot;gpt-4o-mini&quot;,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            temperature=0.3,<br>        )<br>    except Exception as e:<br>        print(f&quot; OpenAI API error: {e}&quot;, file=sys.stderr)<br>        sys.exit(1)<br>    commit_message = response.choices[0].message.content.strip()<br>    if not commit_message:<br>        commit_message = &quot;chore: update files\n\n# Fallback commit message&quot;<br>    with open(msg_file, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>        f.write(commit_message + &quot;\n&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>3. Add .env</h3><pre>OPENAI_API_KEY=&quot;sk-xxxx&quot;<br>OPENAI_COMMIT_FALLBACK</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1229665aed9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Temperature in AI: How It Controls Creativity and Consistency]]></title>
            <link>https://medium.com/@preethi_prakash/understanding-temperature-in-ai-how-it-controls-creativity-and-consistency-fbe2e910bf63?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe2e910bf63</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 15:08:27 GMT</pubDate>
            <atom:updated>2025-02-23T15:14:57.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5p0xm8Dguqtc4YEr" /><figcaption>Photo by <a href="https://unsplash.com/@jonasjaekenmedia?utm_source=medium&amp;utm_medium=referral">Jonas Jaeken</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Have you ever wondered why AI-generated responses can sometimes be precise and repetitive, while other times they feel more creative and varied? The secret lies in a concept called <strong>temperature</strong>, a key parameter in AI models like ChatGPT, Google Gemini, and Llama that controls randomness in responses.</p><p>This article breaks down the <strong>mathematics behind AI temperature</strong>, explaining how it impacts probability distribution and output diversity. Whether you’re a developer tuning AI responses or a curious reader exploring AI’s behavior, this guide will help you understand the logic behind it.</p><h3>What is Temperature in AI?</h3><p>In AI-generated text, the model predicts the most likely next word based on learned probabilities. The <strong>temperature parameter</strong> influences how these probabilities are adjusted before making a final choice.</p><ul><li><strong>Lower temperature (e.g., 0.1)</strong> → More <strong>deterministic</strong> and predictable output.</li><li><strong>Higher temperature (e.g., 1.5)</strong> → More <strong>diverse and creative</strong> responses.</li><li><strong>Temperature = 1</strong> → No modification; the model uses raw probabilities.</li></ul><h3>Mathematical Explanation</h3><p>The probability of choosing a word is determined using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/0*HWhWo5pplcS5qUzE.png" /></figure><p>where:</p><ul><li>P_i is the original probability of token i,</li><li>T (temperature) is a positive value,</li><li>P_i&#39; is the adjusted probability.</li></ul><p>Let’s break this down with an example.</p><h3>Case Study: Temperature in Action</h3><p>Assume a language model predicts the next word with the following probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpYBemOr0YOQuyxwXcqaGQ.png" /></figure><h4>Low Temperature (T = 0.5)</h4><p>A lower temperature makes high-probability tokens even more dominant.</p><p>Compute scaled probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*uibQ1PiwRyvS1wLZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*fbh33xPUrKTR_RCX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/0*7npFv70PMADZJ_QH.png" /></figure><p>Normalize :</p><p><strong>“hello” → 78%</strong> (strong preference for the highest probability word).</p><h4>High Temperature (T = 2.0)</h4><p>A higher temperature flattens probabilities, increasing randomness.</p><p>Compute scaled probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/0*lF0ckPX8JYvxRL05.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/0*QB-yje3qdeIgDitv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/0*gEnyyMHR3jHx5Y4B.png" /></figure><p>Normalize:</p><p><strong>“hello” → 47%</strong>, <strong>“hi” → 33%</strong>, <strong>“hey” → 19%</strong> (more evenly distributed probabilities).</p><h3>Extreme Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeGW305YFKMyFPa62sdLkA.png" /></figure><h4>Practical Applications of Temperature</h4><ul><li><strong>Low Temperature (0–0.5)</strong> → Used for tasks requiring accuracy and predictability (e.g., factual answers, customer service bots).</li><li><strong>Medium Temperature (0.7–1.0)</strong> → Ideal for general conversation and balanced AI responses.</li><li><strong>High Temperature (1.5–2.0)</strong> → Useful for creative writing, brainstorming, and generating unique responses.</li></ul><h4>Example:</h4><pre>import openai<br><br># Set your OpenAI API key<br>openai.api_key = &quot;your-api-key-here&quot;<br><br># Define the prompt<br>prompt = &quot;Once upon a time, in a faraway land, there was a...&quot;<br><br># Function to generate text with adjustable temperature<br>def generate_text_with_temperature(prompt, temperature):<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-003&quot;,  # You can also use &quot;gpt-4&quot; or other models<br>        prompt=prompt,<br>        max_tokens=150,<br>        temperature=temperature,  # Adjust temperature here<br>        n=1,<br>        stop=None<br>    )<br>    return response.choices[0].text.strip()<br><br># Example 1: Low Temperature (0.3)<br>generated_text_low = generate_text_with_temperature(prompt, 0.3)<br>print(&quot;Generated Text (T = 0.3):&quot;)<br>print(generated_text_low)<br><br>print(&quot;\n&quot; + &quot;=&quot;*40 + &quot;\n&quot;)<br><br># Example 2: High Temperature (1)<br>generated_text_high = generate_text_with_temperature(prompt, 1)<br>print(&quot;Generated Text (T = 1):&quot;)<br>print(generated_text_high)</pre><h3>Expected Output:</h3><h4>Low Temperature (T = 0.3):</h4><pre>Once upon a time, in a faraway land, there was a peaceful kingdom ruled by a wise and just king. The people of the kingdom loved their king, and they lived in harmony and prosperity for many years.</pre><h4>High Temperature (T = 1)</h4><pre>Once upon a time, in a faraway land, there was a curious dragon who lived in a cave filled with glowing jewels. He would often sneak out under the cover of night, scattering treasure around the villages, causing confusion and excitement among the villagers. Some thought him a mischievous spirit, others believed him to be a magical guardian of the land.</pre><h3>Final Thoughts</h3><p>Understanding <strong>temperature</strong> in AI helps in fine-tuning responses based on the desired level of creativity versus consistency. Whether you’re a developer optimizing chatbots or an AI enthusiast exploring text generation, knowing how to adjust temperature can dramatically change your AI’s behavior.</p><p>Want to see the effects of temperature in action? Try adjusting it in AI playgrounds like OpenAI’s API, Google Gemini, or Hugging Face models.</p><h3>Sources</h3><ol><li>OpenAI API Documentation — <a href="https://platform.openai.com/docs">https://platform.openai.com/docs</a></li><li>Google Gemini AI Overview — <a href="https://deepmind.google/gemini">https://deepmind.google/gemini</a></li><li>Hugging Face Transformers — <a href="https://huggingface.co/docs">https://huggingface.co/docs</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe2e910bf63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: The Role of Dot Products in Transformer Attention: A Deep Dive (Beginner’s Guide)]]></title>
            <link>https://medium.com/@preethi_prakash/part-3-the-role-of-dot-products-in-transformer-attention-a-deep-dive-beginners-guide-db2fdfffd61c?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/db2fdfffd61c</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 16:22:44 GMT</pubDate>
            <atom:updated>2025-02-15T16:34:05.139Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: The Dot Product Behind Attention</strong></p><p>In the last article, we discussed how the <strong>Query</strong>, <strong>Key</strong>, and <strong>Value</strong> vectors work together in the <strong>Attention</strong> mechanism. Now, we’ll dive deeper into how the <strong>dot product</strong> plays a crucial role in calculating attention scores and helping the Transformer model understand word relationships.</p><h3>How the Dot Product Helps Calculate Attention Scores</h3><p>To measure the similarity between two vectors (e.g., <strong>Query</strong> and <strong>Key</strong>), the Transformer uses the <strong>dot product</strong>. This mathematical operation helps the model decide how much attention one word should pay to another.</p><p>Let’s break it down with an example:</p><p>Imagine we have the sentence:<br><em>“The animal didn’t cross the road because it was too tired.”</em></p><p>We want to know if <em>“it”</em> refers to <em>“animal”</em> or <em>“road”</em>. The model calculates the dot product between the <strong>Query</strong> vector of <em>“it”</em> and the <strong>Key</strong> vectors of <em>“animal”</em> and <em>“road”</em>.</p><h4>Example Calculation:</h4><ul><li><strong>Query Vector (it)</strong>: [1, 0, 1]</li><li><strong>Key Vector (animal)</strong>: [1, 1, 1]</li><li><strong>Key Vector (road)</strong>: [0, 1, 0]</li></ul><p>The <strong>dot product</strong> is calculated by multiplying corresponding elements and adding them up:</p><ul><li><strong>Dot product with “animal”</strong>: (1 × 1) + (0 × 1) + (1 × 1) = 2</li><li><strong>Dot product with “road”</strong>: (1 × 0) + (0 × 1) + (1 × 0) = 0</li></ul><p>The dot product with <em>“animal”</em> is higher, meaning <em>“it”</em> is more likely to refer to <em>“animal”</em>.</p><h3>Why is the Dot Product Important?</h3><p>The <strong>dot product</strong> helps measure how aligned two vectors are. The higher the dot product, the more similar the vectors are, indicating a stronger relationship between the words.</p><ul><li>A high dot product means the words are <strong>related</strong> (like <em>“it”</em> and <em>“animal”</em>).</li><li>A low dot product means the words are <strong>unrelated</strong> (like <em>“it”</em> and <em>“road”</em>).</li></ul><p>This process helps the Transformer decide which words are most important to focus on when making predictions.</p><h3>The Role of Softmax in Attention</h3><p>Once the dot products are calculated, the Transformer uses a mathematical function called <strong>softmax</strong> to turn the raw attention scores into <strong>probabilities</strong>. These probabilities tell the model how much attention to give to each word. Higher dot products lead to higher probabilities, meaning the model will focus more on words like <em>“animal”</em> in our example.</p><h3>Key Takeaways:</h3><ul><li>The <strong>dot product</strong> helps measure the similarity between words by comparing their vectors.</li><li>The <strong>softmax</strong> function turns attention scores into probabilities, determining how much focus each word should get.</li><li>These processes enable the Transformer to focus on the most relevant words, making predictions more accurate.</li></ul><p><strong>Sources:</strong></p><p><strong>“</strong><a href="https://arxiv.org/abs/1706.03762"><strong>Attention Is All You Need</strong></a><strong>” Paper</strong> — The foundational paper introducing the Transformer architecture and Attention mechanism.</p><p><a href="https://jalammar.github.io/illustrated-transformer/"><strong>The Illustrated Transformer</strong></a> — A beginner-friendly visual guide explaining the Transformer architecture and Attention mechanism.</p><p><a href="https://www.khanacademy.org/math/multivariable-calculus/thinking-about-multivariable-function/x786f2022:vectors-and-matrices/a/dot-products-mvc"><strong>Understanding the Dot Product</strong></a> — A simple explanation of the dot product in vector mathematics, essential for understanding how Attention works.</p><p><a href="https://research.google/blog/transformer-a-novel-neural-network-architecture-for-language-understanding/"><strong>Google’s Transformer Architecture (Technical Blog)</strong></a> — Google’s original blog post on the Transformer model, discussing its impact and advantages.</p><p><a href="https://sebastianraschka.com/blog/2023/self-attention-from-scratch.html"><strong>Practical Guide to Attention Mechanisms</strong></a> — A practical guide to understanding Attention and its use in neural networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db2fdfffd61c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: How Attention Works in Transformers: Breaking Down the Mechanism (Beginner’s Guide)]]></title>
            <link>https://medium.com/@preethi_prakash/part-2-how-attention-works-in-transformers-breaking-down-the-mechanism-beginners-guide-83027428f78b?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/83027428f78b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 16:19:46 GMT</pubDate>
            <atom:updated>2025-02-15T16:33:31.313Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: Breaking Down Attention in Transformers</strong></p><p>Now that we know what <strong>Attention</strong> is and why it’s important, let’s dive deeper into how it works within Transformer models. In this article, we’ll break down the <strong>Attention</strong> mechanism step by step to understand how the model uses this concept to make predictions.</p><p>We’ll also explore the roles of <strong>Query</strong>, <strong>Key</strong>, and <strong>Value</strong> vectors, which are the key ingredients in the Attention mechanism.</p><h3>Step-by-Step Breakdown of Attention</h3><h4>1. Word Representations (Embeddings)</h4><p>Each word in a sentence is turned into a numerical representation called an <strong>embedding</strong>. These embeddings are vectors (lists of numbers) that capture the meaning of each word. For example, the word <em>“animal”</em> will have a different vector than <em>“it”</em>.</p><h4>2. Query, Key, and Value Vectors</h4><p>For each word, the model creates three new vectors:</p><ul><li><strong>Query (Q)</strong>: Think of this as a “question” asking, “What do I want to know?”</li><li><strong>Key (K)</strong>: This answers the question, “What information do I have that could help?”</li><li><strong>Value (V)</strong>: This is the actual data the model uses to make a decision.</li></ul><h4>3. Calculating Attention Scores</h4><p>The Transformer uses the <strong>Query</strong> vector of a word and compares it to the <strong>Key</strong> vectors of all other words in the sentence. This comparison gives us an <strong>attention score</strong> that tells us how much focus one word should give to another. The comparison is done using the <strong>dot product</strong> of the vectors.</p><p>For example, in the sentence <em>“The animal didn’t cross the road because it was too tired.”</em>, the word <em>“it”</em> will have a higher attention score with <em>“animal”</em> than with <em>“road”</em> because <em>“it”</em> refers to <em>“animal”</em> in this context.</p><h4>4. Weighting the Values</h4><p>The attention scores are used to weight the <strong>Value</strong> vectors. Words with higher attention scores will have more influence on the model’s predictions. So, in our example, the word <em>“it”</em> will pay more attention to <em>“animal”</em> than to <em>“road”</em>, resulting in a more accurate prediction.</p><h4>5. Final Output</h4><p>Once the attention scores are applied to the <strong>Value</strong> vectors, the model aggregates this information to form a new representation of each word. This new representation captures both the word itself and its context, allowing the model to make better predictions.</p><h3>Key Takeaways:</h3><ul><li><strong>Query</strong>, <strong>Key</strong>, and <strong>Value</strong> vectors are used to calculate how much attention one word should give to another.</li><li>The <strong>attention score</strong> tells the model which words are most important in a given context.</li><li>The model uses these attention scores to adjust the weight of each word’s representation and make predictions.</li></ul><p>Continue to Part 3: <a href="https://medium.com/@preethi_prakash/part-3-the-role-of-dot-products-in-transformer-attention-a-deep-dive-beginners-guide-db2fdfffd61c"><strong>The Role of Dot Products in Transformer Attention: A Deep Dive (Beginner’s Guide)</strong></a></p><p><strong>Sources:</strong></p><p><strong>“</strong><a href="https://arxiv.org/abs/1706.03762"><strong>Attention Is All You Need</strong></a><strong>” Paper</strong> — The foundational paper introducing the Transformer architecture and Attention mechanism.</p><p><a href="https://jalammar.github.io/illustrated-transformer/"><strong>The Illustrated Transformer</strong></a> — A beginner-friendly visual guide explaining the Transformer architecture and Attention mechanism.</p><p><a href="https://www.khanacademy.org/math/multivariable-calculus/thinking-about-multivariable-function/x786f2022:vectors-and-matrices/a/dot-products-mvc"><strong>Understanding the Dot Product</strong></a> — A simple explanation of the dot product in vector mathematics, essential for understanding how Attention works.</p><p><a href="https://research.google/blog/transformer-a-novel-neural-network-architecture-for-language-understanding/"><strong>Google’s Transformer Architecture (Technical Blog)</strong></a> — Google’s original blog post on the Transformer model, discussing its impact and advantages.</p><p><a href="https://sebastianraschka.com/blog/2023/self-attention-from-scratch.html"><strong>Practical Guide to Attention Mechanisms</strong></a> — A practical guide to understanding Attention and its use in neural networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83027428f78b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Understanding Attention in Transformers: The Heart of NLP (Beginner’s Guide)]]></title>
            <link>https://medium.com/@preethi_prakash/part-1-understanding-attention-in-transformers-the-heart-of-nlp-beginners-guide-ec4124a438f6?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec4124a438f6</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 16:17:05 GMT</pubDate>
            <atom:updated>2025-02-15T16:35:54.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1: Understanding Attention in Transformers(Beginner’s Guide)</h3><p><strong>Introduction: The Magic Behind Transformer Models</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VCWhVpLqr762QVHr" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to Natural Language Processing (NLP), <strong>Transformer models</strong> have revolutionized the way machines understand language. But what’s behind this success? A key concept at the heart of Transformers is <strong>Attention</strong>.</p><p>Let’s break it down. Imagine you’re reading the sentence:<br><em>“The capital of France is …”</em></p><p>Not every word in this sentence carries the same weight. Words like <em>“France”</em> and <em>“capital”</em> are far more crucial for predicting the next word. <strong>Attention</strong> is the mechanism that allows models to focus on these important words, while not giving much weight to less important ones like <em>“the”</em> or <em>“is.”</em></p><p>In this article, we’ll explore how <strong>Attention</strong> works, why it’s so important, and how it has transformed machine learning, especially in NLP.</p><h3>What is Attention in Transformers?</h3><p><strong>Attention</strong> refers to the ability of a model to prioritize certain words over others when making predictions. For example, when trying to predict the next word in a sentence, words like <em>“capital”</em> and <em>“France”</em> will weigh more heavily than others because they carry more meaning.</p><p>Think of <strong>Attention</strong> like a spotlight. Imagine you’re at a meeting where several people are speaking, but you’re only paying attention to the words that directly impact you — like “deadline” or “budget.” This is exactly what Attention does in a Transformer model.</p><p>Before Transformers, traditional models processed sentences word-by-word, making it difficult to understand long-range relationships between words. Transformers, however, look at all words simultaneously and use Attention to figure out which ones to focus on. This ability makes it much faster and more accurate in handling complex language tasks.</p><h3>Why Attention Is Revolutionary</h3><p>The key difference with Transformers is that they don’t process words in a sequence. Traditional models read a sentence word by word, often missing the context between words. <strong>Transformers</strong>, on the other hand, use <strong>Attention</strong> to examine the entire sentence at once, allowing them to capture the context of each word more effectively.</p><p>This makes a massive difference in tasks like:</p><ul><li><strong>Machine Translation</strong>: Translating sentences accurately by understanding the relationships between words.</li><li><strong>Text Generation</strong>: Writing text that is coherent and contextually relevant.</li><li><strong>Question Answering</strong>: Selecting the correct answer from a body of text by understanding context.</li></ul><p>Transformers leverage this power of Attention to process sentences more like we humans do when reading. We don’t read every word with the same intensity; instead, we focus on the key words that carry the most meaning. Similarly, the Transformer model gives more focus to the words that are important for making predictions.</p><p>Continue to Part 2: <a href="https://medium.com/@preethi_prakash/part-2-how-attention-works-in-transformers-breaking-down-the-mechanism-beginners-guide-83027428f78b"><strong>How Attention Works in Transformers: Breaking Down the Mechanism (Beginner’s Guide)</strong></a></p><p><strong>Sources:</strong></p><p><strong>“</strong><a href="https://arxiv.org/abs/1706.03762"><strong>Attention Is All You Need</strong></a><strong>” Paper</strong> — The foundational paper introducing the Transformer architecture and Attention mechanism.</p><p><a href="https://jalammar.github.io/illustrated-transformer/"><strong>The Illustrated Transformer</strong></a> — A beginner-friendly visual guide explaining the Transformer architecture and Attention mechanism.</p><p><a href="https://www.khanacademy.org/math/multivariable-calculus/thinking-about-multivariable-function/x786f2022:vectors-and-matrices/a/dot-products-mvc"><strong>Understanding the Dot Product</strong></a> – A simple explanation of the dot product in vector mathematics, essential for understanding how Attention works.</p><p><a href="https://research.google/blog/transformer-a-novel-neural-network-architecture-for-language-understanding/"><strong>Google’s Transformer Architecture (Technical Blog)</strong></a> — Google’s original blog post on the Transformer model, discussing its impact and advantages.</p><p><a href="https://sebastianraschka.com/blog/2023/self-attention-from-scratch.html"><strong>Practical Guide to Attention Mechanisms</strong></a> — A practical guide to understanding Attention and its use in neural networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4124a438f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Baseline Models in Machine Learning]]></title>
            <link>https://medium.com/@preethi_prakash/understanding-baseline-models-in-machine-learning-3ed94f03d645?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed94f03d645</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Wed, 17 May 2023 17:19:33 GMT</pubDate>
            <atom:updated>2023-05-17T17:19:33.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHiw3dwFIYW4Ocei" /><figcaption>Photo by <a href="https://unsplash.com/@richtervet?utm_source=medium&amp;utm_medium=referral">Rich Tervet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Importance, Strategies, and Application to Imbalanced Classes</h4><h4><strong>Introduction to Baseline Models</strong></h4><p>A baseline model is a simple model used to predict the outcome of data. It serves as a starting point for analysis, allowing us to assess the performance of more complex models and the impact of additional features. There are two common approaches to creating a baseline model for classification.</p><p><strong>Majority class classifier :</strong> where the most frequent class in the data is predicted for all observations. For instance, if we have 80% of observations in class A and 20% in class B for a binary classification problem, the baseline model would predict Class A for all instances.</p><p>R<strong>andom classifier :</strong> Randomly assigning class labels based on the class distribution in the data. In the aforementioned binary classification scenario, we would assign class A to 80% of the observations and class B to 20% of the observations randomly.The random classifier is particularly useful when there is no specific guidance or knowledge available to make informed predictions.</p><h4><strong>Importance of Baseline Models in Machine Learning</strong></h4><p>Baseline models serve as a reference point in machine learning tasks and offer several benefits. Here are the key reasons for using baseline models:</p><ol><li><strong>Performance</strong> <strong>comparison</strong>: Baseline models provide a basis for comparing the performance of more advanced models. They help determine if the complexity of a model translates into improved performance. If a model fails to outperform the baseline, it suggests issues with the approach or data.</li><li><strong>Minimum performance requirement</strong>: Baseline models set a minimum performance requirement for any useful model. If a complex model cannot surpass the baseline’s performance, it may not be worthwhile to implement it practically.</li><li><strong>Decision-making</strong>: Baseline models aid in resource allocation, model selection, and further model improvement. If the baseline model already achieves satisfactory performance, additional time and resources may not be necessary for building more complex models.</li></ol><h4><strong>Baseline Models for Imbalanced Classes</strong></h4><p>A baseline model, like a dummy classifier, is useful for detecting imbalanced classes by providing a comparison point. It allows us to assess the performance of more advanced models in the context of imbalanced data.</p><p>Imbalanced classes often lead to the majority class dominating predictions, resulting in high accuracy but poor identification of the minority class. A baseline model helps establish the expected performance level using a random or simplistic approach. Say a new kind of class emerges in your data pipeline , this new class would go unnoticed as the ratio to the existing class differs by a huge margin .</p><p>Creating a baseline model helps determine its accuracy in predicting the majority class and serves as a starting point for evaluating complex models. If an advanced model fails to outperform the baseline, it suggests ineffective handling of the imbalanced class issue.</p><p>The baseline classifier, such as a dummy classifier with the ‘most_frequent’ strategy, is suitable for detecting imbalanced classes in binary classification. It predicts the most frequent class for all instances, essentially ignoring the minority class and introducing bias towards the majority class.</p><p>When evaluating the baseline classifier’s performance on imbalanced classes, relying solely on accuracy may not provide an accurate representation. We will delve deeper into this topic in the next article.</p><h4><strong>Strategies in Dummy Classifier: Exploring Different Approaches</strong></h4><p>The scikit-learn library’s DummyClassifier class offers various strategies for generating predictions. These strategies are designed to create simple baseline models for comparison with more advanced models. Here are some commonly used strategies:</p><ol><li>“<strong>stratified</strong>”: This strategy randomly selects class labels based on the class distribution in the training set. It aims to maintain the same class distribution as the training data, making it useful for imbalanced classes.</li><li>“<strong>most_frequent</strong>”: This strategy always predicts the most frequent class in the training set. It is suitable for imbalanced datasets where the majority class dominates the distribution. It provides a baseline performance level based on the most common class, without considering input features.</li><li>“<strong>uniform</strong>”: This strategy assigns class labels randomly and uniformly, without considering the class distribution in the training data. It is useful when there is no specific pattern or information to guide the predictions.</li><li>“<strong>constant</strong>”: This strategy always predicts a constant class label specified by a constant parameter. It helps create a baseline model that consistently predicts a particular class. It aids in evaluating the impact of class imbalance and comparing model performance against a fixed prediction.</li></ol><p>By selecting an appropriate strategy, you can create a baseline classifier that reflects different aspects of the data, such as class distribution, majority class dominance, randomness, or a fixed prediction.</p><p>A sample baseline classifier for Breast Cancer dataset .</p><pre>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br>from sklearn.dummy import DummyClassifier<br>from sklearn.metrics import accuracy_score, classification_report<br><br># Load the breast cancer dataset<br>data = load_breast_cancer()<br>X = data.data<br>y = data.target<br><br># Split the dataset into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Create a baseline random classifier<br>dummy_clf = DummyClassifier(strategy=&#39;stratified&#39;, random_state=42)<br><br># Fit the baseline classifier on the training data<br>dummy_clf.fit(X_train, y_train)<br><br># Make predictions on the test data<br>y_pred = dummy_clf.predict(X_test)<br><br># Calculate accuracy and other metrics<br>accuracy = accuracy_score(y_test, y_pred)<br>report = classification_report(y_test, y_pred)<br><br># Print the results<br>print(&quot;Baseline Classifier Accuracy:&quot;, accuracy)<br>print(&quot;Classification Report:&quot;)<br>print(report)</pre><p>you can check the entire code here at GitHub — <a href="https://github.com/preethi-prak/ML_Classification/blob/16970d5a52f3f4298ba05ca9f9d3e12082267c8b/Baseline_Classfier.ipynb">Baseline Classifier</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed94f03d645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Machine Learning Predictions in Scikit-Learn]]></title>
            <link>https://medium.com/@preethi_prakash/mastering-machine-learning-predictions-in-scikit-learn-25e86881a70e?source=rss-c072bb0dc6ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e86881a70e</guid>
            <category><![CDATA[scikit]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Preethi Prakash]]></dc:creator>
            <pubDate>Sat, 13 May 2023 17:49:44 GMT</pubDate>
            <atom:updated>2023-05-13T18:21:33.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dYptqSy6IgPGHNs_" /><figcaption>Photo by <a href="https://unsplash.com/es/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Understanding the predict, predict_proba, predict_log_proba, and decision_function Methods</h4><p>In this article we will talk about the difference between prediction functions and their usage .</p><blockquote>In machine learning, the predict and predict_proba, predict_log_proba, and decision_function methods are used to make predictions based on a trained model.</blockquote><h4><strong>‘predict’ method</strong></h4><p>The predict method is used to make a binary or multi-class classification prediction, and it returns the predicted class label(s) for the input data. For example, if you have trained a logistic regression model to predict whether a customer will buy a product or not, you can use the predict method to predict whether a new customer will buy the product or not.</p><p>we will use the breast cancer dataset from scikit-learn. This dataset contains tumor observations and corresponding labels for whether the tumor was malignant or benign.</p><pre>import numpy as np<br>from sklearn.svm import SVC<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.pipeline import make_pipeline<br>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_breast_cancer<br><br>#Loading the dataset<br>dataset = load_breast_cancer(as_frame=True)<br><br>#Creating the features and target<br>X = dataset[&#39;data&#39;]<br>y = dataset[&#39;target&#39;]<br><br>#Splitting the dataset into training and test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y , test_size=0.25, random_state=0)<br><br>#we create a simple pipeline to normalize the data and train the model using SVC classifier<br>svc_clf = make_pipeline(StandardScaler(),SVC(max_iter=1000, probability=True))<br>svc_clf.fit(X_train, y_train)<br></pre><pre># we are predicting the first entry of X_test <br>print(svc_clf.predict(X_test[:1]))</pre><pre>#predicts the class the first entry of X_test belongs to<br><br>[0]</pre><h4><strong>‘ predict_proba’ method</strong></h4><p>The predict_proba method is used to predict the probability of each class label, and it returns the probability estimates for each possible class label. This method is often used for binary or multi-class classification problems, where you want to know the probability of each possible outcome. For example, if you have trained a model to classify images of animals into cats, dogs, and horses, you can use the predict_proba method to get the probability estimates for each class label.</p><pre>print(svc_clf.predict_proba(X_test[:1]))</pre><pre>[[0.99848307 0.00151693]]</pre><h4>‘predict_log_proba’ method</h4><p>The predict_log_proba method is similar to predict_proba, but it returns the logarithm of the probability estimates instead of the raw probabilities. This can be useful when working with very small or very large probability values, as it helps to avoid numerical underflow or overflow issues.</p><pre>print(svc_clf.predict_log_proba(X_test[:1]))</pre><pre>[[-1.51808474e-03 -6.49106473e+00]]</pre><h4>‘ decision_function’ method</h4><p>The decision_function method is used for binary classification problems with linear models. It returns a score for each input data point, which can be used to determine the class label prediction. The threshold for classifying a data point as positive or negative can be set based on the application or domain knowledge.</p><pre>print(svc_clf.decision_function(X_test[:1]))</pre><pre>[-1.70756057]</pre><p>In summary:</p><ul><li>Use ‘predict’ for binary or multi-class classification problems when you want to get the predicted class label(s) for input data.</li><li>Use ‘predict_proba’ for binary or multi-class classification problems when you want to get the probability estimates for each possible class label.</li><li>Use ‘predict_log_proba’ when you need to work with very small or very large probability values, or when you want to avoid numerical underflow or overflow issues.</li><li>Use ‘decision_function’ for binary classification problems with linear models when you want to get a score for each input data point.</li></ul><p>Note : Some classifiers don’t have all the prediction method or needs extra parameteres to access the function . For eg : SVC needs probability argument to be set to ‘True’ in order to use probability predictions .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e86881a70e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>