<?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 Amarpreet Singh on Medium]]></title>
        <description><![CDATA[Stories by Amarpreet Singh on Medium]]></description>
        <link>https://medium.com/@soniamarpreet17?source=rss-3d9d93721587------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ymhf5ydTZnrs0pZ0.</url>
            <title>Stories by Amarpreet Singh on Medium</title>
            <link>https://medium.com/@soniamarpreet17?source=rss-3d9d93721587------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:24:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@soniamarpreet17/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Attention in Transformers — Intuitively Explained]]></title>
            <link>https://medium.com/data-science-collective/attention-in-transformers-intuitively-explained-bd2f0f46d32a?source=rss-3d9d93721587------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd2f0f46d32a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Amarpreet Singh]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 13:06:56 GMT</pubDate>
            <atom:updated>2026-06-12T14:25:17.452Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Intuitive Guide I Wish I Had When Learning LLMs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb_6xCOBvDra-6q2u0ji9A.png" /><figcaption>Image generated through AI</figcaption></figure><p>Most explanations of Attention start with this formula:</p><p>Attention(Q,K,V) = Softmax(QKᵀ/√dk)V</p><p>The problem?</p><p>Most beginners have no idea what Q, K, V, dk, or even “attention” mean.</p><p>I certainly didn’t.</p><p>After spending days understanding how embeddings, attention, training, inference, and contextual representations actually fit together, I realised that attention becomes surprisingly intuitive once you understand the problem it is trying to solve.</p><p>This article is my attempt to explain Attention from first principles.</p><p>No magic.<br>No hand-waving.<br>Just a step-by-step journey from STATIC embeddings to CONTEXTUAL embeddings.</p><h3>The Real Problem Attention Solves</h3><p>Suppose we have the word: <strong>bank</strong></p><p>What does it mean?</p><p>In: “I deposited money in the bank”</p><p>→ bank means a <strong>financial institution.</strong></p><p>But in: “I sat near the river bank”</p><p>→ bank means the <strong>side of a river.</strong></p><p>The problem is that language is <strong>contextual</strong>.</p><p>The meaning of a word depends on the <strong>surrounding words.</strong></p><p>Traditional embedding approaches (like TF-IDF, Word2Vec) assign one vector to each token which are present in the whole corpus:</p><p>bank → [0.2, 0.5, -0.1, …]</p><p>This is called a <strong>static embedding</strong>. This remains the same for the token, no matter in which <strong>context </strong>it appears.</p><p>A single static vector cannot perfectly represent every meaning of the word bank.</p><p>This is where Attention enters the picture.</p><p>Attention was invented because:</p><p>Static embeddings were not good enough to capture complex context-dependent relationships and long-range dependencies in language. <strong>Attention helps us to create contextual embeddings of the tokens.</strong></p><p>If attention wasn’t necessary:</p><p>Word2Vec + MLP would have beaten Transformers.</p><p>They didn’t.</p><p>Because language requires: <strong>Context</strong></p><p>And Attention is an extremely effective mechanism for modelling context.</p><p>Attention works by asking:</p><p>“How much should each surrounding token <strong>contribute </strong>to <strong>updating </strong>the representation of this token in this specific context?”</p><h3>Why Is Self-Attention Such A Big Deal?</h3><p><strong>Transformers did not invent contextual embeddings.</strong></p><p>Before Transformers, contextual embeddings were typically created <strong>using RNNs and LSTMs. </strong>Attention mechanisms also existed in RNN-based architectures, but Self-Attention was introduced as the core building block of Transformers.</p><p>For example, when processing:</p><p>“I deposited money in the bank”</p><p><strong>an RNN would generate</strong>:</p><p>h_bank = f(h_(t-1), x_t)</p><p>where h_bank is a contextual representation built from the <strong>compressed history of all previous tokens.</strong></p><p>This worked, but it created an <strong>information bottleneck (very heavily in longer sequences) </strong>because distant information had to pass through many intermediate states before reaching the current token.</p><p>Self-Attention takes a different approach.</p><p>Instead of compressing the entire history into a single hidden state, it <strong>directly combines information from relevant tokens</strong>:</p><p>h_bank = 0.70(v_money) + 0.20(v_deposit) + 0.10(v_bank)</p><p>This allows the model to directly access important tokens regardless of <strong>how far away they are</strong> in the sequence. Self-Attention significantly mitigated the <strong>long-range dependency problem</strong> of RNNs and LSTMs by allowing tokens to directly interact with distant tokens in a single step.</p><p><em>Why is it called Self-Attention?</em></p><p>Because every token can attend to all other tokens in the <strong>same sequence, including itself.</strong></p><p>This ability to form direct connections between distant tokens significantly mitigated the long-range dependency problem of RNNs and LSTMs and became one of the key reasons Transformers outperformed earlier architectures.</p><h3>Training vs Inference: The Most Important Distinction</h3><p>During training of LLMs, Attention is not used to improve static embeddings directly. Instead, it is used to create contextual representations that help the model <strong>solve its training objective</strong>.</p><ul><li>In <strong>Generative models</strong>, these contextual representations (from attention) are used to predict tokens <strong>(MLM/NTP)</strong>. Also, improving static embeddings is not Attention’s primary purpose; it ultimately leads to better static embeddings E for each token in the corpus. The resulting prediction loss is backpropagated through the Neural network model, gradually improving the <strong>static embedding matrix E along with WQ, WK, WV, FFN, and other model parameters.</strong></li><li>In <strong>Embedding models</strong>, these contextual representations (from attention) are further pooled and transformed into the <strong>final text embeddings</strong> used for similarity learning.</li></ul><figure><img alt="Training Flow for Generative LLMs vs Embedding LLMs" src="https://cdn-images-1.medium.com/max/1024/1*U3xCj5hf-Nnqab0ejv-58g.png" /><figcaption>Training flow of Generative LLMs vs Embedding LLMs</figcaption></figure><p>In this blog, we will take the case of Generative LLMs and explain the Attention.</p><h3><strong>Training Flow:</strong></h3><p>1. Initialise random model parameters</p><ul><li>Random Embedding Matrix E</li><li>Random WQ</li><li>Random WK</li><li>Random WV</li><li>Random FFN</li><li>Random Output Layer</li></ul><p>2. Give the model a prediction task</p><p>Examples:<br>- MLM (Masked Language Modelling)<br>- NTP (Next Token Prediction)</p><p>Example:<br>“I deposited money in the [MASK]”</p><p>Target:<br>“bank”</p><p>3. Look up token embeddings from E</p><p>I → E[I]<br>deposited → E[deposited]<br>money → E[money]<br>[MASK] → E[MASK]</p><p>The embedding matrix E contains one learned static embedding for every token in the vocabulary. Each token is converted into its corresponding embedding through a lookup operation.</p><p>4. Add positional information</p><p>For every token i:</p><p>Xi = Ei + Pi</p><p>where:</p><p>Ei = static token embedding<br>Pi = positional encoding<br>Xi = final position-aware token representation</p><p>The model now knows both:</p><p>What the token means + Where the token appears</p><p>5. Create Q, K, V vectors</p><p>Q = X⋅WQ<br>K = X⋅WK<br>V = X⋅WV</p><p>where:</p><p>X = E + P</p><p>because Q,K,V are created from the <strong>position-aware representation</strong>, not raw embeddings.</p><p>6. Apply Attention</p><p>Attention(Q,K,V) = Softmax(QKᵀ/√dk)V</p><p>This creates contextual embeddings from both token meaning and token position.</p><p>Example:</p><p>bank (generic) → bank_financial</p><p>because of:</p><p>Position Information + Nearby Words (money, deposited)</p><p>7. Process contextual embeddings</p><p>Attention Output<br> ↓<br>Residual<br> ↓<br>LayerNorm<br> ↓<br>FFN<br> ↓<br>Residual<br> ↓<br>LayerNorm</p><p>8. Make prediction</p><p>Example:</p><p>“I deposited money in the [MASK]”</p><p>Prediction: “river”</p><p>9. Calculate Loss</p><p>Actual:<br>“bank”</p><p>Predicted:<br>“river”</p><p>High Loss</p><p>10. Backpropagation</p><p>Gradients flow backwards through:</p><p>Output Layer<br>FFN<br>Attention<br>WQ<br>WK<br>WV<br>E</p><p>11. Update parameters</p><p>Embedding Matrix E<br>WQ<br>WK<br>WV<br>FFN<br>Output Layer</p><p>become slightly better</p><p>12. Repeat many times</p><p>Eventually, the model learns:</p><p>- Better static embeddings (E)<br>- Better attention patterns (WQ, WK, WV)<br>- Better transformations (FFN)</p><p>13. Training Complete</p><p>Store:</p><ul><li>E</li><li>WQ</li><li>WK</li><li>WV</li><li>FFN</li><li>Output Layer</li></ul><p>inside the model.</p><p><strong>Contextual embeddings are NOT stored.</strong> They are discarded. Contextual embeddings <strong>help to improve</strong> the static embedding matrix E. One reason modern embedding matrices E are so powerful is that they were <strong>learned inside a contextual model</strong> rather than a purely static one.</p><h3><strong>Inference Flow:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XU8NcxLv9HfYMmeVCzJNEg.png" /><figcaption>Inference flow of Generative LLMs vs Embedding LLMs</figcaption></figure><p>Input:<br>“I deposited money in the bank”</p><p>Static embeddings of the tokens in the text retrieved from E<br>↓<br>Positional encodings added<br>↓<br>Position-aware token representations<br>↓<br>Attention converts Position-aware token representations to contextual embeddings for the tokens<br>↓<br>Next Token Probabilities<br>↓<br>Token Selection<br>↓<br>Generated Response</p><h3>What Happens When The Model Sees A New Word?</h3><p>Suppose we send:</p><p>abcdefxyz123</p><p>The model probably does not have a dedicated embedding E for that exact string.</p><p>Instead:</p><p>abcdefxyz123<br>↓<br>Tokenizer<br>↓<br>Convert into sub-tokens : abc | d | ef | xy | z | 1 | 2 | 3<br>↓<br>Embeddings of sub-tokens retrieved from E<br>↓<br>Attention creates contextual representations<br>↓<br>Pooling / Projection<br>↓<br>Final contextual embedding of the token “abcdefxyz123”</p><p>This is why modern models can handle words they have never explicitly seen before.</p><h3>Understanding Positional Encodings</h3><p>For every token i:<br> <br> X_i = E_i + P_i<br> <br> where:<br> <br> E_i = static token embedding retrieved from E<br> P_i = positional encoding<br><strong> X_i = final position-aware token representation</strong></p><p>The positional encoding vector P_i has exactly the same dimension as E_i. Otherwise, they cannot be added.</p><p>E_i answers: “What does this token mean in <strong>embedding space</strong>?”</p><p>P_i answers: “Where does this token appear <strong>within the sequence</strong>?”<br> <br> The resulting vector X_i is what actually enters the Attention mechanism.</p><p><strong>Now, how do we get P_i?</strong></p><p>We have 3 methods to get positional encodings: Learned Positional Embeddings, Sinusoidal Positional Encoding (Original Transformer), RoPE (Modern LLMs)</p><p><strong>Sinusoidal Positional Encoding:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8hci3nCYiVrXzXHeQopjw.png" /><figcaption>Image Generated by AI</figcaption></figure><p>Intuition:</p><ul><li>Every position receives a unique vector.</li><li>Nearby positions receive similar vectors.</li><li>Far-away positions receive very different vectors.</li><li>The vectors are generated mathematically and never learned.</li></ul><p>Example: “I deposited money in the bank”</p><p>I → pos = 0<br>deposited → pos = 1<br>money → pos = 2<br>in → pos = 3<br>the → pos = 4<br>bank → pos = 5</p><p>Assume positional vector size: d_model = 4</p><p>d_model is equal to the vector size of the static embedding E.</p><p>For d_model = 4, <strong>each token</strong> position gets 4 values:</p><p>PE(pos,0) = sin(pos)<br>PE(pos,1) = cos(pos)<br>PE(pos,2) = sin(pos / 100)<br>PE(pos,3) = cos(pos / 100)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOsjMD%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOsjMD%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOsjMD%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="339" frameborder="0" scrolling="no"><a href="https://medium.com/media/777fdf35a51f95b93352e0ea9a6fb92e/href">https://medium.com/media/777fdf35a51f95b93352e0ea9a6fb92e/href</a></iframe><p>Now for bank:</p><p>E_bank = static vector of bank<br>P_5 = position information of bank</p><p>So:</p><p>X_bank = E_bank + P_5</p><p>Example:</p><p>E_bank = [0.20, 0.70, 0.50, 0.10]</p><p>P_5 = [-0.9589, 0.2837, 0.0500, 0.9988]</p><p>Then:</p><p>X_bank = [-0.7589, 0.9837, 0.5500, 1.0988]</p><p>This <strong>X_bank goes into attention calculation</strong>, not raw E_bank.</p><p><strong><em>Note:</em></strong><br> The original Transformer paper used sinusoidal positional encodings, while many modern models use learned positional embeddings or RoPE (Rotary Positional Embeddings).</p><h3>Understanding Query, Key and Value</h3><p>This is where most explanations become confusing.</p><p>Let’s define them using a token A.</p><h3>Query</h3><p>A vector used to determine how much other tokens should contribute to updating token A.</p><p>XA = EA + PA</p><p>qA = XA · WQ</p><p>where, EA = Trained static embedding vector of token A, retrieved from the learned static embedding matrix E</p><p>PA = Positional encoding of token A</p><p><strong>XA = Position-aware representation of token A</strong></p><p>WQ = Trained Global Query Weight matrix</p><h3>Key</h3><p>A vector used by other tokens to determine how useful token A is for updating their representations.</p><p>kA = XA · WK</p><p>where WK = Trained Global Key Weight matrix</p><h3>Value</h3><p>A vector containing the information token A can contribute when another token attends to it.</p><p>vA = XA · WV</p><p>where WV = Trained Global Value Weight matrix</p><p><strong>WQ, WK, WV are global weight matrices in the LLM shared across all tokens.</strong></p><p>The easiest way to understand them is:</p><ul><li>Query = How much should each other token contribute to updating me</li><li>Key = How useful am I for updating other tokens?</li><li>Value = What information do I provide when another token attends to me?</li></ul><h3>Computing Attention Scores</h3><p>For every token, we compare its Query with the Keys of all tokens.</p><p>For example:</p><p>qbank · kI<br>qbank · kmoney<br>qbank · kdeposit<br>qbank · kbank</p><p>These comparisons form the matrix:</p><p>QKᵀ =</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHThPstbimMAD6IILUl2fw.png" /></figure><p>This matrix contains raw attention/similarity scores.</p><p>Each row corresponds to one Query token.<br>Each column corresponds to one Key token.<br>Each cell contains the similarity score between a Query and a Key.</p><p>Now, Scaled attention scores = QKᵀ / √dk</p><h3>Why Divide By √dk?</h3><p>As vector dimensions become larger, dot products naturally become larger.</p><p>Large values make Softmax extremely peaky and unstable.</p><p>To prevent this, we use 1/√dk as a multiplier.</p><p>Without 1/√dk​​, the attention scores (QKᵀ) become too large. After Softmax, almost all the attention weight gets assigned to a single token while the remaining tokens receive <strong>nearly zero attention</strong>, making learning unstable.</p><p>This keeps values in a healthy numerical range while preserving relative rankings.</p><h3>Why Softmax?</h3><p>Without Softmax:</p><ul><li>Scores can be negative.</li><li>Scores can be arbitrarily large.</li><li>They don’t sum to 1.</li></ul><p>Softmax converts scores into a probability distribution:</p><p>70% attention here<br>20% attention there<br>10% attention there</p><p>Where 70%, 20%, 10% are calculated by:</p><p><strong>Attention weights</strong> = Softmax(QKᵀ / √dk)</p><p>Now the model has an attention budget.</p><p>It can decide how much focus each (other) token deserves to get a final contextual embedding of a token A.</p><h3>Creating Contextual Embeddings</h3><p>Attention weights are:</p><p>Softmax(QKᵀ / √dk)</p><p>The attention output is:</p><p>Z = Softmax(QKᵀ / √dk)V</p><p>This is the contextualised representation produced by attention.</p><p>For example:</p><p>“I deposited money in the bank”</p><p>might produce a final contextual representation of bank here:</p><p>hbank = 0.70(v_money) + 0.20(v_deposit) + 0.10(v_bank)</p><p>(v is the value vector for that token)</p><p><strong>Here, the word bank becomes strongly associated with financial concepts.</strong></p><p>For:</p><p>“I sat near the river bank”</p><p>attention might produce a final contextual representation of bank here:</p><p>hbank = 0.80(v_river) + 0.15(v_near) + 0.05(v_bank)</p><p>(v is the value vector for that token)</p><p><strong>Now bank becomes associated with rivers.</strong></p><p>The same token starts with the same static embedding but ends with different contextual meanings.</p><p>That is the magic of attention.</p><h3>Final Mental Model</h3><p>Static embeddings answer:</p><p>“What does this token generally mean?”</p><p>Attention answers:</p><p>“What does this token mean here, given its position and the surrounding tokens?”</p><p>Transformers combine both ideas:</p><h4>Static Knowledge (E)<br>+<br>Contextual Understanding (Attention)</h4><p>What started as a mysterious formula,</p><p>Attention(Q,K,V) = Softmax(QKᵀ/√dk)V</p><p>turned out to be just a simple idea:</p><p><em>Every token learns its meaning by looking at the tokens around it.</em></p><p>That one idea gave us contextual embeddings.<br>Contextual embeddings gave us Transformers.<br>Transformers gave us modern LLMs.</p><p><strong>And modern LLMs changed AI forever.</strong></p><p>Now we understand why Attention became one of the most important ideas in AI and how Transformers learned to model human language so effectively.</p><p>Rightly said:</p><p><strong>Attention Is All You Need!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd2f0f46d32a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/attention-in-transformers-intuitively-explained-bd2f0f46d32a">Attention in Transformers — Intuitively Explained</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Off-Beat Approach to Train-Test-Validation Split Your Dataset]]></title>
            <link>https://medium.com/data-science/an-off-beat-approach-to-train-test-validation-split-your-dataset-esp-small-ones-650492b735fb?source=rss-3d9d93721587------2</link>
            <guid isPermaLink="false">https://medium.com/p/650492b735fb</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amarpreet Singh]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 13:24:39 GMT</pubDate>
            <atom:updated>2024-07-12T10:15:12.656Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ensuring distributional integrity in splits of small datasets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cF-MJtmL1hR7D_iNPkunbg.jpeg" /><figcaption>Generated with Microsoft Designer</figcaption></figure><p>We all require to sample our population to perform <strong>statistical analysis</strong> and gain insights. When we do so, the aim is to ensure that our sample’s distribution closely matches that of the population.</p><p>For this, we have various methods: <strong>simple random sampling</strong> (where every member of the population has an equal chance of being selected), <strong>stratified sampling</strong> (which involves dividing the population into subgroups and sampling from each subgroup), <strong>cluster sampling</strong> (where the population is divided into clusters and entire clusters are randomly selected), <strong>systematic sampling</strong> (which involves selecting every nth member of the population), etc etc. Each method has its advantages and is chosen based on the specific needs and characteristics of the study.</p><p>In this article, we won’t be focusing on sampling methods themselves per se, but rather on using these concepts to split the dataset used for machine learning approaches into <strong>Train-Test-Validation</strong> sets. These approaches work for all kinds of <strong>Tabular data</strong>. We will be working in Python here.</p><p>Below are some approaches that you already might know:</p><h3>1. Simple Train-Test-Val Split</h3><p>This approach uses <strong>random-sampling</strong> method.<br>Example code:</p><pre>from sklearn.model_selection import train_test_split<br># Assuming X is your feature set and y is your target variable<br>X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)<br>X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)</pre><h3>2. Stratified Train-Test-Val Split</h3><p>This approach ensures that the splits maintain the <strong>same proportion of classes</strong> as the original dataset (with random sampling again of course), which is useful for imbalanced datasets. This approach will work when your target variable is <strong>not a continuous variable.</strong></p><pre>from sklearn.model_selection import train_test_split<br><br># Stratified split to maintain class distribution<br>X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, stratify=y, random_state=42)<br>X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, stratify=y_temp, random_state=42)</pre><h3>3. K-Fold Cross-Validation</h3><p>In K-Fold cross-validation, the dataset is split into k subsets (folds). The model is trained on k-1 folds and tested on the remaining fold. This process is repeated k times.</p><pre>from sklearn.model_selection import KFold, train_test_split<br><br>kf = KFold(n_splits=5, shuffle=True, random_state=42)<br><br>for train_index, test_index in kf.split(X):<br>    X_train, X_test = X[train_index], X[test_index]<br>    y_train, y_test = y[train_index], y[test_index]<br>    <br>    # Further split X_train and y_train into train and validation sets<br>    X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)<br>    <br>    # Now you have X_train, X_val, X_test, y_train, y_val, y_test for each fold<br>    # You can now train and evaluate your model using these sets</pre><h3>4. Stratified K-Fold Cross-Validation</h3><p>As the name suggests, this is a combination of Stratified sampling and K-fold cross-validation.</p><pre>from sklearn.model_selection import StratifiedKFold, train_test_split<br><br>skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)<br><br>for train_index, test_index in skf.split(X, y):<br>    X_train, X_test = X[train_index], X[test_index]<br>    y_train, y_test = y[train_index], y[test_index]<br>    <br>    # Further split X_train and y_train into train and validation sets<br>    X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, stratify=y_train, random_state=42)<br>    <br>    # Now you have X_train, X_val, X_test, y_train, y_val, y_test for each fold<br>    # You can now train and evaluate your model using these sets</pre><p>Full example usage:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score<br><br># Initialize lists to store the scores for each fold<br>accuracy_scores = []<br>precision_scores = []<br>recall_scores = []<br>f1_scores = []<br><br>skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)<br><br>for train_index, test_index in skf.split(X, y): #y is a categorical target variable<br>    X_train, X_test = X[train_index], X[test_index]<br>    y_train, y_test = y[train_index], y[test_index]<br>    <br>    # Further split X_train and y_train into train and validation sets<br>    X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, stratify=y_train, random_state=42)<br>    <br>    # Train the model<br>    model = LogisticRegression(random_state=42)<br>    model.fit(X_train, y_train)<br>    <br>    # Validate the model<br>    y_val_pred = model.predict(X_val)<br>    val_accuracy = accuracy_score(y_val, y_val_pred)<br>    val_precision = precision_score(y_val, y_val_pred, average=&#39;weighted&#39;)<br>    val_recall = recall_score(y_val, y_val_pred, average=&#39;weighted&#39;)<br>    val_f1 = f1_score(y_val, y_val_pred, average=&#39;weighted&#39;)<br>    <br>    print(f&quot;Validation Scores - Accuracy: {val_accuracy}, Precision: {val_precision}, Recall: {val_recall}, F1 Score: {val_f1}&quot;)<br>    <br>    # Test the model<br>    y_test_pred = model.predict(X_test)<br>    test_accuracy = accuracy_score(y_test, y_test_pred)<br>    test_precision = precision_score(y_test, y_test_pred, average=&#39;weighted&#39;)<br>    test_recall = recall_score(y_test, y_test_pred, average=&#39;weighted&#39;)<br>    test_f1 = f1_score(y_test, y_test_pred, average=&#39;weighted&#39;)<br>    <br>    # Store the scores<br>    accuracy_scores.append(test_accuracy)<br>    precision_scores.append(test_precision)<br>    recall_scores.append(test_recall)<br>    f1_scores.append(test_f1)<br>    <br>    print(f&quot;Test Scores - Accuracy: {test_accuracy}, Precision: {test_precision}, Recall: {test_recall}, F1 Score: {test_f1}&quot;)<br><br># Calculate and print the average scores across all folds<br>print(f&quot;\nAverage Test Scores across all folds - Accuracy: {sum(accuracy_scores) / len(accuracy_scores)}, Precision: {sum(precision_scores) / len(precision_scores)}, Recall: {sum(recall_scores) / len(recall_scores)}, F1 Score: {sum(f1_scores) / len(f1_scores)}&quot;)</pre><p>Now, you can use these methods to split your dataset but they have the following <strong>limitations</strong>:</p><ul><li><strong><em>Random Train-Test-Val Split</em></strong><em>:</em> This method can’t guarantee <strong>similar</strong> <strong>distributions</strong> among the splits, especially if the dataset is not large enough or if there is an imbalance in the target variable.</li><li><strong><em>Stratified Split</em></strong><em>:</em> This method is useful only when you have a <strong>non-continuous</strong> target variable (y). Although there are workarounds for continuous target variables (such as converting the continuous variable into categorical through some conditions, e.g., if y ≥ quartile1 → 1, else 0), these approaches may still not always ensure similar distributions among the splits.</li></ul><p>Now, suppose you have a <strong>small</strong> total number of observations in your dataset and it’s difficult to ensure similar distributions amongst your splits. In that case, you can combine <strong>clustering</strong> and <strong>random sampling (or stratified sampling)</strong>.</p><p>Below is how I did it for <strong>my problem</strong> at hand:</p><h3>5. Clustering-based Train-Test-Validation split</h3><p>In this method, first, we cluster our dataset and then use sampling methods on each cluster to obtain our data splits.</p><p>For example, using <strong><em>HDBSCAN:</em></strong></p><pre>import hdbscan<br>from sklearn.metrics import silhouette_score<br>from sklearn.model_selection import ParameterGrid<br>import random<br>random.seed(48) #for regeneration of same results<br><br>def get_clusters(df):<br>  to_drop =[&quot;cluster_&quot;, &quot;ID&quot;]<br>  req_cols = sorted(set(df.columns) - set(to_drop))<br>  X = df[req_cols] #keep only required columns in X<br>  X_std = X.values #no need of scaling the training set for HDBSCAN<br><br>  # Define parameter grid for HDBSCAN, you can play with this grid accordingly<br>  param_grid = {<br>      &#39;min_cluster_size&#39;: list(range(2,20))<br>      #&#39;min_samples&#39;: [1, 2, 3]<br>  }<br><br>  best_score = -1<br>  best_params = None<br><br>  # Iterate over parameter grid<br>  for params in ParameterGrid(param_grid):<br>    model = hdbscan.HDBSCAN(**params, gen_min_span_tree=True)<br>    cluster_labels = model.fit_predict(X_std)<br>    unique_labels = np.unique(cluster_labels)<br>    if len(unique_labels) &gt; 1:  # Check if more than one cluster is formed<br>      silhouette_avg = silhouette_score(X_std, cluster_labels) if len(unique_labels) &gt; 1 else -1<br>      if silhouette_avg &gt; best_score:<br>        best_score = silhouette_avg<br>        best_params = params<br><br>  if best_params is not None:<br>    print(best_params)<br>    best_model = hdbscan.HDBSCAN(**best_params, gen_min_span_tree=True)<br>    cluster_labels = best_model.fit_predict(X_std) #get cluster labels from best model<br>    df[&quot;cluster_&quot;] = [str(i) for i in cluster_labels]<br>  else:<br>    print(&quot;HDBSCAN produced only one cluster label. Unable to split the data.&quot;)<br>    df[&quot;cluster_&quot;] = &quot;0&quot; #when no clusters are found<br><br>  return df</pre><p>You can also use other clustering methods according to your problem for eg. <strong><em>K-Means clustering</em></strong>:</p><pre>import matplotlib.pyplot as plt<br>from sklearn.cluster import KMeans<br>from sklearn.metrics import silhouette_score<br>from sklearn.preprocessing import StandardScaler<br>from yellowbrick.cluster import KElbowVisualizer<br><br>def get_clusters(df):<br><br>  to_drop =[&quot;cluster_&quot;, &quot;ID&quot;]<br>  req_cols = sorted(set(df.columns) - set(to_drop))<br>  X = df[req_cols].values #keep only required columns in X<br><br>  scaler = StandardScaler()<br>  X_std = scaler.fit_transform(X) #scaling is needed in case of K-Means<br><br>  model = KMeans()<br>  visualizer = KElbowVisualizer(model, k=(2, 50)) #you can play with the range accordingly<br>  visualizer.fit(X_std)<br>  #visualizer.show()<br><br><br>  optimal_n_clusters = visualizer.elbow_value_  #using elbow method to get optimal no. of clusters<br>  kmeans = KMeans(n_clusters=optimal_n_clusters, random_state=42)<br>  kmeans.fit(X_std)<br><br>  clust_labels = [str(i) for i in kmeans.labels_]<br><br>  # Evaluate the clustering using silhouette score<br>  silhouette_avg = silhouette_score(X_std, clust_labels)<br><br>  df[&quot;cluster_&quot;] = clust_labels<br><br>return df</pre><p>Now you can also add <strong>levels of granularities</strong> (any categorical variable) to your dataset to get more refined clusters as follows:</p><pre>import matplotlib.pyplot as plt<br>from sklearn.cluster import KMeans<br>from sklearn.metrics import silhouette_score<br>from sklearn.preprocessing import StandardScaler<br>from yellowbrick.cluster import KElbowVisualizer<br><br>def get_clusters(df):<br>  # taking animal categorical variable as a level of granularity to split on<br>  grp1 = df.loc[(df[&#39;animal&#39;]==&#39;cat&#39;)]<br>  grp2 = df.loc[(df[&#39;animal&#39;]==&#39;dog&#39;)]<br><br>  temps = []<br>  for num, temp in enumerate([grp1, grp2]):<br>    to_drop =[&quot;cluster_&quot;, &quot;ID&quot;]<br>    final_cols = sorted(set(temp.columns) - set(to_drop))<br>    X = temp[final_cols]<br><br>    X = X.values<br>    scaler = StandardScaler()<br>    X_std = scaler.fit_transform(X) #scaling of variables is needed for K-Means clustering<br><br>    model = KMeans()<br>    visualizer = KElbowVisualizer(model, k=(2, 50))<br>    visualizer.fit(X_std)<br>    # visualizer.show()<br>    <br>    #get optimal no. of clusters, K using elbow method<br>    optimal_n_clusters = visualizer.elbow_value_  <br>    kmeans = KMeans(n_clusters=optimal_n_clusters, random_state=42) <br>    kmeans.fit(X_std)<br><br>    clust_labels = [str(num) + &quot;_&quot; + str(i) for i in kmeans.labels_]<br><br>    # Evaluate the clustering using silhouette score<br>    silhouette_avg = silhouette_score(X_std, clust_labels)<br><br>    temp[&quot;cluster_&quot;] = clust_labels<br>    temps.append(temp)<br>  <br>  df = pd.concat(temps, axis=0)<br><br>  return df</pre><p>Once you have obtained <strong>cluster labels</strong> from any clustering method, you can use <strong>random sampling or stratified sampling</strong> to select samples from each cluster.</p><p>We will select indices randomly and then use these indices to select our train-test-val sets as follows:</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br><br># Assuming df is your DataFrame, &quot;cluster_&quot; is the column with cluster labels,<br>unique_clusters = df[&quot;cluster_&quot;].unique()<br><br>train_indices = []<br>val_indices = []<br>test_indices = []<br><br>for cluster in unique_clusters:<br>    cluster_data = df[df[&quot;cluster_&quot;] == cluster]<br>    cluster_indices = cluster_data.index.values<br>    cluster_y = cluster_data[&#39;y&#39;].values<br><br>    if stratify_ == True: #if you have categorical target variable<br>      train_idx, temp_idx, _, temp_y = train_test_split(cluster_indices, cluster_y, test_size=0.4, stratify=cluster_y, random_state=42)<br>      val_idx, test_idx = train_test_split(temp_idx, test_size=0.5, stratify=temp_y, random_state=42)<br>    else:<br>      # Split indices of the current cluster into train and temp (which will be further split into val and test)<br>      train_idx, temp_idx = train_test_split(cluster_indices, test_size=0.4, random_state=42)<br>      val_idx, test_idx = train_test_split(temp_idx, test_size=0.5, random_state=42)<br>    <br>    <br>    train_indices.extend(train_idx)<br>    val_indices.extend(val_idx)<br>    test_indices.extend(test_idx)<br><br># Convert the indices lists to numpy arrays<br>train_indices = np.array(train_indices)<br>val_indices = np.array(val_indices)<br>test_indices = np.array(test_indices)<br><br># Assuming &#39;X&#39; are the features and &#39;y&#39; is the target column<br>X = df.drop(columns=[&#39;y&#39;, &#39;cluster_&#39;]).values<br>y = df[&#39;y&#39;].values<br><br># Select the corresponding data for train, validation, and test sets<br>X_train, y_train = X[train_indices], y[train_indices]<br>X_val, y_val = X[val_indices], y[val_indices]<br>X_test, y_test = X[test_indices], y[test_indices]</pre><p>As per <strong>my use-case</strong>, it was useful to sort my target variable y and then select every <strong>1st, 2nd, and 3rd</strong> indices for train, test, and validation set respectively (all mutually exclusive), a.k.a <strong>systematic random sampling </strong>as below:</p><pre>def get_indices(df):<br>  np.random.seed(seed=48)<br><br>  total_length = len(df)<br>  sample1_length = int(0.60 * total_length) #you can choose proportion accordingly<br>  remaining_length = total_length - sample1_length<br><br>  sample2_length = int(remaining_length / 2)<br>  sample3_length = total_length - (sample1_length + sample2_length)<br>  <br>  #create an array with range 0 - length of the df<br>  all_indxs = np.array(range(total_length))<br><br>  # Create arrays of indices divisible by 2 and 3 exclusively<br>  indices_divisible_by_2 = np.array(list(set(np.where(all_indxs % 2 == 0)[0]) - set(np.where(all_indxs % 6 == 0)[0])))<br>  indices_divisible_by_3 = np.array(list(set(np.where(all_indxs % 3 == 0)[0]) - set([0])))<br>  <br>  #randomly choose indices divisibly by 2 with sample2_length<br>  sample2_indices = sorted(indices_divisible_by_2[np.random.choice(len(indices_divisible_by_2), size=sample2_length, replace=False)])<br>  try:<br>    sample3_indices = sorted(indices_divisible_by_3[np.random.choice(len(indices_divisible_by_3), size=sample3_length, replace=False)])<br>  except:<br>    sample3_indices = []<br>  <br>  sample1_indices = sorted(set(all_indxs) - set(sample2_indices) - set(sample3_indices))<br><br>  return sample1_indices, sample2_indices, sample3_indices</pre><pre>indices_train = []<br>indices_test = []<br>indices_val = []<br><br>for num, cluster in enumerate(df[&#39;cluster_&#39;].unique()):<br>  temp_df = df[df[&#39;cluster_&#39;] == cluster]<br>  sample1_indices, sample2_indices, sample3_indices = get_indices(temp_df)<br>  indices_train.append(list(temp_df.iloc[sample1_indices].index))<br>  indices_test.append(list(temp_df.iloc[sample2_indices].index))<br>  indices_val.append(list(temp_df.iloc[sample3_indices].index))<br><br># to flatten the list of lists containing indices for train,test,val set<br>indices_train = [x for xs in indices_train for x in xs]<br>indices_test = [x for xs in indices_test for x in xs]<br>indices_val = [x for xs in indices_val for x in xs]</pre><pre>def traintestvalsplit(df, id_col, cols_to_drop, cont_var, train_indices, test_indices, val_indices):<br><br>  train, test, val = df.loc[train_indices], df.loc[test_indices], df.loc[val_indices]<br><br>  # Split the data into train, validation, and test sets based on indices<br>  X_train = train.drop(cols_to_drop + [cont_var] ,axis=1) #add which columns to drop<br>  X_test = test.drop(cols_to_drop + [cont_var] ,axis=1)<br>  X_val = val.drop(cols_to_drop + [cont_var] ,axis=1)<br><br>  y_train = train[[cont_var]] #target variable<br>  y_test = test[[cont_var]]<br>  y_val = val[[cont_var]]<br><br>  train_ids = train[[id_col]] #to preserve the IDs<br>  test_ids = test[[id_col]]<br>  val_ids = val[[id_col]]<br><br>  print(&quot;Train set size:&quot;, X_train.shape, len(train_ids))<br>  print(&quot;Test set size:&quot;, X_test.shape, len(test_ids))<br>  print(&quot;Validation set size:&quot;, X_val.shape, len(val_ids))<br><br>  return X_train, X_val, X_test, y_train, y_val, y_test, train_ids, val_ids, test_ids<br><br>X_train, X_val, X_test, y_train, y_val, y_test, train_ids, val_ids, test_ids = traintestvalsplit(df, id_col, cols_to_drop, cont_var, train_indices, test_indices, val_indices)</pre><p>The above-discussed approaches of combining clustering with different sampling methods are very useful when you have a small number of observations in your dataset as they ensure to maintain similar distributions amongst the Train, Test and Validation sets.</p><p>Thanks for reading, and I hope you find this article helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650492b735fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-off-beat-approach-to-train-test-validation-split-your-dataset-esp-small-ones-650492b735fb">An Off-Beat Approach to Train-Test-Validation Split Your Dataset</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Pickletools : Handling large model pickle files]]></title>
            <link>https://medium.com/data-science/the-power-of-pickletools-handling-large-model-pickle-files-7f9037b9086b?source=rss-3d9d93721587------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f9037b9086b</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pickles]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Amarpreet Singh]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 06:15:15 GMT</pubDate>
            <atom:updated>2024-07-10T07:27:33.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Power of Pickletools</h3><h4>Handling large ML model pickle files</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57k7qpo9hNAvRgmg4IqPCg.jpeg" /><figcaption>Generated with Microsoft Designer</figcaption></figure><p>The volume of data is increasing. The more the data, the more we can use it for solving different problems. Suppose you train a machine learning model for some solution and want to save it for later predictions. Here come some serialization-deserialization methods: <strong>Pickling</strong> (Pickle, cPickle, Joblib, JsonPickle, Dill, Mlflow), saving to <strong>PMML</strong> format as pipeline (sklearn2pmml), saving as <strong>JSON</strong> format (sklearn_json, sklearn_export, msgpack, JsonPickle).</p><p>You may also use <strong>m2cgen </strong>library<strong> </strong>to export your model to python/java/c++ code or write your own code to serialize and de-serialize your model.</p><p>When you build a machine learning model to solve some problem by using huge data, the model is gonna be huge too! So the problem arises when you try to save this ginormous encoding to your system (I am going to talk here about the large RandomForestClassifier model/pickle file I tried to take care of).</p><h3>Solution #1:</h3><p>More data implies a large-sized model. Try to reduce your data as much as possible without losing your valuable information in the data. Removing <strong>duplicates or near-duplicates</strong>,<strong> Stratified Under-Sampling</strong> can save you here.</p><h3>Solution #2:</h3><p>Try to bring down your model size by tweaking the model parameters without compromising much accuracy. <strong>Hyper-parameter tuning</strong> will help you in this case. My base <em>RandomForestClassifier</em> model was of whooping 60 GB but hyper-parameter tuning managed to get it lower to 8 GB. Still large? Let’s check out the next cure.</p><h3>Solution #3:</h3><p>You’ve now done everything to make your model lighter without trading off much of its predictive power and still getting 8 GB of pickle file. Oh, Dear, Life is so unfair.</p><p>Hold on, still, some hope is left. <strong>Pickletools</strong> comes to the rescue!</p><p>The library helps you to reduce the size of the pickle file as well as makes loading the pickle file back as an RF object easy and faster.</p><p>Although Joblib and using compression methods such as <strong>zlib, gzip</strong> made my pickle file to shrink down to 1 GB, but loading back that file as a random forest classifier object was a headache. It would take more than 16 GB RAM to load my pickle (1 GB in size) and de-serialize the RF object which would result in <em>MemoryError.</em></p><p>Using Pickletools solves both problems of shrinking the size and faster loading of pickle file back without shooting the RAM more than your system can handle as follows.</p><p>To serialize:</p><pre>clf.fit(X_train, y_train) #your classifier/regressor model</pre><pre>import gzip, pickle, pickletools</pre><pre>filepath = &quot;random_forest.pkl&quot;<br>with gzip.open(filepath, &quot;wb&quot;) as f:<br>    pickled = pickle.dumps(clf)<br>    optimized_pickle = pickletools.optimize(pickled)<br>    f.write(optimized_pickle)</pre><p>To deserialize/loading back:</p><pre>with gzip.open(filepath, &#39;rb&#39;) as f:<br>    p = pickle.Unpickler(f)<br>    clf = p.load()</pre><p>Woohoo!! While gzip helps to reduce the pickle size (to 1 GB), pickletools helps the pickle file to load faster without consuming much memory (took 7 GB RAM this time)</p><p>You may also set pickle attribute fast = True for this purpose but it may be deprecated in future as the documentation says so:</p><pre>import pickle</pre><pre>filepath = &quot;random_forest.pkl&quot;</pre><pre>with open(filepath, &#39;wb&#39;) as f:<br>    p = pickle.Pickler(f)<br>    p.fast = True<br>    p.dump(clf)</pre><pre>with open(filepath, &#39;rb&#39;) as f:<br>    p = pickle.Unpickler(f)<br>    clf = p.load()</pre><h3>Bonus Solution:</h3><p>If you can in any way parallelize the whole process by making each core of your CPU work at the same time, it may rescue you too up-to some extent!</p><p>Okay, your turn to try it yourself. May the force be with ya!</p><p><strong><em>Further reading and References:</em></strong></p><ol><li><a href="https://docs.python.org/3/library/pickle.html#pickle.Pickler.fast">https://docs.python.org/3/library/pickle.html#pickle.Pickler.fast</a></li><li><a href="https://docs.python.org/3/library/pickletools.html#pickletools.optimize">https://docs.python.org/3/library/pickletools.html#pickletools.optimize</a></li><li><a href="https://wiki.python.org/moin/ParallelProcessing">https://wiki.python.org/moin/ParallelProcessing</a></li><li><a href="https://stackoverflow.com/questions/23916413/celery-parallel-distributed-task-with-multiprocessing">https://stackoverflow.com/questions/23916413/celery-parallel-distributed-task-with-multiprocessing</a></li><li><a href="https://docs.python.org/3/library/multiprocessing.html">https://docs.python.org/3/library/multiprocessing.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9037b9086b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-power-of-pickletools-handling-large-model-pickle-files-7f9037b9086b">The Power of Pickletools : Handling large model pickle files</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>