<?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 Rohan Sardar on Medium]]></title>
        <description><![CDATA[Stories by Rohan Sardar on Medium]]></description>
        <link>https://medium.com/@rohan-sardar?source=rss-275add068eb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*syJlN1oDWNxMegJSQl6G0w.jpeg</url>
            <title>Stories by Rohan Sardar on Medium</title>
            <link>https://medium.com/@rohan-sardar?source=rss-275add068eb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:20:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohan-sardar/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[Decision Tree Classifier from Scratch using NumPy]]></title>
            <link>https://rohan-sardar.medium.com/decision-tree-classifier-from-scratch-using-numpy-3b901763c567?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b901763c567</guid>
            <category><![CDATA[decision-tree-classifier]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 14:36:09 GMT</pubDate>
            <atom:updated>2026-04-12T14:36:09.972Z</atom:updated>
            <content:encoded><![CDATA[<p>A complete guide to create a decision tree classifier from scratch using NumPy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_odEnoEcCdaynXLVeUeEA.jpeg" /><figcaption>A sample decision tree for Iris dataset</figcaption></figure><h3>What is a decision tree ?</h3><p>A decision tree is a supervised learning model that represents decisions in a hierarchical, tree-like structure. While modern implementations often use advanced variants, the foundational logic is rooted in the <strong>ID3 (Iterative Dichotomiser 3)</strong> and <strong>CART (Classification and Regression Trees)</strong> algorithms.</p><p>Formally, a decision tree recursively partitions the input space. At each internal node, the algorithm selects an attribute and a threshold that optimizes a specific statistical criterion. In probabilistic terms, the tree aims to transform a high-entropy prior probability distribution of classes into a set of low-entropy posterior distributions at the leaf nodes. Each leaf node represents a conditional probability <em>P(y|X)</em>, where<em> y</em> is the predicted class given the feature path <em>X</em>.</p><p>To represent these decision points and final predictions, we use <strong>Node </strong>class:</p><pre>class Node:<br>    def __init__(self, feature=None, threshold=None, left=None, right=None, value=None, info_gain=None):<br>        self.feature = feature<br>        self.threshold = threshold<br>        self.left = left<br>        self.right = right<br>        self.value = value<br>        self.info_gain = info_gain<br><br>    # Check leaf node<br>    def is_leaf_node(self):<br>        return self.value is not None</pre><p>Each node stores the splitting rule (feature + threshold) or a final prediction if it’s a leaf.</p><h3>How to split the nodes ?</h3><p>In a decision tree, “learning” is the process of finding the feature <em>j</em> and threshold <em>t</em> that best separates the data. We determine “best” by measuring the reduction in impurity. The two common criterions used in the process are: <strong>Gini Impurity</strong> and <strong>Entropy</strong>.</p><p>The following Python code demonstrates that:</p><pre>def _split(self, X_column, split_thresh):<br>    left_idxs = np.argwhere(X_column &lt;= split_thresh).flatten()<br>    right_idxs = np.argwhere(X_column &gt; split_thresh).flatten()<br>    return left_idxs, right_idxs</pre><h4>Gini Impurity</h4><p>Gini Impurity is a statistical measure used to quantify the frequency at which a randomly chosen element from a dataset would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset. In the context of decision trees, it helps us understand the “purity” of a node. A node is considered pure if all instances in that node belong to a single class.</p><p>The mathematical formula for Gini Impurity is:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F4neHmMCtd4ntc59eyvMmBx&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4neHmMCtd4ntc59eyvMmBx" width="452" height="169" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab1fefe6969f180b0e36b05640b4580/href">https://medium.com/media/aab1fefe6969f180b0e36b05640b4580/href</a></iframe><p>Here, <em>pᵢ</em> represents the probability of an item being classified into a particular class <em>i</em> and <em>c</em> is the number of classes, which is 2 for binary classification. When we split a node, we calculate the weighted Gini Impurity of the resulting children and compare it to the parent node. The goal is to minimize this value. Thus, if the gini impurity becomes 0 then the node is 100% pure.</p><h4>Entropy</h4><p>Entropy is a concept borrowed from information theory that measures the level of disorder, or uncertainty, in a system. For a classifier, entropy represents the impurity of the data. If a dataset is perfectly split between two classes, the entropy is at its maximum (1.0). If all data points belong to one class, the entropy is zero.</p><p>The formula for Entropy is:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FoZnr2sQbA4BUABH2aEgRqs&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoZnr2sQbA4BUABH2aEgRqs" width="200" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2eff1a37f0374cb3aa72c4b81bba0f6/href">https://medium.com/media/c2eff1a37f0374cb3aa72c4b81bba0f6/href</a></iframe><p>In this equation, <em>pᵢ</em> is again the proportion of examples belonging to class <em>i</em>. Using <em>log₂</em> ensures the measure is in “bits” of information. High entropy means the node is very “mixed,” while low entropy means it is closer to being a leaf node.</p><p>In Python, these two processes are implemented using the following block:</p><pre>def _calculate_impurity(self, y):<br>    if self.criterion == &quot;entropy&quot;:<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return -np.sum([p * np.log2(p) for p in ps if p &gt; 0])<br>    else: # Gini<br>        hist = np.bincount(y)<br>        ps = hist / len(y)<br>        return 1 - np.sum([p**2 for p in ps if p &gt; 0])</pre><p>Here<strong><em> np.bincount</em></strong> efficiently computes class frequencies, avoiding loops.</p><h3>Information Gain</h3><p>Information Gain (IG) is the most critical statistical component of the tree. It is the measure of the decrease in entropy (or Gini) after a dataset is split on a feature. It effectively asks: <em>“How many bits of uncertainty did we lose by knowing the value of Feature X?”</em></p><p>When we split a parent node into children, we cannot simply compare the raw entropy. We must use a <strong>weighted average</strong> based on the size of the child populations. This prevents the algorithm from favoring splits that create tiny pure groups at the expense of large, disorganized ones.</p><p>The formula for Information Gain is defined as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F5DZXHc3FbnyqQiYtA6RYip&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F5DZXHc3FbnyqQiYtA6RYip" width="450" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/4901dd3236e313a6361ff6e08bcb6f34/href">https://medium.com/media/4901dd3236e313a6361ff6e08bcb6f34/href</a></iframe><p>In this equation, <em>H(S)</em> is the entropy of the parent set <em>S</em>. The second part of the formula represents the weighted entropy of the children. The weight <em>|Sᵢ|/|S|</em> is the proportion of total samples that fell into child node <em>i</em>. The goal of our algorithm is to iterate through every feature and evaluate all unique values as candidate thresholds to find the exact point that maximizes this gain.</p><p>The following Python code shows how the nodes are split based on information gain:</p><pre>def _best_split(self, X, y, feat_idxs):<br>    best_gain = -1<br>    split_idx, split_thresh = None, None<br><br>    for feat_idx in feat_idxs:<br>        X_column = X[:, feat_idx]<br>        thresholds = np.unique(X_column)<br><br>        for thr in thresholds:<br>            gain = self._information_gain(y, X_column, thr)<br><br>            if gain &gt; best_gain:<br>                best_gain = gain<br>                split_idx = feat_idx<br>                split_thresh = thr<br><br>    return split_idx, split_thresh, best_gain</pre><p>Now the information gain is implemented using the following block of Python code:</p><pre>def _information_gain(self, y, X_column, threshold):<br>    # Calculate parent impurity<br>    parent_impurity = self._calculate_impurity(y)<br><br>    # Generate split<br>    left_idxs, right_idxs = self._split(X_column, threshold)<br>    if len(left_idxs) == 0 or len(right_idxs) == 0:<br>        return 0<br><br>    # Calculate weighted average impurity of children<br>    n = len(y)<br>    n_l, n_r = len(left_idxs), len(right_idxs)<br>    e_l, e_r = self._calculate_impurity(y[left_idxs]), self._calculate_impurity(y[right_idxs])<br>    child_impurity = (n_l / n) * e_l + (n_r / n) * e_r<br><br>    # Return information gain<br>    return parent_impurity - child_impurity</pre><p>This brute-force search evaluates every possible split and selects the one that maximizes information gain.</p><h3>The Mechanics of the Algorithm: Recursive Partitioning</h3><p>The process of building the tree is known as <strong>Recursive Binary Splitting</strong>. It is a “greedy” algorithm because it makes the best possible split at the current moment without looking ahead to see if a different split would result in a better tree globally.</p><ol><li><strong>Search:</strong> For the current dataset, calculate the Information Gain for every possible feature and threshold.</li><li><strong>Selection:</strong> Choose the split with the highest IG.</li><li><strong>Bifurcation:</strong> Divide the data into “Left” (<em>x ≤ threshold</em>) and “Right” (<em>x &gt; threshold</em>) subsets.</li><li><strong>Recursion:</strong> Repeat the process for the child nodes.</li><li><strong>Termination:</strong> Stop when:<br>- The maximum depth is reached.<br>- The node is pure (Entropy = 0). <br>- The number of samples is too small to split.</li></ol><p>Python code on how tree is grown is given below:</p><pre>def _grow_tree(self, X, y, depth=0):<br>    n_samples, n_features = X.shape<br>    n_labels = len(np.unique(y))<br><br>    # Stopping conditions<br>    if (depth &gt;= self.max_depth or n_labels == 1 or n_samples &lt; self.min_samples_split):<br>        leaf_value = self._most_common_label(y)<br>        return Node(value=leaf_value)<br><br>    feat_idxs = np.arange(n_features)<br>    best_feat, best_thresh, best_gain = self._best_split(X, y, feat_idxs)<br><br>    if best_gain == 0:<br>        leaf_value = self._most_common_label(y)<br>        return Node(value=leaf_value)<br><br>    left_idxs, right_idxs = self._split(X[:, best_feat], best_thresh)<br><br>    left = self._grow_tree(X[left_idxs, :], y[left_idxs], depth + 1)<br>    right = self._grow_tree(X[right_idxs, :], y[right_idxs], depth + 1)<br><br>    return Node(best_feat, best_thresh, left, right, info_gain=best_gain)</pre><h3>Implementation Insights</h3><p>Using NumPy allows us to vectorize these statistical calculations. For instance, <strong><em>np.bincount</em></strong> is used to efficiently calculate the class frequencies (<em>pᵢ</em>), and <strong><em>np.argwhere</em></strong> facilitates the rapid partitioning of the feature matrix.</p><p>By the time the <strong><em>fit </em></strong>method finishes, we have a linked structure of <strong><em>Node</em></strong> objects. Prediction then becomes a simple traversal: if the input feature is less than the node threshold, go left; otherwise, go right.</p><pre>def _traverse_tree(self, x, node):<br>    if node.is_leaf_node():<br>        return node.value<br><br>    if x[node.feature] &lt;= node.threshold:<br>        return self._traverse_tree(x, node.left)<br>    return self._traverse_tree(x, node.right)<br><br>def predict(self, X):<br>    return np.array([self._traverse_tree(x, self.root) for x in X])</pre><h3>Putting It All Together</h3><p>Now that we’ve built everything from scratch, let’s test it on a real dataset. Use the <strong><em>DecisionTree </em></strong>class (full code is on GitHub link given below) on the Iris dataset and check the accuracy.</p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br>data = load_iris()<br>X, y = data.data, data.target<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br>clf = DecisionTree(max_depth=4, criterion=&quot;entropy&quot;)<br>clf.fit(X_train, y_train)<br><br>y_pred = clf.predict(X_test)<br><br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><h3>Conclusion</h3><p>Building a Decision Tree from scratch reveals that Machine Learning isn’t just about “coding models”- it is about applying Information Theory to data. By quantifying uncertainty and systematically reducing it, we transform a raw table of numbers into a logical map of human-readable decisions.</p><h3>GitHub</h3><p>The code is available <a href="https://github.com/RohanSardar/decision-tree-scratch">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b901763c567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stratified K-Fold: Resampling Technique for Variance Reduction in Imbalanced Data]]></title>
            <link>https://rohan-sardar.medium.com/stratified-k-fold-resampling-technique-for-variance-reduction-in-imbalanced-data-a60a27f33e52?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a60a27f33e52</guid>
            <category><![CDATA[k-fold]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[stratified-k-fold]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 18:35:37 GMT</pubDate>
            <atom:updated>2026-03-07T18:35:37.429Z</atom:updated>
            <content:encoded><![CDATA[<p>Accurate model validation relies on the assumption that our training and testing subsets are representative of the underlying population distribution. <strong>Stratified K-Fold</strong> addresses this by ensuring that <strong>each fold preserves the class distribution of the dataset</strong>, providing a more stable and statistically reliable estimate of a model’s generalization performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRnqlsJpMQY4fRt67Sa4oA.png" /><figcaption>Stratified K Fold</figcaption></figure><h3>Why Stratified Resampling ?</h3><p>In standard K-Fold Cross-Validation, the dataset is partitioned into <em>k </em>folds using <strong>simple random sampling</strong>. While this works well for large and balanced datasets, it can introduce <strong>sampling bias</strong> when classes are imbalanced or the dataset is small.</p><p>For example, if a churn dataset contains <strong>80% non-churn and 20% churn</strong>, a random split might produce a fold with a 98/2 distribution purely by chance or even with a 100/0 absolute distribution.</p><p>This leads to two primary issues:</p><ol><li><strong>High Variance:</strong> Our model’s accuracy or F1-score will fluctuate significantly depending on the specific composition of the fold.</li><li><strong>Pessimistic or Optimistic Bias:</strong> If a fold lacks the minority class entirely, the model cannot be evaluated on its ability to detect that class, leading to a misleading performance report.</li></ol><h3>The Stratification Mechanism</h3><p>In statistics, <strong>stratification</strong> divides a population into mutually exclusive groups called <strong>strata</strong>. In machine learning, each class label in the target variable <em>y</em> represents a stratum.</p><p>Instead of drawing samples from the dataset using simple random sampling, Stratified K-Fold applies <strong>proportionate stratified sampling</strong>, ensuring that each fold maintains approximately the same class proportions as the full dataset.</p><p>The number of samples from each class <em>h</em> in a fold is determined using proportional allocation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*0idIwDgOk6tiEnBsy2SM8g.png" /></figure><h4>Implementing for train-test split</h4><pre>from sklearn.model_selection import train_test_split<br><br># &#39;stratify=y&#39; ensures class proportions are preserved<br>X_train, X_test, y_train, y_test = train_test_split(<br>  X, y, test_size=0.2, random_state=42, stratify=y<br>)</pre><h3>Demonstrating Stratified K-Fold</h3><p>To see the statistical difference, we will simulate a synthetic dataset where only <strong>10%</strong> of the samples belong to the positive class. We will then compare how many positive samples end up in each validation fold using both techniques.</p><pre>import numpy as np<br>from sklearn.model_selection import KFold, StratifiedKFold<br><br># Dataset: 100 samples (90 zeros, 10 ones)<br>y = np.array([0]*90 + [1]*10)<br>X = np.zeros((100, 1))  # dummy feature matrix<br><br><br>def analyze_splits(splitter, name):<br>    print(f&quot;\nDISTRIBUTION OF {name}:&quot;)<br><br>    for fold, (_, val_idx) in enumerate(splitter.split(X, y), 1):<br>        fold_y = y[val_idx]<br><br>        # count classes<br>        n0 = np.sum(fold_y == 0)<br>        n1 = np.sum(fold_y == 1)<br><br>        print(f&quot;\nFold {fold}&quot;)<br>        print(&quot;Labels:&quot;, fold_y)<br>        print(f&quot;Class 0: {n0}&quot;)<br>        print(f&quot;Class 1: {n1}&quot;)<br><br><br># Splitters<br>kf = KFold(n_splits=5, shuffle=True, random_state=42)<br>skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)<br><br># Run comparison<br>analyze_splits(kf, &quot;Standard KFold&quot;)<br>analyze_splits(skf, &quot;Stratified KFold&quot;)</pre><p>It gives the following output:</p><pre>DISTRIBUTION OF Standard KFold:<br><br>Fold 1<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]<br>Class 0: 19<br>Class 1: 1<br><br>Fold 2<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>Fold 3<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]<br>Class 0: 19<br>Class 1: 1<br><br>Fold 4<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1]<br>Class 0: 16<br>Class 1: 4<br><br>Fold 5<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>DISTRIBUTION OF Stratified KFold:<br><br>Fold 1<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>Fold 2<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>Fold 3<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>Fold 4<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2<br><br>Fold 5<br>Labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]<br>Class 0: 18<br>Class 1: 2</pre><p>So we can see that <strong>Standard K-Fold produces folds with highly variable class distributions</strong>, ranging from 1 to 4 positive samples in the validation set. This variability introduces instability in model evaluation because each fold effectively tests the model under a different class imbalance scenario.</p><p>In contrast, <strong>Stratified K-Fold maintains a consistent class distribution across all folds</strong>, with each validation split containing exactly 18 negative and 2 positive samples. This ensures that every evaluation step reflects the true underlying class proportions of the dataset.</p><h3>When Should We Use Stratified K-Fold?</h3><p>Stratified sampling is especially important when:</p><ul><li>The dataset is class-imbalanced</li><li>The dataset is small</li><li>The evaluation metric is sensitive to minority classes (like recall, F1-score, ROC-AUC)</li></ul><h3>Key Takeaway</h3><p>Standard K-Fold assumes that random sampling will preserve class proportions, which is not guaranteed for small or imbalanced datasets. Stratified K-Fold removes this randomness by explicitly enforcing class balance in each fold.</p><p>By doing so, it produces more reliable, lower variance estimates of model performance, making it a safer and more statistically sound validation strategy for classification tasks.</p><h3>References</h3><p><a href="https://scikit-learn.org/stable/api/index.html">Scikit-learn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a60a27f33e52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing BERT Word Embeddings with NetworkX and Plotly using PyTorch]]></title>
            <link>https://rohan-sardar.medium.com/visualizing-bert-word-embeddings-with-networkx-and-plotly-using-pytorch-84dff2a20636?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/84dff2a20636</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[networkx]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 14:32:20 GMT</pubDate>
            <atom:updated>2025-12-24T14:32:20.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Build an interactive tool to explore the semantic connections inside a BERT model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*eQq0EPjVv54J51175u_eZA.png" /></figure><h3>The Problem with Vectors</h3><p>Large Language Models (LLMs) like BERT (Bidirectional Encoder Representations from Transformers) “think” in high-dimensional vectors. For BERT, this is 768 dimensions.</p><p>This means each and every word (or token) passed into it gets mapped to 768 dimensional vectors. These high-dimensional vectors are the one responsible for capturing the semantic similarity among words.</p><p>While these numbers are mathematically useful for tasks like classification or translation, they are unintuitive for humans. We cannot intuitively see that words like “doctor” and “hospital” are closely related, or that “apple” is far away just by looking at a tensor of floating-point numbers.</p><p>In this tutorial, I will show you how to bridge that gap. We will build an <em>interactive semantic network</em> inside a Jupyter Notebook. We will use <strong>Hugging Face Transformers</strong> to get the model, also can be said as the “brain,” <strong>NetworkX</strong> to build the structure, and <strong>Plotly</strong> to make it beautiful and interactive.</p><h3>The Tech Stack</h3><p>We will be using the following libraries:<br> → <strong>PyTorch &amp; Transformers:</strong> To load the pre-trained BERT model<br> → <strong>NetworkX:</strong> To calculate the graph structure and layout<br> → <strong>Plotly:</strong> For interactive rendering (zooming, panning)<br> → <strong>IPyWidgets:</strong> To control the parameters directly in the notebook</p><h4>Importing the Libraries &amp; Modules</h4><p>First, we need to import all the necessary libraries and modules required for the visualization.</p><pre>import torch<br>import torch.nn.functional as F<br>import networkx as nx<br>import plotly.graph_objects as go<br>from transformers import BertTokenizer, BertModel<br>from tqdm.notebook import tqdm<br>import ipywidgets as widgets<br>from IPython.display import display</pre><h4>Loading the Model</h4><p>The next task is to load the `<strong><em>bert-base-uncased</em></strong>` model. We start from its full vocabulary of 30522 tokens filtering out special tokens, subwords, non-alphabetic tokens &amp; short words.</p><p>However, calculating similarity during runtime on a vocabulary of that scale is slow. The trick is to pre-compute embeddings for the filtered vocabulary once during class initialization. This allows us to perform significantly faster cosine similarity searches later. We use mean pooling over the token embeddings to obtain a single vector per word.</p><p>So, to streamline the process of loading the model and calculating the similarity, it is better to create a class.</p><pre>class BERTSimilarity:<br>    def __init__(self, model_name=&quot;bert-base-uncased&quot;, vocab_size=30522, batch_size=256):<br>        self.device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>        print(f&quot;Using device: {self.device}&quot;)<br><br>        self.tokenizer = BertTokenizer.from_pretrained(model_name)<br>        self.model = BertModel.from_pretrained(model_name).to(self.device)<br>        self.model.eval()<br><br>        raw_vocab = list(self.tokenizer.get_vocab().keys())<br>        self.vocab = self._filter_vocab(raw_vocab)[:vocab_size]<br>        self.batch_size = batch_size<br><br>        self.token_embeddings = self._compute_vocab_embeddings()<br><br>    def _filter_vocab(self, vocab):<br>        &quot;&quot;&quot;<br>        Removes special tokens, subwords, non-alphabetic tokens, short words.<br>        &quot;&quot;&quot;<br>        filtered = [<br>            token for token in vocab<br>            if token.isalpha() and not token.startswith(&quot;##&quot;) and len(token) &gt; 2<br>        ]<br>        return filtered<br><br>    def _compute_vocab_embeddings(self):<br>        &quot;&quot;&quot;<br>        Compute embeddings for filtered vocab using batching.<br>        &quot;&quot;&quot;<br>        embeddings = []<br>        for i in tqdm(range(0, len(self.vocab), self.batch_size), desc=&quot;Computing embeddings&quot;):<br>            batch_tokens = self.vocab[i:i+self.batch_size]<br>            inputs = self.tokenizer(batch_tokens, return_tensors=&quot;pt&quot;, padding=True, truncation=True).to(self.device)<br><br>            with torch.no_grad():<br>                outputs = self.model(**inputs)<br>                batch_embeds = outputs.last_hidden_state.mean(dim=1)<br>                embeddings.append(batch_embeds)<br><br>        return torch.cat(embeddings, dim=0)<br><br>    def get_similar_words(self, input_word, top_n=10):<br>        &quot;&quot;&quot;<br>        Given an input word, return top N similar words.<br>        &quot;&quot;&quot;<br>        inputs = self.tokenizer(input_word, return_tensors=&quot;pt&quot;).to(self.device)<br>        with torch.no_grad():<br>            outputs = self.model(**inputs)<br>            input_embedding = outputs.last_hidden_state.mean(dim=1)<br><br>        similarities = F.cosine_similarity(input_embedding, self.token_embeddings, dim=1)<br>        top_indices = torch.topk(similarities, top_n).indices<br>        similar_words = [(self.vocab[i], float(similarities[i])) for i in top_indices]<br>        return similar_words</pre><p>Then just run the following block to load the model and compute the embeddings:</p><pre>bert_model = BERTSimilarity(vocab_size=30522)<br>print(&quot;Model loaded &amp; embeddings computed...&quot;)</pre><h4>Finding Connections</h4><p>When the user types a seed word (for example, “science”), we convert it to an embedding and calculate the Cosine Similarity against our pre-computed vocabulary matrix.</p><p>We take the top N results (suppose, top 30 words). But here is where it gets interesting: we don’t just want to know what is connected to “science”. We want to know how those 30 results connect to each other.</p><p>We extract the sub-matrix of embeddings for just those 30 words and run an all-vs-all similarity check. The following function does that:</p><pre>def get_sub_matrix(word_list, engine):<br>    &quot;&quot;&quot;<br>    Re-computes embeddings for just the small list of words to find<br>    connections between them.<br>    &quot;&quot;&quot;<br>    inputs = engine.tokenizer(word_list, return_tensors=&quot;pt&quot;, padding=True, truncation=True).to(engine.device)<br>    with torch.no_grad():<br>        outputs = engine.model(**inputs)<br>        embeddings = outputs.last_hidden_state.mean(dim=1)<br>    <br>    embeddings = F.normalize(embeddings, p=2, dim=1)<br>    return torch.mm(embeddings, embeddings.t()).cpu().numpy()</pre><h4>Building the Graph</h4><p>Next, we will use <strong>NetworkX</strong> to create the nodes and edges. We only draw an edge if the similarity score is above a user-defined threshold.</p><p>If the threshold is too low, everything connects to everything. If it is too high, you get isolated islands. We use the <strong>Fruchterman-Reingold </strong>force-directed algorithm (<strong><em>spring_layout</em></strong>) to position the nodes. This algorithm treats edges like springs, connected words pull each other close, while unconnected words push apart.</p><p>The following function creates the visualization of the graph network based on similarity scores and the number of words asked for:</p><pre>def visualize_network(seed_word, top_n, threshold):<br>    try:<br>        # Get Similar Words<br>        similar_results = bert_model.get_similar_words(seed_word, top_n=top_n)<br>        print(f&quot;Displaying top {top_n} words similar to &#39;{seed_word}&#39;&quot;)<br>        <br>        # Prepare Data for Graph<br>        found_words = [seed_word] + [item[0] for item in similar_results]<br>        sim_matrix = get_sub_matrix(found_words, bert_model)<br><br>        G = nx.Graph()<br>        for w in found_words:<br>            G.add_node(w)<br>            <br>        rows, cols = sim_matrix.shape<br>        for i in range(rows):<br>            for j in range(i + 1, cols):<br>                score = sim_matrix[i][j]<br>                if score &gt; threshold:<br>                    G.add_edge(found_words[i], found_words[j], weight=score)<br><br>        # NetworkX Layout<br>        pos = nx.spring_layout(G, seed=42, k=0.5)<br><br>        # Plotly Traces<br>        edge_x, edge_y = [], []<br>        for edge in G.edges():<br>            x0, y0 = pos[edge[0]]<br>            x1, y1 = pos[edge[1]]<br>            edge_x.extend([x0, x1, None])<br>            edge_y.extend([y0, y1, None])<br><br>        edge_trace = go.Scatter(<br>            x=edge_x, y=edge_y,<br>            line=dict(width=0.5, color=&#39;#888&#39;),<br>            hoverinfo=&#39;none&#39;,<br>            mode=&#39;lines&#39;)<br><br>        node_x, node_y = [], []<br>        node_text = []<br>        node_adjacencies = []<br>        <br>        for node in G.nodes():<br>            x, y = pos[node]<br>            node_x.append(x)<br>            node_y.append(y)<br>            node_text.append(node)<br>            node_adjacencies.append(len(G.adj[node]))<br><br>        node_trace = go.Scatter(<br>            x=node_x, y=node_y,<br>            mode=&#39;markers+text&#39;,<br>            text=node_text,<br>            textposition=&quot;top center&quot;,<br>            hoverinfo=&#39;text&#39;,<br>            marker=dict(showscale=True, colorscale=&#39;Plasma&#39;, reversescale=True, color=node_adjacencies,<br>                        size=15, colorbar=dict(thickness=15, title=dict(text=&#39;Connections&#39;, side=&#39;right&#39;),<br>                                               xanchor=&#39;left&#39;)))<br><br>        fig = go.Figure(data=[edge_trace, node_trace],<br>                        layout=go.Layout(<br>                            title=f&quot;Network for &#39;{seed_word}&#39; (Similarity: {threshold})&quot;,<br>                            showlegend=False, hovermode=&#39;closest&#39;,<br>                            margin=dict(b=20,l=5,r=5,t=40),<br>                            xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),<br>                            yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))<br>        fig.show()<br>        <br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)</pre><h4>Visualizing with IPyWidgets</h4><p>A static graph is informative, but an interactive one is exploratory. To fully understand the model’s behavior, we need to tweak parameters on the fly. This is where IPyWidgets comes in.</p><p>We create a simple User Interface (UI) directly inside the notebook with three controls:</p><ol><li><strong>Search Term (Text Input):</strong> The seed word to start our search</li><li><strong>Number of Words (Slider):</strong> How many related words to fetch. Increasing this creates a denser graph</li><li><strong>Connection Threshold (Slider):</strong> The threshold for drawing lines</li></ol><p>We wrap our “<strong><em>vizualize_network”</em></strong> function in “<strong><em>widgets.interactive_output”</em></strong>. This creates a reactive binding: whenever we slide the bar, the Python kernel re-calculates the graph and Plotly re-draws it instantly.</p><pre># Create Widgets<br>seed_input = widgets.Text(value=&#39;science&#39;, description=&#39;Search Term:&#39;)<br>top_n_slider = widgets.IntSlider(value=30, min=10, max=100, step=5, description=&#39;Number of Words:&#39;)<br>threshold_slider = widgets.FloatSlider(value=0.9, min=0.5, max=0.99, step=0.01, description=&#39;Connection Threshold:&#39;)<br><br># Use interact to make it reactive<br>ui = widgets.VBox([seed_input, top_n_slider, threshold_slider])<br>out = widgets.interactive_output(visualize_network, {&#39;seed_word&#39;: seed_input, &#39;top_n&#39;: top_n_slider, &#39;threshold&#39;: threshold_slider})<br><br>display(ui, out)</pre><h3>Source Code</h3><p>The notebook is available on GitHub, click <a href="https://github.com/RohanSardar/bert_similarity_search">here</a></p><h3>References</h3><p><a href="https://huggingface.co/docs/transformers/en/model_doc/bert">BERT</a> on Hugging Face</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84dff2a20636" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing ResNet18 Attention with Class Activation Mapping (CAM) in PyTorch]]></title>
            <link>https://rohan-sardar.medium.com/visualizing-resnet18-attention-with-class-activation-mapping-cam-in-pytorch-5c0b56d3f246?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0b56d3f246</guid>
            <category><![CDATA[class-activation-map]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 19:32:57 GMT</pubDate>
            <atom:updated>2025-12-08T19:32:57.709Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step guide using PyTorch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXVal5Z8isPZsWASF_oH_g.png" /><figcaption>Actual representation of CAM of ResNet18</figcaption></figure><h3><strong>The “Black Box” dilemma</strong></h3><p>One of the most significant hurdles in deploying Computer Vision models is the <strong>“</strong><em>Black Box</em><strong>” </strong>problem. In the domain of <strong>Explainable AI (XAI)</strong>, this refers to the inherent trade-off between model complexity and interpretability.</p><p>While simple models like Decision Trees are transparent, Deep Neural Networks (DNNs) like ResNet18 prioritize predictive performance through high-level abstraction. Mathematically, a CNN approximates a complex nonlinear function through successive layers of convolution and pooling. Through this process, the input image is projected onto a high-dimensional feature manifold, allowing the model to separate complex classes effectively but complicating the decision-making process. We can observe the input (pixels) and the output (class probabilities), but the internal logic remains opaque.</p><h4><strong>The Risk of Spurious Correlations</strong></h4><p>This opacity creates a specific danger known as shortcut learning or relying on spurious correlations. If we cannot visualize the model’s attention, we cannot confirm if it is learning semantic features or exploiting biases in the dataset.</p><p>A classic example in XAI literature is the <strong>Wolf vs. Husky</strong> classification. A model might achieve high accuracy not by recognizing the morphological features of a wolf, but by detecting snow in the background. In this case, the model has unknowingly become a “<em>background detector</em>” rather than an object classifier.</p><p>To mitigate this, we use <strong>post-hoc explanations- </strong>techniques applied after model training to visualize the decision boundary. This brings us to <strong>Class Activation Mapping (CAM)</strong>, a method that projects the weights of the final classification layer back onto the convolutional feature maps to highlight the exact regions driving the prediction.</p><h3>Overview of CAM</h3><p>Class Activation Maps (CAM) provide a way to identify which regions of an input image contribute most to a convolutional neural network’s decision for a specific class. CAMs highlight the spatial locations in the feature maps that are most influential for predicting class <em>c</em>, allowing an interpretable visualization of the model’s attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CD05faig_scXegGU_eTeqQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ck_EBvanKe4DSDpQICV14g.jpeg" /><figcaption>Figure taken from <a href="https://arxiv.org/abs/1512.04150">arXiv:1512.04150</a></figcaption></figure><h3>Getting Started</h3><p>To visualize the CAM, we will use PyTorch, OpenCV and other necessary libraries.</p><h4>Imports</h4><p>Here we will first import everything that is required.</p><pre>import numpy as np<br>import cv2<br>import requests<br>import matplotlib.pyplot as plt<br>from torchvision import transforms<br>from torchvision.models import resnet18, ResNet18_Weights<br>import torch.nn.functional as F<br>import torch</pre><h4>Load ResNet18 model weights</h4><p>We load the ResNet18 architecture with pre-trained weights. Using <em>ResNet18_Weights.DEFAULT</em> ensures we use the most up-to-date weights available in Torchvision.</p><pre>model = resnet18(weights=ResNet18_Weights.DEFAULT)<br>model = model.eval()</pre><h4>Define ‘Hook’</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ekgROfC5-1t9rsJ-3ZxGuw.png" /><figcaption>ResNet-18 architecture, taken from ResearchGate</figcaption></figure><p>In PyTorch, a ‘<em>hook</em>’ is a function that automatically executes when data passes through a specific layer and it allows us to inspect internal data- like intermediate feature maps without changing the model architecture.</p><p>PyTorch models usually return only the final classification output. To access the internal feature maps, we register a ‘<em>forward hook</em>’ on <em>layer4</em>. This is the final convolutional layer in ResNet18, meaning it contains the most semantically rich spatial information before the data is flattened.</p><pre>activation = {}<br>def getActivation(name):<br>    def hook(model, input, output):<br>        activation[name] = output.detach()<br>    return hook<br><br># Attach hook to the last convolutional layer (layer4 in ResNet)<br>model.layer4.register_forward_hook(getActivation(&#39;final_conv&#39;))</pre><h4>Load ImageNet class labels</h4><p>ResNet models were trained on the <strong>ImageNet</strong> dataset, so we will fetch its class labels from GitHub.</p><pre>labels_url = &quot;https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt&quot;<br>imagenet_labels = requests.get(labels_url).text.split(&#39;\n&#39;)</pre><h4>Prepare data</h4><p>Here we will convert the images read by OpenCV, which is in BGR format by default to RGB format, so that the model that can the proper color channel. Also we apply the transformations as applied in the model.</p><pre>image_path = &quot;img4.jpg&quot;  <br>original_img_cv2 = cv2.imread(image_path)<br><br># Convert BGR to RGB for Matplotlib and ResNet18 to work<br>original_img_rgb = cv2.cvtColor(original_img_cv2, cv2.COLOR_BGR2RGB)<br><br># Store original dimensions for final resizing<br>h_orig, w_orig, _ = original_img_rgb.shape<br><br># Define transforms<br>preprocess = transforms.Compose([<br>    transforms.ToPILImage(),<br>    transforms.Resize((224, 224)),<br>    transforms.ToTensor(),<br>    transforms.Normalize(<br>        mean=[0.485, 0.456, 0.406], <br>        std=[0.229, 0.224, 0.225]<br>    )<br>])<br><br># Apply transforms and add batch dimension<br>input_tensor = preprocess(original_img_rgb)<br>input_batch = input_tensor.unsqueeze(0)</pre><h4>Forward pass</h4><p>We push the input batch through the model to get the raw logits, which is then used to get the probabilities, class index, class name and its confidence.</p><pre>outputs = model(input_batch)<br><br># Get prediction<br>probabilities = F.softmax(outputs, dim=1)<br>class_idx = torch.argmax(probabilities).item()<br>class_name = imagenet_labels[class_idx]<br>confidence = probabilities[0][class_idx].item() * 100</pre><h4>Generate CAM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqStYL6KZxv74TWeOpYt4g.jpeg" /></figure><p>This is the core CAM logic. Crucially, ResNet18 uses <strong>Global Average Pooling (GAP)</strong> to squash the feature maps (512x7x7) into a flat vector (1x512) before the final layer<strong>.</strong></p><p>To generate the heatmap, we reverse this process. We retrieve the spatial feature maps captured by our hook and the weights from the fully connected layer (1000x512). By computing the dot product of the class-specific weights with the feature maps, we generate a 2D heatmap. This heatmap represents the <strong>attention</strong><em> </em>of the model for that specific class.</p><pre># Fetch features and weights<br>conv_features = activation[&#39;final_conv&#39;].cpu().numpy() # Shape: (1, 512, 7, 7)<br>weight_fc = model.fc.weight.detach().cpu().numpy()     # Shape: (1000, 512)<br><br>def generate_cam(feature_conv, weight_fc, class_idx):<br>    # _ = batch size, nc = number of channels, h=height, w=width<br>    _, nc, h, w = feature_conv.shape<br>    <br>    # Calculate dot product: (weights for class) * (feature map)<br>    # We perform a weighted sum of the 512 feature planes<br>    cam = weight_fc[class_idx].dot(feature_conv.reshape((nc, h*w)))<br>    cam = cam.reshape(h, w)<br>    <br>    # Normalize between 0 and 1<br>    cam = cam - np.min(cam)<br>    cam = cam / np.max(cam)<br>    <br>    # Convert to uint8 (0-255)<br>    return np.uint8(255 * cam)<br><br>cam_gray = generate_cam(conv_features, weight_fc, class_idx)</pre><h4>Visualization</h4><p>Finally, we visualize the results. The raw CAM is small, so we upscale it to the original image dimensions. We apply a color map (<em>JET</em>) to visualize high activation regions in red and low activation in blue. By overlaying this heatmap onto the original image, we can see exactly which pixels influenced the model’s decision. Also, it prints the predicted class index, class name and its confidence.</p><pre>def show_cam_sequence(cam_gray, original_img_rgb):<br>    h, w, _ = original_img_rgb.shape<br><br>    # Resize CAM to match original image size<br>    cam_resized = cv2.resize(cam_gray, (w, h))<br><br>    # Create Heatmap<br>    heatmap = cv2.applyColorMap(cam_resized, cv2.COLORMAP_JET)<br>    heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) <br><br>    # Create Overlay (Weighted sum) = 0.5 * Heatmap + 0.5 * Original<br>    overlay = cv2.addWeighted(heatmap, 0.5, original_img_rgb, 0.5, 0)<br><br>    # Plotting<br>    plt.figure(figsize=(20, 9))<br><br>    # Plot 1: Original Image<br>    plt.subplot(1, 3, 1)<br>    plt.imshow(original_img_rgb)<br>    plt.title(&quot;Original Image&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    # Plot 2: Heatmap Only<br>    plt.subplot(1, 3, 2)<br>    plt.imshow(heatmap)<br>    plt.title(&quot;CAM Heatmap&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    # Plot 3: Overlay, overlapping the original image and the heatmap<br>    plt.subplot(1, 3, 3)<br>    plt.imshow(overlay)<br>    plt.title(f&quot;Overlay&quot;)<br>    plt.axis(&quot;off&quot;)<br><br>    plt.show()<br><br><br>print(f&quot;Predicted Class Index: {class_idx}&quot;)<br>print(f&quot;Predicted Class Name: {class_name}&quot;)<br>print(f&quot;Confidence: {confidence:.2f}%&quot;)<br>show_cam_sequence(cam_gray, original_img_rgb)</pre><h4>Source Code</h4><p>The notebook is available on GitHub, click <a href="https://github.com/RohanSardar/CNNexplainability/blob/main/class_activation_mapping.ipynb">here</a><br>I have also deployed it using a Streamlit web app, check <a href="https://cnn-cam.streamlit.app/">here</a></p><h4>References</h4><p>Learning Deep Features for Discriminative Localization, available on arXiv <a href="https://arxiv.org/abs/1512.04150"><br>arXiv:1512.04150</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0b56d3f246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Generation using Gemma library for JAX]]></title>
            <link>https://rohan-sardar.medium.com/text-generation-using-gemma-library-for-jax-707e2ed480cd?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/707e2ed480cd</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[gemma-3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 20:10:16 GMT</pubDate>
            <atom:updated>2025-07-23T20:10:16.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Official Gemma logo from Google DeepMind" src="https://cdn-images-1.medium.com/max/1024/0*_cXFAX3cjLZuCjTT.jpg" /><figcaption>Image credit: Gemma logo by Google DeepMind. Used here for informational purposes under fair use.</figcaption></figure><p>We all know that Gemma is a family of open-weights Large Language Model (LLM) by Google DeepMind, based on Gemini research and technology.</p><p>The Gemma library is a lightweight Python package designed as an extension of the JAX framework. It offers the performance benefits of JAX such as accelerated computation and automatic differentiation while dramatically reducing the amount of boilerplate code typically required.</p><p>This library provides an easy way to run any Gemma model with just a few lines of code.</p><h3>Installation and Environment</h3><p>To get started, first you need to install the gemma library. And for the environment, I will suggest using cloud based services like <strong>Google Colab</strong> or <strong>Kaggle</strong> notebooks as it offers hassle free setup. Running locally would require a decent GPU with <strong>8GB+ VRAM</strong> and also you need to install JAX properly. Both <strong>Google Colab</strong> and <strong>Kaggle</strong> offers <strong>T4 x2 GPUs</strong> for free with <strong>16GB VRAM</strong> with JAX installed. So the lower parameter models like 1B and 4B should work seamlessly.</p><pre>pip install gemma</pre><p>After installation, next thing to do is to import the library and other necessary things.</p><pre>from gemma import gm<br>from IPython.display import Markdown</pre><p>Here I have imported Markdown to properly format the generated output and display it.</p><h3><strong>Loading Gemma</strong></h3><p>Next thing is to load a Gemma model and its checkpoints.</p><pre>model = gm.nn.Gemma3_1B()<br>params = gm.ckpts.load_params(gm.ckpts.CheckpointPath.GEMMA3_1B_IT)</pre><p>For now, I have used <strong>Gemma3 1B</strong> model as it is the smallest among all other variants, so it has the highest probability to work without facing any error.</p><h3>Chatting with the model</h3><p>For chatting with the model, multi_turn=True parameter of gm.text.ChatSampler function has to be set. This enables the model to remember the previous context, enabling us to ask follow-up questions. If multi_turn=False, it doesn&#39;t remember any previous chat context and hence a complete fresh single-turn conversation starts.</p><pre>chat_sampler = gm.text.ChatSampler(<br>    model=model,<br>    params=params,<br>    max_out_length=512,<br>    sampling=gm.text.RandomSampling(temperature=0.9),<br>    multi_turn=True,<br>)</pre><p>The number of output tokens can be set via the max_out_length: int = &lt;output_token_count&gt; parameter. To control sampling randomness, use gm.text.RandomSampling(temperature: float = &lt;temperature&gt;).</p><p>Next thing is to make a function which uses the Markdown function imported earlier, to display the generated output text in proper format within the notebook.</p><pre>def render_output(prompt: str):<br>    return Markdown(chat_sampler.chat(prompt))</pre><p>Now ask anything to using this render_output(prompt: str) function. Write your prompt as a parameter to this function.<br>For example, I gave the prompt:</p><pre>render_output(&#39;Give one line of poetry that connects &quot;ashes&quot; and &quot;dreams&quot;.&#39;)</pre><p>And it gave an output this like this:</p><blockquote>As ashes whisper, dreams fade into the night.</blockquote><p>Then I asked a follow-up question:</p><pre>render_output(&#39;Elaborate the poetry in short&#39;)</pre><p>It then gave the following text as output:</p><blockquote>Okay, here are a few options, depending on the specific feeling you’re going for:</blockquote><blockquote><strong>Option 1 (Melancholy &amp; Loss):</strong></blockquote><blockquote>“Ashes bloom where vibrant dreams once flew, a silent, fading hue.”</blockquote><blockquote><strong>Option 2 (Hopeful &amp; Transcendent):</strong></blockquote><blockquote>“Consumed by ashes, hopes ignite anew, within a dream’s lingering view.”</blockquote><blockquote><strong>Option 3 (Simple &amp; Evocative):</strong></blockquote><blockquote>“The embers glow, where lost dreams now sleep, in silent ashes, secrets keep.”</blockquote><blockquote>To help me tailor it even more perfectly, could you tell me:</blockquote><blockquote><strong>What feeling are you trying to evoke?</strong> (Sadness, wonder, remembrance, etc.)</blockquote><blockquote><strong>What kind of imagery are you leaning towards?</strong> (Dark, bright, ethereal, etc.)</blockquote><h3>Sampling with prompt</h3><p>gm.text.Sampler can be used perform efficient sampling. In instruction-tuned Gemma, dialogue segments are wrapped with &lt;start_of_turn&gt; and &lt;end_of_turn&gt;. The tag following &lt;start_of_turn&gt; specifies the speaker:</p><ul><li>user — human input</li><li>model — Gemma&#39;s output</li></ul><p>These markers clarify speaker roles and maintain structured multi-turn interaction.</p><p>For example, you can write:</p><pre>prompt = &quot;&quot;&quot;&lt;start_of_turn&gt;user<br>Give me a list of famous footballers in the world&lt;end_of_turn&gt;<br>&lt;start_of_turn&gt;model<br>&quot;&quot;&quot;</pre><p>And then you can pass your prompt to render_output(prompt: str) function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707e2ed480cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of LLMs]]></title>
            <link>https://rohan-sardar.medium.com/fundamentals-of-llms-b7565fb6da33?source=rss-275add068eb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7565fb6da33</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Rohan Sardar]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 09:49:28 GMT</pubDate>
            <atom:updated>2024-07-29T09:49:28.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0paoGvIhHhRzMoFD8WyEfQ.jpeg" /></figure><p>Large Language Models (LLMs) have significantly transformed the landscape of artificial intelligence (AI) by enabling machines to understand and generate human-like text. Tools like OpenAI’s GPT-4, Google’s BERT, and others have revolutionized how we interact with technology, impacting fields from customer service to content creation.</p><h3>What is a Large Language Model (LLM) ?</h3><p>Today almost everybody has heard and even used tools such as <strong>ChatGPT</strong>, <strong>Gemini</strong>, etc. Many of us use these tools in our everyday lives. These tools have almost changed our lives in the last few years. Now you may be thinking how does this tool work and how does it generate such texts that look so realistic?</p><p>The idea behind this is <strong>Generative AI</strong> or in short <strong>GenAI</strong>. This is a type of AI which can generate realistic texts, images and other contents based on the user prompt. These AI model are trained on a vast amount of training data and based on its learning it generates new content.</p><p>A large language model is a type of AI model which is capable of generating probabilistic texts. This is said to be probabilistic because the language model assigns probabilities to every words or tokens in its vocabulary which it has learned during its training on large datasets and based on this probability and its semantic relationship, it generates the texts.</p><p><em>Consider an example, suppose you ask a LLM to complete this sentence: “The sky is ____”.</em></p><p><em>You know that it should be blue . Now how does LLM answers this ? So after receiving the user prompt, the LLM assigns probabilities to words on its vocabulary based on its semantic relationship. Suppose it assigns the following:</em></p><ul><li><em>blue (probability = 0.91)</em></li><li><em>red (probability = 0.03)</em></li><li><em>dark (probability = 0.01)</em></li><li><em>aeroplane (probability = 0.00002)</em></li><li><em>warship (probability = 0.00000001)</em></li></ul><p><em>Here you can see </em><strong><em>blue</em></strong><em> has the highest probability, and other colors like </em><strong><em>red</em></strong><em> and </em><strong><em>dark</em></strong><em> has much lower probability. Words like </em><strong><em>aeroplane</em></strong><em> and </em><strong><em>warship</em></strong><em> has almost 0 probability. Why is it so ? This is because the LLM identified based on semantics of the received prompt that the answer must be in some form of color, so it has distributed the probabilities mostly to colors and objects like </em><strong><em>aeroplane </em></strong><em>and </em><strong><em>warship</em></strong><em> are not semantically related, hence it received around 0 probability. Now among the colors, </em><strong><em>blue</em></strong><em> got the highest probability among all, so the LLM will predict the output to be </em><strong><em>blue</em></strong><em>.</em></p><h3>LLM Architectures</h3><p>Now let’s discuss about the architecture of a LLM. Basically it has two parts: <strong>encoder</strong> and <strong>decoder</strong>. Some LLM also use combination of them: <strong>encoder-decoder </strong>architecture. These things are based on the <strong>Transformer Architecture</strong>, which revolutionized AI few years ago. This architecture was published in the famous research paper titled: “<strong>Attention Is All You Need</strong>”</p><h3>Encoder</h3><p>Generally encoders do the task of embeddings. Now embeddings refers to the numeric representation of words based on its semantics or its meaning. These embeddings are generally multi-dimensional vectors which are stored in vector databases.</p><p><em>Example: BERT, Embed-Light, etc.</em></p><h3>Decoder</h3><p>Decoders do the task of generating the next word as output after taking a sequence of words as input. One thing to note is that decoders can only generate a single word or token at a time. So it has to run multiple times to generate a proper output. This is also one of the reason why LLMs streams text while generating output. If they do not show streaming output then the user would have to wait until it completes generating the total output.</p><p>Decoders are very efficient for generating text outputs. So this architecture based LLMs are used for generating answers, chat, new creative contents, etc.</p><p><em>Example: ChatGPT, Llama, etc.</em></p><h3>Encoder-Decoder</h3><p>This type of architecture is a combination of both of them. The encoder part converts the prompt into embeddings then the decoder part use those embeddings to generate the text output one at a time similar to above mentioned decoder only architecture. The main purpose of this architecture is for translation from one language to another, time-series applications, etc.</p><p><em>Example: T5, etc.</em></p><h3>Hyperparameters</h3><p><em>Often while using LLM you may be confused while seeing hyperparameters like Temperature, Top K, Top P, Max Tokens, etc. and might think what does these things do, so here are what it means:</em></p><h3>Temperature</h3><p>It is a hyperparameter that flattens the distribution of probability of words in its vocabulary. When this parameter is increased, the likeliness of producing a diverse creative output increases. It does not necessarily alter the probability of all the words, instead it normalizes the probability, so the chance of picking a less probable word increases.</p><p>Increase this parameter when you would like to generative creative responses.</p><p>Another thing to note here is that when temperature is set to 0, it is called as <strong>greedy decoding</strong> because it only selects the highest probability words or tokens, it is also called as <strong>deterministic decoding</strong>. This is because setting temperature to 0 will always output the same response, no matter how many times you ask the same question.</p><h3>Top K</h3><p>This hyperparameter is used to set the limit of the LLM vocabulary to top ‘k’ number of tokens sorted from highest to lowest probability. Here ‘k’ is an exact number.</p><p>Like if you select top k = 5, then the LLM will generate the next token from the top 5 options.</p><h3>Top P</h3><p>It is used to limit the vocabulary of the LLM on the basis of sum of probabilities of the tokens. The cumulative sum of all tokens is 1. So when you select any value between 0 and 1, the LLM limits itself to only those tokens whose cumulative sum equals to the given value.</p><p>Suppose you set top p = 0.92, so cumulative sum of the tokens are considered until it reaches 0.92.</p><h3>Stop Sequence</h3><p>It is a symbol or string which is used to stop the generation of output. The model will stop generating more content once when it reaches the given symbol or string.</p><p>If you assign period(.) as stop sequence, then the model will stop after generating the first sentence.</p><h3>Max Tokens</h3><p>This hyperparameter controls the number of tokens or words the model should generate as output.</p><p>If you assign a large value of max token, then the LLM will generate longer responses.</p><h3>Frequency and Presence Penalties</h3><p>Such hyperparameters are used to restrict the use of same token in a response. Frequency penalties penalizes based on the number of times a particular token appeared in the response while presence penalties penalizes based on its previous appearance.</p><p>These are used to generate creative contents as the LLM tries to avoid generating the same token.</p><h3>Prompting Strategies</h3><p><em>We all know prompting is the way we communicate with a LLM. But often it happens that the LLM could not generate the type of response we expect from it. In such cases, we can use different prompting strategies. In fact it is one of the best practices to effectively utilize the power of LLMs. These strategies are part of a broader field known as prompt engineering.</em></p><p><strong>Prompt engineering </strong>is a process of designing or writing prompts in such a way that the LLM understand the context and generates the desired type of response.</p><h3>In-context Learning</h3><p>This is a prompting technique where examples or demonstrations of the task to perform by the LLM is given. Based on given example, it tries to respond to the given query in a similar context.</p><h3>K-shot Prompting</h3><p>In this technique ‘k’ number of examples are provided in the prompt to let the LLM know the intention and context of the task we are trying to achieve. Here ‘k’ is just a number. If you provide 1 example, it is <strong>one-shot prompting</strong>, similarly 2, 3 and so on. But generally we can say terms like <strong>few-shot prompting</strong> if you provide a few examples and <strong>multi-shot prompting</strong> if you provide a number of examples. <strong>Zero-shot prompting</strong> is when you don’t provide any example at all.</p><p><em>Consider the prompt where we are providing 3 examples to let the LLM understand the context:</em></p><p><em>“Predict the city name:</em></p><ul><li><em>India: New Delhi</em></li><li><em>Nepal: Kathmandu</em></li><li><em>Sri Lanka: Colombo</em></li><li><em>Thailand: “</em></li></ul><p><em>Here the LLM understands from the given examples that we are asking for the name of the capital city of the country. So the LLM will answer the name of the capital city of Thailand which is Bangkok.</em></p><h3>Chain-of-Thought</h3><p>This strategy is used to direct the LLM to show intermediate reasoning steps. This is particularly useful when solving complex problems.</p><p><em>If you are asking directly how many minutes are there in a week we can ask in this way:</em><br><em>“A week has 7 days. 1 day have 24 hours. 1 hour have 60 minutes. How many minutes are there in a week ?”</em></p><h3>Least-to-Most</h3><p>Here we direct the LLM to break down complex problems into easily solvable parts. First solve the easy part and then move on to more complex parts. Then combining those parts the actual response is generated.</p><p><em>Suppose you want to generate an essay on </em><strong><em>climate change. </em></strong><em>So instead of directly asking the LLM to do so, asking a series of questions like:</em></p><ul><li><em>“What is Climate Change ?</em></li><li><em>How does it affect the environment ?”</em></li></ul><p><em>and so on, this will help to get a better response.</em></p><h3>Step-Back</h3><p>In this strategy LLM do abstractions to derive the high level concepts from the prompt. Now using those concepts as guidance the LLM tries to answer the prompt.</p><p><em>For example, if you ask a numerical question from thermodynamics, the LLM might ask you if this question is from physics or chemistry because you might know that thermodynamics have some different principles from physics’ point of view and chemistry’s point of view. So based on your response to LLM, it would generate the required output.</em></p><h3>What to do when LLM still does not produce desired output ?</h3><p><em>Sometimes it happens that even after trying all prompting strategies, the LLM fails to answer. However training a LLM from scratch is not the best option because it requires a lot of resources and finances, so it is not feasible for normal people like us. Here are some of the ways to consider in such situations:</em></p><h3>Fine-Tuning</h3><p>It is a way to improve the performance of the LLM on specific tasks which it couldn’t do earlier. It involves training a small part of the LLM to a domain-specific data. Various cloud providers provide variety of ways to do so.</p><h3>RAG</h3><p>RAG or Retrieval Augmented Generation is ability of the LLM to search and fetch relevant information from a large vector database corpuses of different enterprises. This feature enables LLM to answer to those queries which it has no information during its training.</p><p><em>During the initial days of LLMs, it failed to answer questions from recent events and it had answered</em> <em>that its knowledge base is limited to the training data which was at least a year old. But now if you ask a LLM any question related to recent incidents, it can easily answer correctly by fetching the relevant information.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7565fb6da33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>