<?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 Hamidreza on Medium]]></title>
        <description><![CDATA[Stories by Hamidreza on Medium]]></description>
        <link>https://medium.com/@hamidrezak324?source=rss-c47856c94f86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c8UbPCrdQBZWRN8L8TAadw.jpeg</url>
            <title>Stories by Hamidreza on Medium</title>
            <link>https://medium.com/@hamidrezak324?source=rss-c47856c94f86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:05:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamidrezak324/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[Comprehensive Review of Feature Selection + Bonus Feature Engineering Insights]]></title>
            <link>https://medium.com/@hamidrezak324/comprehensive-review-of-feature-selection-bonus-feature-engineering-insights-a307f093f599?source=rss-c47856c94f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/a307f093f599</guid>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[meta-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[Hamidreza]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 05:31:54 GMT</pubDate>
            <atom:updated>2025-06-27T20:14:10.174Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re trying to guess what someone’s favorite pizza is based on 5,000 facts about them — like their shoe size, favorite animal, birth time, favorite toothpaste brand, and so on.</p><p>Would you really need all 5,000 facts?<br> Probably not.<br> You’d just want the few that actually <strong>matter</strong> — like dietary preferences, past pizza orders, or toppings they hate.</p><p>That’s exactly what <strong>Feature Selection</strong> does in machine learning.</p><p>It’s the art (and science) of <strong>picking the most relevant signals</strong> from a sea of information.</p><p>In an age where we can collect thousands of features per user, product, or patient — selecting the right ones isn’t just convenient, it’s <em>critical</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhhYnlkvNgxBrfYkVWTENQ.png" /><figcaption>Become a Master of Feature Selection Road Map</figcaption></figure><h3>Section 1: What is Feature Selection?</h3><p>At its core, <strong>Feature Selection (FS)</strong> is a process where we choose a subset of relevant features from our dataset, before feeding it into a machine learning model.</p><p>Let’s break this down further.</p><h4>The Goal:</h4><ul><li>Improve model accuracy</li><li>Reduce overfitting</li><li>Speed up training</li><li>Increase interpretability</li><li>Lower computational cost</li></ul><p>Think of it like trying to solve a puzzle — you don’t want too many pieces that don’t fit. FS helps you keep only the pieces that matter.</p><h4>Where does FS fit in the ML pipeline?</h4><pre>Raw data → Preprocessing → Feature Selection → Modeling → Evaluation</pre><p>FS comes <strong>before</strong> training your model, which makes it different from techniques that try to explain a model after the fact (like SHAP).</p><p>note: we will explain the SHAP….</p><h4>FS vs Feature Extraction</h4><p>Let’s clear up one common confusion:</p><p><em>I should mention that feature extraction is a mapping of feature selection.</em></p><figure><img alt="Feature Selection vs Feature Extraction Table" src="https://cdn-images-1.medium.com/max/858/1*ihS7acSznb5CP6kHIN0EwA.png" /><figcaption>fig1: Feature Selection vs Feature Extraction</figcaption></figure><p><strong>Analogy</strong>: Feature Selection is like cleaning your wardrobe by removing clothes you don’t wear. Feature Extraction is like cutting up those clothes to make new outfits.</p><h3>Why FS Matters More Today Than Ever?</h3><p>In modern machine learning:</p><ul><li>We have <strong>hundreds or thousands</strong> of features</li><li>Some features are noisy, redundant, or irrelevant</li><li>Many algorithms suffer when input space is huge (especially on tabular or bioinformatics data)</li></ul><figure><img alt="Feature Selection pros &amp; cons" src="https://cdn-images-1.medium.com/max/1024/1*ZNJrRBRp3eZC9nbgt2zeEg.png" /><figcaption>fig2: Feature Selection pros &amp; cons</figcaption></figure><p>This is especially true in <strong>healthcare</strong>, <strong>finance</strong>, <strong>recommendation systems</strong>, and <strong>natural language processing</strong>, where irrelevant features can mislead the model or inflate computation costs.</p><h3>Section 2: Types of Feature Selection Methods</h3><p>There are three main families of feature selection methods — each with its own philosophy, strengths, and use cases. Think of them like three different strategies for choosing the best team members for a mission:</p><h4>2.1 Filter Methods</h4><p><em>“Judge before the model is even built.”</em></p><p>These methods evaluate features <strong>independently</strong> of the learning algorithm. They rely on <strong>statistical properties</strong> (like correlation, variance, mutual information) to rank and filter features.</p><figure><img alt="Filter methods approach pros &amp; cons" src="https://cdn-images-1.medium.com/max/1024/1*U3slyEgWXnA2NXrbBXVYfw.png" /><figcaption>fig3: Filter methods approach pros &amp; cons</figcaption></figure><p>🔧 <strong>Examples</strong>:</p><ul><li>Pearson Correlation Coefficient</li><li>Chi-Square Test</li><li>Mutual Information</li><li>Variance Threshold</li></ul><p><strong>Analogy</strong>: Like choosing soccer players just based on their sprint speed — without seeing how well they play as a team.</p><h4>2.2 Wrapper Methods</h4><p><em>“Try different feature combinations and pick what works best for the model.”</em></p><p>These methods <strong>use the model’s performance</strong> (e.g., accuracy, F1 score) as feedback to guide feature selection. They search through subsets of features and evaluate each set by training a model on it.</p><figure><img alt="Wrapper methods approach pros &amp; cons" src="https://cdn-images-1.medium.com/max/1024/1*bz9f468STDH5fee8j7RjcA.png" /><figcaption>fig4: Wrapper methods approach pros &amp; cons</figcaption></figure><p><strong>Examples</strong>:</p><ul><li>Forward Selection</li><li>Backward Elimination</li><li>Recursive Feature Elimination (RFE)</li></ul><p><strong>Analogy</strong>: Like testing different soccer teams in real matches to find the best lineup.</p><h4>2.3 Embedded Methods</h4><p><em>“Let the model do the selection during training.”</em></p><p>These methods integrate feature selection <strong>into the model training process itself</strong>. The model identifies important features as it learns — often through regularization or internal scoring.</p><figure><img alt="Embedded Methods approach pros &amp; cons" src="https://cdn-images-1.medium.com/max/1024/1*AvGCVKu0XMUtcma_2FzYWQ.png" /><figcaption>fig5: Embedded Methods approach pros &amp; cons</figcaption></figure><p><strong>Examples</strong>:</p><ul><li>Lasso (L1 Regularization)</li><li>Decision Tree Feature Importance</li><li>Random Forest / Gradient Boosting Feature Importance</li></ul><p><strong>Analogy</strong>: Like a coach who continuously adjusts the lineup during training sessions, cutting players who underperform.</p><h3>Section 3: How Feature Selection Improves Models — Speed, Simplicity &amp; Accuracy</h3><p>Feature Selection (FS) isn’t just a fancy preprocessing step — it can <em>transform</em> how your model learns, generalizes, and even trains. In this section, we’ll show why FS matters so much in practice, and how it works through real algorithms like <strong>Forward Selection</strong>.</p><h4>3.1 Why FS Makes a Difference</h4><p>Here’s what happens when you cut irrelevant or redundant features:</p><ul><li><strong>Reduced overfitting</strong><br> Less noise = better generalization on unseen data</li><li><strong>Faster training</strong><br> Fewer features = smaller search space and fewer computations</li><li><strong>More interpretable models</strong><br> With fewer inputs, you can actually understand what the model is learning</li><li><strong>Better performance</strong><br> Yes, fewer features can <em>improve</em> accuracy by removing confusion</li></ul><h4>3.2 Forward Selection: A Step-by-Step Build-Up</h4><p><strong>Forward Selection</strong> is a classic <strong>greedy wrapper algorithm</strong>. It starts with <strong><em>zero features</em> </strong>and adds one feature at a time — always picking the one that most improves model performance.</p><h4>How it works:</h4><ol><li>Start with an empty feature set</li></ol><p>2. For each remaining feature:</p><ul><li>Add it temporarily</li><li>Train the model</li><li>Measure performance (e.g., accuracy, RMSE)</li></ul><p>3. Keep the feature that gives the best improvement</p><p>4. Repeat until no significant improvement is observed or max features reached</p><p>Analogy: It’s like forming a band one musician at a time — keep adding the person who improves the sound most, and stop when adding more just creates noise.</p><h4>3.3 When Does Forward Selection Shine?</h4><ul><li>Best for <strong>small-to-medium datasets</strong></li><li>Especially helpful when features are <strong>expensive to compute</strong> or noisy</li><li>Works great with interpretable models like <strong>Linear Regression</strong></li></ul><h4>Limitations:</h4><ul><li><strong>Computationally expensive</strong> for large feature sets</li><li>Can get stuck in <strong>local optima</strong> (it’s greedy — not global search)</li></ul><h4>3.4 Quick Example (Pseudocode-style|Using a library)</h4><pre>selected_features = []<br>remaining_features = all_features<br><br>for step in range(max_steps):<br>    best_score = -inf<br>    best_feature = None<br>    <br>    for feature in remaining_features:<br>        trial_set = selected_features + [feature]<br>        score = cross_val_score(model, X[trial_set], y)<br>        <br>        if score &gt; best_score:<br>            best_score = score<br>            best_feature = feature<br><br>    if improvement is significant:<br>        selected_features.append(best_feature)<br>        remaining_features.remove(best_feature)<br>    else:<br>        break</pre><pre>from mlxtend.feature_selection import SequentialFeatureSelector as SFS<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br><br>X, y = load_iris(return_X_y=True)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)<br><br>model = LogisticRegression(max_iter=1000)<br><br>sfs = SFS(model,<br>          k_features=3,<br>          forward=True,<br>          floating=False,<br>          scoring=&#39;accuracy&#39;,<br>          cv=5)<br><br>sfs.fit(X_train, y_train)<br>print(sfs.k_feature_names_)</pre><h4>3.5 Backward Elimination: Start Big, Trim Smart</h4><p>If <strong>Forward Selection</strong> builds up features one by one, <strong>Backward Elimination</strong> does the opposite:<br> It starts with <strong>all features</strong>, and gradually removes the <em>least useful</em> ones — those that contribute the least to model performance.</p><h4>How it works:</h4><ol><li>Start with <strong>all features</strong> in the model</li><li>Train the model and <strong>evaluate feature importance</strong> (e.g., p-values, weights, or importance scores)</li><li>Remove the <strong>least significant feature</strong></li><li>Repeat until removing more features hurts performance or drops below a threshold</li></ol><p>Analogy: Like a sculptor starting with a big stone and chiseling away everything that doesn’t look like the final statue.</p><h4>When to Use Backward Elimination:</h4><ul><li>When you have <strong>lots of features</strong>, but can afford to train a few models</li><li>When features may be <strong>correlated</strong>, and you want to eliminate redundancy</li><li>When your model gives interpretable coefficients (like linear models)</li></ul><h4>Limitations:</h4><ul><li>Still <strong>computationally expensive</strong> (must retrain after each removal)</li><li>Can remove a useful feature if its effect is only visible when combined with others</li></ul><h4>3.6 Generalized Sequential Forward/Backward Selection (GSFS &amp; GSBS)</h4><p>While classic forward and backward selection are intuitive and useful, they follow a <strong>greedy, one-step-at-a-time</strong> approach that can miss global interactions. To improve this, researchers proposed more flexible variations:</p><p>Generalized Sequential Forward Selection (GSFS)</p><p>GSFS improves upon Forward Selection by allowing <strong>more than one feature to be added at each step</strong>, or even allowing <strong>temporary feature removals</strong> after adding.</p><ul><li>✅ Allows more flexible exploration of the feature space</li><li>✅ Can uncover interactions between features earlier</li><li>✅ Reduces the chance of local optima caused by early bad choices</li></ul><p><strong>Analogy</strong>: Like building a soccer team where you can add two players at once, and if one doesn’t perform well after a few matches, you’re free to swap them out — mid-process.</p><p>Generalized Sequential Backward Selection (GSBS)</p><p>GSBS is the counterpart to GSFS. It starts with all features but removes <strong>multiple features per step</strong>, or even <strong>reintroduces a removed feature</strong> if performance improves.</p><ul><li>✅ More robust than strict backward elimination</li><li>✅ Helps recover from overly aggressive feature removal</li><li>✅ Useful when features are highly interdependent</li></ul><p><strong>Analogy</strong>: Like trimming a tree carefully — removing multiple branches, but also having the option to graft one back if you realize it was essential.</p><p>These generalized approaches offer a <strong>balance between exhaustive search</strong> and greedy methods, making them suitable when:</p><ul><li>You have <strong>moderate-sized</strong> feature sets (not thousands)</li><li>You suspect <strong>interactions between features</strong></li><li>You want a <strong>higher-performing FS</strong> without fully brute-forcing the space</li></ul><figure><img alt="Comparison of Feature Selection Methods" src="https://cdn-images-1.medium.com/max/923/1*GC5dNjhdn6nlfi55puQwcw.png" /><figcaption>fig6: Comparison of Feature Selection Methods</figcaption></figure><h4>3.7 Plus-l Take-away-r: Balancing Exploration and Correction</h4><p>Classic greedy methods like forward or backward selection often make <strong>irreversible decisions</strong> — once a feature is added or removed, it’s final.<br> But what if we could revisit our decisions?</p><p>That’s the idea behind <strong>Plus-l Take-away-r (ℓ, r)</strong> strategy:</p><p>In each iteration:</p><ul><li>Add <strong>ℓ features</strong> (based on performance gain)</li><li>Remove <strong>r features</strong> (that reduce performance or are redundant)</li></ul><p>This dynamic makes it possible to <strong>correct earlier mistakes</strong>, and escape local optima.</p><blockquote><em>ℓ and r are hyperparameters. For example, ℓ=3 and r=2 means we try 3 additions, then remove the worst 2 from the set.</em></blockquote><p>Analogy: Imagine a chef who tries 3 new ingredients in a recipe, then tastes it — and throws out the 2 that ruin the flavor. It’s trial-and-error with a feedback loop.</p><h3>When to Use:</h3><ul><li>In high-dimensional problems where <strong>pure forward selection is too rigid</strong></li><li>When you want a <strong>balance between exploration and correction</strong></li><li>Common in hybrid FS algorithms and feature ranking refinements</li></ul><blockquote><em>🔍 </em><strong><em>Note:</em></strong><em><br> In the early stages of Plus-l Take-away-r selection, it’s common to choose </em><strong><em>larger values for ℓ and r</em></strong><em>. This encourages </em><strong><em>more aggressive exploration</em></strong><em> of the feature space. As the process continues, ℓ and r can be reduced to fine-tune the feature set more cautiously.</em></blockquote><h4>3.8 Floating Search Methods: Adaptive and Flexible Subset Search</h4><p>Floating search methods were designed to address a major limitation of greedy selection: <strong>getting stuck with bad early decisions</strong>.</p><p>Unlike basic forward or backward selection — which only move in one direction — <strong>floating methods allow backtracking</strong> dynamically. This means the algorithm can <strong>add a feature and later remove it</strong>, or <strong>remove a feature and later add it back</strong> if the overall performance improves.</p><p>Types:</p><ul><li><strong>Sequential Forward Floating Selection (SFFS)</strong><br> Forward search + occasional conditional backward steps</li><li><strong>Sequential Backward Floating Selection (SBFS)</strong><br> Backward elimination + occasional conditional forward steps</li></ul><p>Why it’s “Floating”:</p><p>Because there’s <strong>no fixed number</strong> of features added or removed per iteration.<br> The process “floats” based on current evaluation — making it <strong>adaptive</strong>.</p><p>Pros:</p><ul><li>More flexible than strict forward/backward</li><li>Can recover from suboptimal early choices</li><li>Often performs comparably to exhaustive search — but much faster</li></ul><p>When to Use:</p><ul><li>When you suspect feature interactions are important</li><li>When basic greedy methods give inconsistent results</li><li>When you want <strong>near-optimal performance</strong> with lower computational cost</li></ul><p><strong>Analogy</strong>: Think of a hiring process where you can re-interview previously rejected candidates — or let go of someone you hired too quickly — if team performance isn’t working.</p><h3>Example: Why Floating Selection Can Be Smarter</h3><p>Let’s say we’re trying to predict student performance based on 5 features:</p><p>F1: Hours of study</p><p>F2: Attendance rate</p><p>F3: Breakfast eaten</p><p>F4: Favorite color</p><p>F5: Number of pens used</p><p>We want to select the best subset of features to predict final grades.</p><h4>Forward Selection (Greedy)</h4><ol><li>It tries all features individually — finds F2 (Attendance) has the best individual score → adds it.</li><li>Then tries pairs like F2+F1, F2+F3, ... — picks F2+F5.</li><li>Then F2+F5+F1 slightly improves accuracy → done.<br> ✅ Final selected: F2, F5, F1</li></ol><p>But F5 (pens used) is a noisy feature that only looked useful in step 2.<br> It should’ve been removed!</p><h3>Floating Selection (SFFS)</h3><ol><li>Like Forward, it starts with F2, then F2+F5</li><li>But then it checks: does removing F5 help? It does!</li><li>So F5 is dropped, and F1 is added instead</li><li>Now subset is: F2, F1 → better result</li></ol><p>✅ Final selected: F2, F1 — a cleaner, more meaningful set</p><blockquote><em>🧠 </em><strong><em>Key Insight:</em></strong><em><br> Greedy methods commit early and don’t look back.<br> Floating methods allow “regret” — they backtrack when better paths appear.</em></blockquote><h3>Section 4: The Hidden Cost of Selection — Estimation Error, Bias, and the Curse of Dimensionality</h3><p>Feature selection isn’t just about picking the “best” features — it’s about making <strong>good decisions under uncertainty</strong>. That’s where <strong>error estimation</strong> plays a key role.</p><h4>4.1 Why Estimation Error Matters in FS</h4><p>Every time we evaluate a set of features — whether through cross-validation or hold-out testing — we are <strong>estimating</strong> its performance. And just like any estimation, it comes with <strong>error</strong>.</p><p>So what happens when we search over <strong>thousands of feature subsets</strong>?<br>We’re likely to overestimate the performance of some subsets just by chance.</p><p>This leads to what’s known as:</p><p><strong>Selection Bias</strong> — the more we search, the more likely we are to pick a feature set that looks good by accident.</p><h4>4.2 Bias-Variance Trade-off and the Role of Estimators</h4><p>There’s a direct connection between feature selection and the <strong>bias-variance tradeoff</strong>:</p><ul><li>If your estimator has high variance, feature selection might overfit to noise</li><li>If your estimator is biased, it may underrepresent complex relationships</li></ul><p>That’s why in wrapper methods, <strong>the quality of your estimator (learner) is as critical as the search strategy</strong>.</p><p>Sometimes, changing your model (e.g., from decision trees to regularized logistic regression) may have more impact than changing the feature scoring method.</p><h4>4.3 Multi-objective Optimization: Beyond Single Accuracy</h4><p>Instead of optimizing for accuracy alone, modern FS techniques aim to <strong>jointly optimize</strong> for:</p><ul><li>Accuracy or loss</li><li>Feature count (sparsity)</li><li>Redundancy (diversity of information)</li><li>Stability (consistency across samples)</li></ul><p>This leads to <strong>multi-objective optimization</strong> — where FS becomes a balancing act, not a race for one metric.</p><h4>4.4 Why We Sample Instead of Exhaust</h4><p>When you have 5,000 features, the number of possible subsets is ²⁵⁰⁰⁰ — astronomically large.</p><p><em>Even if you had a computer the size of the sun, you couldn’t try them all.</em></p><p>So we turn to <strong>heuristic search + sampling</strong> strategies:</p><ul><li>Greedy methods (like Forward Selection)</li><li>Randomized algorithms (like Genetic FS)</li><li>Model-based selectors (like embedded methods)</li></ul><h4>4.5 Feature Interactions and “Paradoxical Pairs”</h4><p>Sometimes two features are great individually, but terrible together — or vice versa.</p><blockquote><em>Think of Feature A and Feature B as two spices. Individually, they taste great. But mix them together? You ruin the dish.</em></blockquote><p>This is why <strong>evaluating features independently can be misleading</strong>, and methods that consider interactions (like wrappers or attention-based models) are often better.</p><blockquote><strong><em>From Here On: Modern &amp; Advanced Feature Selection Techniques</em></strong><em><br> So far, we’ve explored the classical categories of feature selection — filter and wrapper— each offering unique trade-offs between speed, interpretability, and predictive power.<br> Now, we’re entering the frontier of </em><strong><em>modern and research-driven approaches</em></strong><em>. These include techniques based on embedded methods, </em><strong><em>attention mechanisms</em></strong><em>, </em><strong><em>learnable selectors</em></strong><em>, </em><strong><em>explainability tools like SHAP</em></strong><em>, and even </em><strong><em>reinforcement learning</em></strong><em>.<br> If the previous sections were the foundation, what comes next is the </em><strong><em>cutting edge</em></strong><em> — where feature selection meets deep learning, causality, and model interpretability at scale.</em></blockquote><h3>Section 5: Embedded Methods — Learning and Selecting Simultaneously</h3><p>Embedded methods integrate feature selection <strong>directly into the training process</strong> of the learning algorithm.<br> Unlike filter (independent) or wrapper (external) methods, embedded approaches let the model <strong>decide which features matter most</strong> as it learns.</p><h4>5.1 Why Embedded Methods Are Powerful</h4><p><strong>Efficient</strong> — no need to search through many feature subsets</p><p><strong>Interaction-aware</strong> — considers joint effects of features during training</p><p><strong>Model-specific</strong> — works best with models that have built-in mechanisms for feature weighting or sparsity</p><h3>5.2 Regularization-Based Methods</h3><p>Some models apply <strong>penalties</strong> during training to force the model to keep only important features.<br> These penalties act like “feature bouncers” — they push unhelpful weights toward zero.</p><h4>L1 Regularization (Lasso)</h4><p>Lasso encourages <strong>sparsity</strong> by shrinking many weights to exactly zero.</p><p><strong>Loss function with L1:</strong></p><figure><img alt="L1 Regularization formula" src="https://cdn-images-1.medium.com/max/482/1*EPwShmamUaaooSWf7uN6ig.jpeg" /><figcaption>fig7: L1 formula</figcaption></figure><ul><li>w: model weights</li><li>λ: regularization strength</li><li>p: number of features</li></ul><p>⛔Features with zero weights are effectively removed from the model.</p><h4>L2 Regularization (Ridge)</h4><p>Ridge penalizes <strong>large weights</strong>, but doesn’t produce exact zeros — so it doesn’t fully perform feature selection.</p><p><strong>Loss function with L2:</strong></p><figure><img alt="L2 Regularization formula" src="https://cdn-images-1.medium.com/max/457/1*vehDTraG9EB3zb7WxL867A.png" /><figcaption>fig8: L2 formula</figcaption></figure><p>✅ Good for <strong>handling multicollinearity</strong></p><p>❌ Keeps all features in the model</p><h4>Elastic Net (L1 + L2)</h4><p>Elastic Net combines both L1 and L2 — giving a balance between <strong>sparsity</strong> and <strong>stability</strong>.</p><p><strong>Loss function:</strong></p><figure><img alt="Elastic Net formula" src="https://cdn-images-1.medium.com/max/845/1*eBrFRaLjzj9EXMxGTbRHuQ.png" /><figcaption>fig9: Elastic Net formula</figcaption></figure><p>When you want the <strong>selection power of Lasso</strong> and the <strong>robustness of Ridge</strong>, use Elastic Net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*cMuKspED6f2NDWypQ8qzbg.png" /><figcaption>fig10: L1,L2 &amp; Elastic net</figcaption></figure><h4>5.3 Tree-Based Models (Feature Importance)</h4><p>Tree-based models like Decision Trees, Random Forests, and Gradient Boosting <strong>naturally select features</strong> by splitting on the most informative ones.</p><ul><li>They provide <strong>feature importance scores</strong></li><li>They are <strong>nonlinear</strong>, so they can handle complex relationships</li><li>They work well out-of-the-box for FS, but can be biased toward high-cardinality features</li></ul><p>Embedded methods are the <strong>default choice</strong> in many pipelines — especially when using linear models, decision trees, or any algorithm with built-in sparsity.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.datasets import load_iris<br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Load dataset<br>data = load_iris()<br>X = pd.DataFrame(data.data, columns=data.feature_names)<br>y = data.target<br><br># Train model<br>model = RandomForestClassifier(n_estimators=100, random_state=42)<br>model.fit(X, y)<br><br># Get feature importances<br>importances = model.feature_importances_<br>feat_importance = pd.Series(importances, index=X.columns).sort_values(ascending=False)<br><br># Plot<br>feat_importance.plot(kind=&#39;bar&#39;, title=&#39;Feature Importance (Random Forest)&#39;)<br>plt.ylabel(&#39;Importance Score&#39;)<br>plt.tight_layout()<br>plt.show()</pre><h3>Section 6: Stability of Feature Selection — Can We Trust the Chosen Features?</h3><p>Imagine running your feature selection pipeline today and getting a list of “top 10 features”. Then you rerun it tomorrow with slightly different data — and get a completely different set.</p><p>That’s a <strong>stability problem</strong>.</p><h4>6.1 What Is Stability?</h4><p><strong>Stability</strong> refers to how <strong>consistent</strong> the selected feature set is when:</p><ul><li>The dataset is slightly perturbed (e.g., bootstrapping, noise, subsampling)</li><li>The model is retrained multiple times</li><li>The data distribution shifts slightly</li></ul><p>A feature selector is <strong>stable</strong> if it repeatedly chooses the <em>same core features</em>, even under small changes.</p><p><strong>Why It Matters</strong>: Stability increases <strong>trust</strong> in selected features, especially in high-stakes fields like healthcare, finance, and scientific research.</p><h4>6.2 How to Measure Stability?</h4><p>There are several metrics to quantify feature selection stability:</p><p>✅ Jaccard Index</p><p>Measures <strong>overlap</strong> between two sets A and B:</p><figure><img alt="Jaccard Index formula" src="https://cdn-images-1.medium.com/max/639/1*j9o6pwEvh6gG8oKevKq1vA.png" /><figcaption>fig11: Jaccard Index</figcaption></figure><p>Ranges from 0 (no overlap) to 1 (perfect match).<br> Often used by computing the <strong>average Jaccard index</strong> across multiple runs.</p><p>✅ Kuncheva Index</p><p>A normalized index that adjusts for chance agreement between selected features:</p><figure><img alt="Kuncheva Index" src="https://cdn-images-1.medium.com/max/109/1*OL_Gneyb8N57eJJ-x0qXwQ.png" /><figcaption>fig12: Kuncheva Index</figcaption></figure><p><a href="https://lucykuncheva.co.uk/papers/lkAIA07.pdf"><em>click here to get the Kuncheva Index article!</em></a></p><p>Where:</p><ul><li>r: average number of overlapping features between pairs</li><li>k: number of selected features</li><li>n: total number of features</li></ul><p>Values close to 1 = stable; near 0 = unstable.</p><p>✅ Hamming Distance (Binary Encoding)</p><p>Represents each feature set as a binary vector and computes the average Hamming distance between runs.</p><p>Lower distance = higher stability.</p><p>✅ Spearman Rank Correlation</p><p>Instead of binary selection, we rank features by importance, then calculate correlation between rankings across runs.</p><p>Useful for <strong>soft feature selectors</strong> that return importance scores.</p><h4>6.3 How to Improve Stability?</h4><ul><li>Use <strong>ensemble feature selection</strong></li><li>Choose <strong>regularized models</strong> (e.g., Lasso)</li><li>Use <strong>filter methods</strong> that are less sensitive to sampling</li><li>Avoid overfitting in FS by reducing search depth</li></ul><h4>6.4 Example Insight</h4><blockquote><em>Two feature selection algorithms may have the same accuracy — but very different stabilities. Always choose the one that’s </em><strong><em>accurate </em>and<em> stable</em></strong><em> if your goal is trust and interpretability.</em></blockquote><h3>Section 7: Ensemble Feature Selection — Combining Multiple Views for Better Stability</h3><p>Feature selection methods often disagree. One method selects features based on correlation, another based on model performance, and yet another based on mutual information.<br> So, how do we <strong>combine their strengths</strong>?</p><p>That’s where <strong>Ensemble Feature Selection (EFS)</strong> comes in.</p><h3>7.1 The Idea Behind Ensemble Feature Selection</h3><p>Rather than relying on a single FS method, EFS runs <strong>multiple feature selectors</strong> (either different types or repeated versions of the same type) and combines their outputs.</p><p>This improves:</p><ul><li><strong>Stability</strong> (consistent results across data variations)</li><li><strong>Robustness</strong> (less sensitive to noise)</li><li><strong>Coverage</strong> (better at capturing complex, multi-view patterns)</li></ul><h3>7.2 Types of Ensembles in Feature Selection</h3><p>Let’s organize EFS into a table to clarify:</p><figure><img alt="Types of Ensembles in Feature Selection" src="https://cdn-images-1.medium.com/max/928/1*lXUNf4zw2xYde-foA3JerA.png" /><figcaption>fig13: Types of Ensembles in Feature Selection</figcaption></figure><h3>7.3 How to Combine Results?</h3><p>Three popular ways:</p><ol><li><strong>Hard Voting</strong>: Keep features selected by the majority (e.g., appears in ≥ 2 of 3 methods)</li><li><strong>Rank Aggregation</strong>: Assign ranks from each method, average them, and pick the top-k</li><li><strong>Score Averaging</strong>: Average importance scores across runs or methods</li></ol><blockquote><em>You can also use weighted versions of these if you trust one method more than others.</em></blockquote><h3>7.4 A Practical Use Case</h3><p>Imagine a high-dimensional text dataset with 10,000 features. One selector picks word frequency, another picks TF-IDF scores, and a third uses a tree-based model.</p><p>If we <strong>ensemble them</strong>, we’re not forced to trust any one viewpoint. Instead, we trust <strong>consensus</strong>.</p><p><strong>Bottom line</strong>: Ensemble FS is like assembling a committee of experts — they each see the data differently, but together, they help you choose the most meaningful features with higher confidence.</p><h3>Section 8: Explainable Feature Selection with SHAP — Opening the Black Box</h3><p>In modern machine learning, especially with complex models like XGBoost, deep neural networks, or ensembles, feature selection isn’t always about <strong>eliminating</strong> features beforehand — sometimes, it’s about <strong>understanding</strong> them afterward.</p><p>That’s where <strong>SHAP (SHapley Additive exPlanations)</strong> shines.</p><h3>8.1 What Is SHAP?</h3><p>SHAP is based on a concept from cooperative game theory called the <strong>Shapley value</strong>.<br> It measures how much each “player” (in our case, feature) <strong>contributes</strong> to the model’s prediction, fairly and mathematically.</p><blockquote><em>Each feature is treated like a player in a team game — and SHAP computes its average </em><strong><em>marginal contribution</em></strong><em> across all possible feature combinations.</em></blockquote><h3>8.2 Why Use SHAP for Feature Selection?</h3><ul><li>Provides <strong>local</strong> and <strong>global</strong> explanations</li><li>Works with <strong>any model</strong> (via KernelSHAP) or natively with tree models (TreeSHAP)</li><li>Helps identify <strong>most influential features</strong> per sample and overall</li><li>Model-agnostic, interpretable, and statistically grounded</li></ul><figure><img alt="Why SHAP?" src="https://cdn-images-1.medium.com/max/918/1*EXwrQKL0CBQhUzliB2nZTQ.png" /><figcaption>fig14: Why does SHAP work for us?</figcaption></figure><h3>8.3 How It Works (Simplified)?</h3><p>Imagine a model f(x) and a feature vector x=[x1,x2,…,xn]. SHAP assigns a score ϕi to each feature xi​ such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*5RjVx70m3KZjWXofir4pJg.png" /><figcaption>fig15: SHAP formula</figcaption></figure><p>Where:</p><ul><li><em>ϕ0</em>​ is the base value (average model output)</li><li><em>ϕi</em>​ is the contribution of feature i</li></ul><h3>8.4 Feature Selection via SHAP</h3><figure><img alt="How can we use SHAP?" src="https://cdn-images-1.medium.com/max/583/1*3t5GaSUTRjcS4m8Y_mbriw.png" /><figcaption>fig16: How can we use SHAP?</figcaption></figure><p>Unlike filters or wrappers, SHAP tells you <strong>how each feature affects predictions</strong>, not just how correlated it is with the label.</p><h3>8.5 Python Example (TreeSHAP)</h3><pre>import shap<br>import xgboost as xgb<br>from sklearn.datasets import load_breast_cancer<br><br># Load data<br>X, y = load_breast_cancer(return_X_y=True)<br>model = xgb.XGBClassifier().fit(X, y)<br><br># SHAP values<br>explainer = shap.Explainer(model)<br>shap_values = explainer(X)<br><br># Plot summary<br>shap.summary_plot(shap_values, X)</pre><p><em>SHAP turns the black box into a </em><strong><em>glass box</em></strong><em>, helping you select and trust features based on how much they really impact the model.</em></p><p><a href="https://www.sciencedirect.com/science/article/pii/S2405896322020742"><em>If you want to understand the power of SHAP, check out this article where the authors used this approach to develop the Kanoo model!</em></a></p><h3>Section 9: Differentiable Feature Selection with Concrete Autoencoders</h3><h4>9.1 What Is a Concrete Autoencoder?</h4><p>A <strong>Concrete Autoencoder (CAE)</strong> is a neural network–based approach for selecting a <strong>discrete subset of input features</strong> in a fully <strong>differentiable</strong> and <strong>unsupervised</strong> manner.</p><p>Unlike classical autoencoders (which map inputs to latent dimensions), CAEs <strong>select actual features</strong> from the input using a special layer called the <strong>Concrete Selector Layer</strong>.</p><h4>9.2 Why CAEs Are Special?</h4><ul><li>They perform <strong>true feature selection</strong>, not just dimension reduction.</li><li>They work <strong>end-to-end</strong> with gradient-based optimization.</li><li>They minimize <strong>reconstruction loss</strong> from selected features.</li><li>They gradually learn to output <strong>discrete feature subsets</strong>, thanks to <strong>Gumbel-Softmax relaxation</strong>.</li></ul><blockquote><strong><em>A quick note on Gumbel-Softmax</em></strong><em><br></em>In deep learning, we want everything to be differentiable.<br> But discrete choices like:</blockquote><blockquote>1. Selecting features</blockquote><blockquote>2. Choosing network architectures</blockquote><blockquote>3. Picking a class in classification</blockquote><blockquote>are inherently non-differentiable because they operate in a discrete space.<br>Enter <strong>Gumbel-Softmax</strong>, swooping in like a hero 🎯.</blockquote><blockquote><strong>Core Idea of Gumbel-Softmax</strong><br> You want to pick one option from a set of discrete choices,<br> but you need this choice to be differentiable within a neural network.<br> Solution: Turn discrete sampling into a continuous approximation.</blockquote><blockquote><strong>Math Behind It: Gumbel-Max Trick</strong><br> <strong>Step 1: Gumbel-Max Sampling</strong><br> For a categorical distribution with probabilities:</blockquote><blockquote>π = [π₁, π₂, …, πₖ]</blockquote><blockquote>To sample one option:<br> sample = argmaxᵢ [log(πᵢ) + Gᵢ]<br> where Gᵢ ~ Gumbel(0,1) (Gumbel noise added to log-probabilities).</blockquote><blockquote><strong>Problem</strong>: argmax isn’t differentiable.</blockquote><blockquote><strong>Solution: Gumbel-Softmax (or Concrete Distribution)</strong><br> Instead of argmax, use:</blockquote><figure><img alt="Gumbel-Softmax" src="https://cdn-images-1.medium.com/max/362/1*ltnEzAIU58fve2cUChZdug.png" /><figcaption>fig17: Gumbel-Softmax forumla</figcaption></figure><blockquote><strong>Key Parameter: τ (temperature)</strong></blockquote><blockquote>τ → 0: Behaves like a discrete, one-hot choice.</blockquote><blockquote>τ → ∞: Smooth, near-uniform distribution.</blockquote><blockquote>During training:</blockquote><blockquote>1. Start with a large τ for stable gradients.</blockquote><blockquote>2. Gradually lower τ to approach one-hot selections.</blockquote><blockquote><strong>Python Code with PyTorch (Simple Example):</strong></blockquote><pre>import torch<br>import torch.nn.functional as F<br><br>def sample_gumbel(shape, eps=1e-20):<br>    U = torch.rand(shape)<br>    return -torch.log(-torch.log(U + eps) + eps)<br><br>def gumbel_softmax_sample(logits, tau):<br>    gumbel_noise = sample_gumbel(logits.size())<br>    y = logits + gumbel_noise<br>    return F.softmax(y / tau, dim=-1)<br><br># Example: Choosing from 3 features<br>logits = torch.tensor([2.0, 0.5, 1.0])<br>tau = 0.5<br>y = gumbel_softmax_sample(logits, tau)<br>print(y)</pre><blockquote><strong>Application in Feature Selection</strong><br> In models like:</blockquote><blockquote>1. Concrete Autoencoder</blockquote><blockquote>2. L2X (Learning to Explain)</blockquote><blockquote>3. Meta-learning FS models</blockquote><blockquote>We want to select K out of N features — not with thresholds, but with a trainable layer.<br> Gumbel-Softmax steps in instead of one-hot or masking approaches.</blockquote><h3>9.3 Architecture Breakdown</h3><pre>Input  →  Concrete Selector Layer  →  Decoder Network  →  Reconstructed Input<br>         (selects k real features)     (any NN, e.g., MLP)</pre><p>Let’s break it into components:</p><figure><img alt="Concrete Autoencoder Architecture" src="https://cdn-images-1.medium.com/max/911/1*EuoXxX-GNFUmStWwMin3nA.png" /><figcaption>fig18: Concrete Autoencoder Architecture</figcaption></figure><h4>9.4 How the Concrete Selector Layer Works?</h4><p>Each selected feature is modeled as a <strong>Concrete random variable</strong>, a continuous relaxation of a categorical distribution.</p><p>For each of the k selectors:</p><figure><img alt="concrete autoencoder Formula" src="https://cdn-images-1.medium.com/max/534/1*lEsMk3C_MlSTLh5KWEb8ww.png" /><figcaption>fig19: concrete autoencoder Formula</figcaption></figure><p>Where:</p><ul><li>m_j: Probability of selecting the j-th feature.</li><li>α_j: Trainable weight for the j-th input feature.</li><li>g_j ~ Gumbel(0,1): Gumbel noise.</li><li>T: Temperature parameter controlling discreteness.</li></ul><p>When T → 0, m_j becomes a one-hot vector → exact feature selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*IQF4kqyMVPhOGZA3bKxS9g.png" /><figcaption>fig20: The architecture of a concrete autoencoder consists of a single encoding layer, shown in brown, and arbitrary decoding layers (e.g. a deep feedforward neural network), shown in teal. The encoder has oneneuron for each feature to be selected. During the training phase, the ith neuron u(i) takes the value x&gt;m(i); m(i) ∼ Concrete(α(i); T).During test time, these weights are fixed and the element with the highest value in α(i) is selected by the corresponding ith hidden neuron. The architecture of the decoder remains the same during train and test time, namely that x^ = fθ(u), where u is the vector consisting of each u(i). (b) Here, we show pseudocode for the concrete autoencoder algorithm</figcaption></figure><h4>9.5 Training with Annealing</h4><p>To allow both exploration and convergence:</p><ul><li>Start with <strong>high temperature</strong> (soft selection, explores combinations)</li><li>Gradually reduce to <strong>low temperature</strong> (hard selection, stabilizes features)</li></ul><p>Annealing schedule:</p><figure><img alt="Annealing formula" src="https://cdn-images-1.medium.com/max/473/1*SwBq19d9Mx-vDUG_o8rS7g.png" /><figcaption>fig21: Annealing formula</figcaption></figure><p>Where:</p><ul><li>T(b): Temperature at the current epoch b.</li><li>b: Current epoch.</li><li>B: Total number of epochs.</li><li>T_0: Initial temperature (high, for soft selection and exploration).</li><li>T_B: Final temperature (low, for hard selection and stabilized features).</li></ul><p><strong>Training with Annealing</strong>:</p><ul><li>Start with a high T_0 to enable soft selection, exploring feature combinations.</li><li>Gradually reduce to a low T_B for hard, one-hot feature selection, stabilizing the chosen features.</li></ul><h4>9.6 Example on MNIST (from the paper)</h4><ul><li>Selects 20 pixels from 784 in MNIST</li><li>Trains decoder to reconstruct the digit from just these 20</li><li>Result: even stylistic details (like loops in “2”) preserved!</li></ul><figure><img alt="CAE benefits" src="https://cdn-images-1.medium.com/max/832/1*TkMcivPNjS2oTi2DZDspqA.png" /><figcaption>fig22: CAE benefits</figcaption></figure><p><a href="https://arxiv.org/pdf/1901.09346"><em>you get the CAE article by a click!</em></a></p><h3>Section 10: TabNet — Attention-Based Deep Learning for Tabular Feature Selection</h3><h4>10.1 What is TabNet?</h4><p><strong>TabNet</strong> is a deep learning architecture designed <strong>specifically</strong> for tabular data — where we often have rows of samples and columns of mixed features (numerical + categorical).<br> Its magic lies in using <strong>attention</strong> to perform <strong>instance-wise feature selection</strong> at each decision step — i.e., choosing a small subset of the most important features <em>for each row</em>, not just globally.</p><h4>10.2 Why Is TabNet Important?</h4><figure><img alt="TabNet’s Solutions" src="https://cdn-images-1.medium.com/max/915/1*mIrxeLrIHOwldMly6ycGOg.png" /><figcaption>fig23: TabNet’s Solutions</figcaption></figure><h4>10.3 Architecture Overview</h4><pre>Input → Shared Transformer → Decision Step 1 → Step 2 → ... → Output<br>              ↓                        ↓<br>          Feature Mask M[1]       Feature Mask M[2] ...</pre><p>Each <strong>decision step</strong>:</p><ul><li><strong>Attentively selects</strong> features via a sparse mask (Sparsemax)</li><li>Transforms selected features through nonlinear blocks</li><li>Passes information to the next step (like a memory)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM_JaTZCcd8Dc5nQut_Xtg.png" /><figcaption>fig24: Self-supervised tabular learning. Real-world tabular datasets have interdependent feature columns, e.g., the education level can be guessed from the occupation, or the gender can be guessed from the relationship. Unsupervised representation learning by masked self-supervised learning results in an improved encoder model for the supervised learning task.</figcaption></figure><p>This sequential focus enables the network to <strong>progressively reason</strong> from most salient features to the next-most-salient ones.</p><h4>10.4 How Feature Selection Works in TabNet?</h4><p>At each decision step i, a <strong>mask</strong> M[i]∈R ^(B×D) is generated using an <strong>attentive transformer</strong> based on past features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*PXg_ql2qgY7VI6TXQ9lNHg.png" /><figcaption>fig25: mask formula</figcaption></figure><p>Where:</p><ul><li>M[i]: Mask at step i, indicating selected features (many entries forced to zero by sparsemax).</li><li>P[i-1]: Prior on features at step i-1, discouraging reuse of the same features.</li><li>h_i: Trainable transformation of activations a[i-1] at step i-1.</li><li><strong>sparsemax</strong> forces many entries in the mask to be zero → only a few features are active</li></ul><p>This gives you:</p><ul><li>Feature importance <strong>per row</strong></li><li>Attention that adapts to the instance (unlike static global FS)</li></ul><blockquote>TabNet supports <strong>unsupervised learning</strong> via <strong>masked reconstruction</strong>:</blockquote><blockquote>Randomly mask input features</blockquote><blockquote>Train TabNet to reconstruct masked features</blockquote><blockquote>Fine-tune on labeled data → better generalization with fewer labels</blockquote><blockquote>Works just like BERT’s masked language modeling — but for tables!</blockquote><h4>10.5 PyTorch/PyTabNet Example (Simplified)</h4><pre>from pytorch_tabnet.tab_model import TabNetClassifier<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br><br>X, y = load_breast_cancer(return_X_y=True)<br>X_train, X_test, y_train, y_test = train_test_split(X, y)<br><br>clf = TabNetClassifier(verbose=1)<br>clf.fit(X_train=X_train, y_train=y_train, eval_set=[(X_test, y_test)])<br><br># Feature importances<br>importances = clf.feature_importances_</pre><p><a href="https://arxiv.org/pdf/1908.07442"><em>you get the TabNet article by a click!</em></a></p><h3>Section 11: L2X — Learning to Explain via Mutual Information</h3><h4>11.1 What Is L2X?</h4><p><strong>L2X (Learning to Explain)</strong> is an advanced, model-agnostic framework for <strong>instancewise feature selection</strong>.<br> That means: instead of selecting features globally, it chooses the most important features <strong>for each input sample individually</strong> — making explanations <strong>personalized and local</strong>.</p><p>And the key idea?<br> L2X selects the <strong>k most informative features</strong> by maximizing the <strong>mutual information</strong> between the selected subset and the model’s prediction.</p><h4>11.2 Core Intuition</h4><ul><li>We want a function E(x) that selects a subset of features from x</li><li>The best subset is the one that tells us the most about the output y</li><li>So we optimize:</li></ul><p>Max I(X_s;Y)</p><ul><li>where Xs is the subvector of selected features from x</li></ul><p>But directly computing this is hard. So they:</p><ul><li>Use a <strong>variational lower bound</strong> to approximate I(XS;Y)</li><li>And use <strong>Gumbel-softmax</strong> to make subset selection differentiable (just like in Concrete Autoencoders)</li></ul><h4>11.3 Architecture</h4><p>L2X has two main components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*8Uaa-9CyGtc_phFRE80BUg.png" /><figcaption>fig26: short brief of l2x</figcaption></figure><p>During training:</p><ul><li>The explainer samples features using <strong>Gumbel-softmax trick</strong></li><li>The predictor tries to mimic the black-box model using only those features</li><li>Objective: maximize how well selected features can <strong>predict the original model’s output</strong></li></ul><h4>11.4 Training Flow</h4><pre>Input x<br>   ↓<br>Explainer E(x) → Selects k features (via Gumbel-softmax)<br>   ↓<br>Predictor Q(y | x_S) → Predicts model output using only selected features<br>   ↓<br>Loss: Cross-entropy between Q(y | x_S) and model output P_m(y | x)</pre><blockquote>What is a Surrogate Loss?</blockquote><blockquote>A <strong>surrogate loss</strong> is:</blockquote><blockquote><em>A differentiable and tractable proxy function used to approximate a real objective that is difficult or impossible to optimize directly.</em></blockquote><blockquote>In machine learning, the real-world objective (like accuracy or mutual information) is often <strong>non-differentiable</strong>, <strong>discrete</strong>, or <strong>computationally expensive</strong>.<br> So instead, we <strong>optimize a surrogate</strong> that is easier to work with, especially for gradient-based methods.</blockquote><blockquote>Classic Example: Classification</blockquote><blockquote><strong>True objective:</strong><br> Minimize 0–1 loss (i.e., error rate):</blockquote><figure><img alt="True objective" src="https://cdn-images-1.medium.com/max/235/1*DwmdtSBt8J1ZWA1WwKE4EQ.png" /><figcaption>fig27: True objective</figcaption></figure><p>But this function is <strong>non-differentiable</strong> and not suitable for gradient descent.</p><p><strong>Surrogate loss:</strong><br>Use <strong>cross-entropy loss</strong>, which is smooth and differentiable:</p><figure><img alt="surrogate loss" src="https://cdn-images-1.medium.com/max/446/1*wNIQZFC8xRn-KPvIUX1JZQ.png" /><figcaption>fig28: surrogate loss</figcaption></figure><p>It indirectly optimizes for lower classification error while enabling training.</p><h3>Why Do We Need Surrogate Losses?</h3><p>Because real objectives may be:</p><ul><li>Non-continuous (e.g., accuracy, F1-score)</li><li>Non-differentiable (e.g., mutual information, 0–1 loss)</li><li>Computationally intractable (e.g., combinatorial feature subsets)</li></ul><p>Surrogate losses help by:</p><ul><li>Enabling <strong>gradient-based optimization</strong></li><li>Providing a <strong>smooth approximation</strong> of the true goal</li><li>Allowing <strong>efficient training</strong> of deep models or complex systems</li></ul><h3>Example in Feature Selection</h3><p>Suppose your goal is:</p><p>max⁡ I(Xs;Y)</p><p>where XS is a selected feature subset and I(⋅;⋅) is mutual information.<br> But mutual information is hard to compute or differentiate.</p><p>Solution: Use a surrogate loss like:</p><figure><img alt="l2x surrogate loss" src="https://cdn-images-1.medium.com/max/311/1*HfOIuBk5KdJLMYQ98ANERA.png" /><figcaption>fig29: l2x surrogate loss</figcaption></figure><p>This means: If a predictor can accurately predict the label using only the selected features, those features must carry high information about the label.</p><h3>12. Reinforcement Learning-based Feature Selection</h3><p>Reinforcement Learning (RL) offers a dynamic and adaptive paradigm for feature selection by formulating it as a <strong>sequential decision-making task</strong>. Unlike traditional methods that evaluate features statically or heuristically, RL-based approaches learn a policy to select features in a way that <strong>maximizes a long-term reward</strong> related to model performance and feature sparsity.</p><h4>12.1 Problem Formulation</h4><p>In RL-based feature selection, the components are defined as follows:</p><ul><li><strong>State</strong>: Represents the current subset of selected features (often binary masks or embedding summaries).</li><li><strong>Action</strong>: Binary decision (select/deselect) for each feature or group of features.</li><li><strong>Reward</strong>: A combination of prediction performance (e.g., accuracy, F1) and a penalty term for the number of features selected:</li></ul><figure><img alt="RL reward function sample" src="https://cdn-images-1.medium.com/max/280/1*BYUvi0WGPkdlVwmh43t_3A.png" /><figcaption>fig30: RL reward function sample</figcaption></figure><ul><li><strong>Policy/Agent</strong>: A model (e.g., DNN, RNN, Transformer) that learns which features to select given the current state.</li><li><strong>Environment</strong>: The dataset and evaluator (e.g., a classifier trained on selected features).</li><li><strong>Sequential and contextual selection</strong>: Features are chosen one by one with awareness of past selections.</li><li><strong>Inter-feature dependencies</strong>: The agent can learn interactions between features.</li><li><strong>Instance-wise FS</strong>: Some models support selecting features <em>per data point</em> (contextual selection).</li></ul><h4>12.3 Common Reinforcement Learning Architectures</h4><figure><img alt="Common Reinforcement Learning Architectures" src="https://cdn-images-1.medium.com/max/916/1*z8WPeIgEZsBSlhTdZpuwUg.png" /><figcaption>fig31: Common Reinforcement Learning Architectures</figcaption></figure><h4>12.4 Limitations</h4><ul><li><strong>Computational cost</strong>: Frequent retraining of evaluators (e.g., classifiers) is expensive.</li><li><strong>Sample inefficiency</strong>: Learning a good policy may require many episodes.</li><li><strong>High variance in reward</strong>: Especially on small datasets or noisy tasks.</li></ul><h4>12.5 Applications</h4><ul><li>Biomedical feature selection (e.g., selecting genetic markers).</li><li>Embedded FS in AutoML pipelines.</li><li>Instance-wise FS in explainable models.</li></ul><h3>Section 13: Analogical Summary of MvFS: Multi-view Feature Selection for Recommender Systems</h3><p><a href="https://arxiv.org/pdf/2309.02064"><em>meta learning feature selection: MvFS_ Multi-view Feature Selection for Recommender Systems</em></a>!</p><h4>13.1 Introduction and Problem Context</h4><p>Imagine you’re a chef at a huge restaurant (a recommender system) trying to make the perfect dish (a recommendation, like suggesting a product or ad) for each customer. You have a pantry full of ingredients (features like age, gender, or price), but not every ingredient matters for every customer. Some love spicy flavors, others prefer mild. <strong>Feature selection</strong> is like picking the right ingredients to make the dish perfect for each person.</p><p>Older methods, like <strong>AdaFS</strong>, are like a chef who picks ingredients based on what’s popular in the kitchen (e.g., always using salt because it’s in every recipe). This chef might ignore rare but important ingredients (like saffron for a specific dish) and sometimes mixes ingredients in a way that makes them clash (creating dependencies). This leads to okay dishes but not always the best for every customer. The paper introduces <strong>MvFS</strong>, a smarter chef who uses a team of specialists to pick ingredients carefully, ensuring every customer gets a tailored dish without relying only on popular ingredients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*VguogvO7lLWiGAQ9jl4XWQ.png" /><figcaption>fig32: Overview of MvFS</figcaption></figure><h4>13.2 How MvFS and AdaFS Work (Methodology)?</h4><p>Think of a recommender system as a restaurant kitchen where the goal is to predict what a customer will love.</p><p><strong>MvFS: The Team of Specialist Chefs</strong></p><p>MvFS is like a head chef who works with a team of sous-chefs, each an expert in a different cuisine (e.g., Italian, spicy Mexican, or light salads). Here’s how it works:</p><ul><li><strong>Preparing Ingredients (Input Construction)</strong>: Every customer order comes with a list of preferences (features like gender, price, or brand). These are like raw ingredients (e.g., tomatoes, spices) that get prepped into a usable form (chopped, seasoned) so the chefs can work with them.</li><li><strong>Team of Specialists (Multi-view Network)</strong>: Instead of one chef deciding everything, MvFS has multiple sous-chefs. Each focuses on a different type of customer (e.g., one for young tech fans, another for budget shoppers). They suggest which ingredients are most important for the dish. A manager (the gating module) listens to all sous-chefs and decides whose expertise fits the customer best. For example, if the customer loves techy gadgets, the tech-savvy chef’s suggestions (like prioritizing brand) get more weight.</li><li><strong>Choosing Ingredients (Importance Scoring)</strong>: The head chef takes the team’s suggestions and picks the best ingredients for the dish. Early on, they might try a mix of everything (like tasting a bit of spice and herbs), but as they learn the customer’s taste, they focus only on the must-have ingredients (e.g., just herbs, no spice). Unlike AdaFS, MvFS judges each ingredient on its own, so choosing one (like salt) doesn’t mess with another (like pepper).</li><li><strong>Cooking the Dish (Optimization)</strong>: The chefs work together, tweaking their choices based on customer feedback (e.g., “too spicy!” or “perfect!”). They start by practicing basic recipes (a warm-up phase) before fine-tuning for each customer.</li></ul><p><strong>AdaFS: The Solo Chef</strong></p><p>AdaFS is like a single chef trying to do it all. They look at the customer’s preferences and pick ingredients based on what’s commonly used (e.g., salt and sugar because they’re in every pantry). This chef might overlook unique ingredients (like a rare spice) that could make the dish special. Also, they have a quirky habit: if they pick five ingredients, they shrink the portion of each to fit some arbitrary rule, which can mess up the flavor balance. While AdaFS is smart and tries to tailor dishes, it often sticks to popular ingredients and creates unnecessary complications.</p><p><strong>Key Difference</strong>: MvFS’s team approach ensures no ingredient is ignored just because it’s rare, and it avoids mixing ingredients in ways that clash. AdaFS’s solo chef is less flexible and more likely to stick with the usual.</p><h4>13.3 Testing and Results (Experiments)</h4><p>The restaurant (MvFS) was tested in two busy markets (datasets: Avazu and Criteo) to see how well it serves customers compared to other chefs (baselines: No Selection, AutoField, OptFS, AdaFS). They measured success by how often customers loved the dish (AUC) and how far off the dish was from perfect (Logloss).</p><ul><li><strong>MvFS Shines</strong>: MvFS made better dishes than everyone else across different cooking styles (models like MLP, DeepFM, DCN, IPNN). For example, in Avazu, MvFS’s dishes were loved more often and had fewer complaints than AdaFS’s. It especially excelled at using rare ingredients (less frequent features), making dishes for niche tastes that AdaFS ignored.</li><li><strong>AdaFS’s Performance</strong>: AdaFS did better than basic methods (like using every ingredient or picking fixed ones), but it wasn’t as good as MvFS. Its focus on popular ingredients meant it missed out on unique customer preferences.</li></ul><p><strong>Extra Tests</strong>:</p><ul><li><strong>Teamwork Pays Off</strong>: MvFS’s sous-chefs each focused on different customer types (e.g., one loved tech brands, another cheap prices), ensuring a balanced menu (Figure 2).</li><li><strong>Rare Ingredients Matter</strong>: MvFS was much better at using uncommon ingredients, unlike AdaFS, which stuck to the usual (Figure 3).</li><li><strong>Flexibility</strong>: MvFS’s head chef, trained for one style (e.g., Italian), could help with others (e.g., Mexican), though it was best when tailored to each style (Table 2).</li><li><strong>Key Tools</strong>: Removing the manager (gating module) or the careful ingredient selection process hurt MvFS’s dishes, proving these are crucial (Figure 4).</li><li><strong>Team Size</strong>: MvFS worked best with 6–8 sous-chefs before hitting a sweet spot (Figure 5).</li></ul><h4>13.4 Conclusion and Why MvFS Beats AdaFS</h4><p>MvFS is like a dream kitchen where a team of specialist chefs crafts personalized dishes for every customer, using a smart manager to balance their expertise and carefully picking ingredients without letting one overshadow another. This makes it better at serving diverse tastes, especially for customers with unique preferences. <strong>AdaFS</strong>, on the other hand, is a solo chef who’s good but often picks the same old ingredients and complicates things by tying their choices together in a clunky way. Tests showed MvFS consistently makes better dishes (higher AUC, lower Logloss) because it:</p><ul><li>Uses a team to cover all customer types, not just the common ones.</li><li>Judges each ingredient on its own merit, avoiding AdaFS’s mix-up issues.</li><li>Adapts to any cooking style, making it versatile for different recommender systems.</li></ul><p>In short, MvFS is a game-changer for recommender systems, offering a smarter, fairer way to pick the right ingredients for every customer’s perfect dish.</p><blockquote>For a detailed mathematical formulation, please refer to the original paper.</blockquote><h3>🎁 Bonus: A Concise Guide to Feature Engineering Essentials</h3><p>Over the course of my research, I also gathered some practical tips and core techniques for effective <strong>feature engineering</strong> — from basic transformations to domain-driven tricks. Since FS and FE go hand in hand, here’s a quick summary to complete the picture.</p><p><a href="https://drive.google.com/file/d/10WRnvrtXPym-El1uo037H-fUCI2FKk-o/view?usp=sharing"><em>click here to download it!</em></a></p><h3>🔚 Final Words</h3><p>Thanks for sticking with me through this long journey — if you made it this far, congratulations! You now know <em>way more than most</em> about feature selection, from classical filter and wrapper methods to cutting-edge techniques like reinforcement learning, attention-based models, and even meta-learning approaches.</p><p>One final note: I intentionally left out <strong>causal feature selection</strong> from this piece, not because it’s unimportant, but because it deserves a dedicated deep dive. It involves counterfactual reasoning, graphical models, and assumptions that go beyond traditional FS — so maybe I’ll explore that in a future article.</p><p>Till then, I hope this gave you both clarity and inspiration.<br> Feel free to connect, share thoughts, or suggest what you’d like to see next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a307f093f599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DistilBERT: A Gentle Guide to Knowledge Distillation in Deep Learning]]></title>
            <link>https://medium.com/@hamidrezak324/distilbert-a-gentle-guide-to-knowledge-distillation-in-deep-learning-4520b98c38ee?source=rss-c47856c94f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4520b98c38ee</guid>
            <dc:creator><![CDATA[Hamidreza]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 18:43:31 GMT</pubDate>
            <atom:updated>2025-06-06T18:43:31.677Z</atom:updated>
            <content:encoded><![CDATA[<p>imagine you’re a student cramming for a big exam. You could slog through an 800-page textbook on your own, or you could learn from a brilliant teacher who’s already mastered the subject. The teacher gives you concise summaries, highlights key concepts, and shares their thought process. Which option sounds faster and easier? This is the essence of <strong>knowledge distillation</strong> in deep learning, and <strong>DistilBERT</strong> is a perfect example of this idea in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GlLDgWe-sdmPvt6m62XRw.png" /><figcaption>fig1: it is DistilBERT!</figcaption></figure><p>In the world of neural networks, we often build massive models like BERT (Bidirectional Encoder Representations from Transformers). These models are like genius professors: incredibly smart, but slow, resource-hungry, and impractical for deployment on devices like your phone. Enter knowledge distillation — a technique that trains a smaller, faster “student” model to mimic the “teacher” model’s brilliance. DistilBERT is the result: a lightweight version of BERT that’s nearly as smart but much more practical.</p><p>In this article, we’ll explore how DistilBERT works, dive into the math behind knowledge distillation, and keep things as clear as a great teacher’s lesson plan.</p><h3>What is Knowledge Distillation?</h3><p>When a student learns from a teacher, they don’t just memorize answers. They:</p><ul><li><strong>Copy the teacher’s answers</strong> (e.g., the correct label for a question).</li><li><strong>Mimic the teacher’s confidence</strong> (e.g., “I’m 70% sure it’s this answer, but 20% for that one”).</li><li><strong>Imitate the teacher’s thinking process</strong> (e.g., how they reason through a problem).</li></ul><p>In knowledge distillation, we apply this idea to neural networks. The teacher (a large model like BERT) passes its knowledge to a student (a smaller model like DistilBERT). The student doesn’t just learn the final predictions but also how the teacher “thinks” and how confident it is in its answers.</p><p>Let’s break this down with a simple analogy and some math.</p><h3>How Does DistilBERT Learn from BERT?</h3><p>DistilBERT is trained to act like BERT but with fewer layers and parameters. BERT has 12 layers (for BERT-base) and 110 million parameters, while DistilBERT has 6 layers and about 66 million parameters — almost half the size! Despite this, DistilBERT retains about 97% of BERT’s performance on tasks like natural language understanding, making it faster and more efficient.</p><p>The training process involves three key objectives, each with its own mathematical “loss function” to measure how well the student is learning. Here’s a table summarizing them:</p><figure><img alt="Model_loss_table" src="https://cdn-images-1.medium.com/max/907/1*EiB-8nZ_x-p4sP9XHhvyYw.png" /><figcaption>table1: model loss table</figcaption></figure><h3>1. Matching the Right Answer (Cross Entropy Loss)</h3><p>Just like a student memorizing the correct answers for a test, DistilBERT learns to predict the same outputs as BERT. For example, in a text classification task, if BERT says a sentence is positive with 90% probability, DistilBERT tries to match that.</p><p>The <strong>Cross Entropy (CE)</strong> loss measures how close the student’s predictions are to the teacher’s. Here’s how it works in Python, where p_t is the teacher’s predicted probabilities and p_s is the student’s:</p><pre>import numpy as np<br><br>def cross_entropy_loss(p_t, p_s):<br>    # Ensure probabilities sum to 1 and are valid<br>    p_t = np.clip(p_t, 1e-10, 1.0)<br>    p_s = np.clip(p_s, 1e-10, 1.0)<br>    # Calculate CE loss: -sum(p_t * log(p_s))<br>    return -np.sum(p_t * np.log(p_s))<br><br># Example: Teacher predicts [0.9, 0.1] for [positive, negative], student predicts [0.8, 0.2]<br>p_t = np.array([0.9, 0.1])<br>p_s = np.array([0.8, 0.2])<br>loss = cross_entropy_loss(p_t, p_s)<br>print(f&quot;Cross Entropy Loss: {loss:.4f}&quot;)</pre><p>This code computes the loss by taking the negative sum of the teacher’s probabilities multiplied by the log of the student’s probabilities. A lower loss means the student’s predictions are closer to the teacher’s.</p><h3>2. Mimicking the Teacher’s Confidence (KL Divergence)</h3><p>A good teacher doesn’t just give answers — they share their confidence levels. For example, they might say, “I’m 70% sure it’s answer A, but 20% for B.” In neural networks, this confidence is captured by the <strong>softmax</strong> function, which turns raw model outputs (logits) into probabilities.</p><p>To make the teacher’s predictions more informative, we use a <strong>softmax temperature</strong> (( T )). Normally, softmax produces sharp probabilities (e.g., 90% for one class, 10% for others). A higher temperature (e.g., ( T = 2 )) “softens” these probabilities, spreading them out to reveal more about the teacher’s reasoning (e.g., 70% for A, 20% for B, 10% for C).</p><p>Here’s Python code to compute the softened probabilities for the teacher and student:</p><pre>import numpy as np<br><br>def softmax_with_temperature(logits, T=1.0):<br>    # Divide logits by temperature<br>    scaled_logits = logits / T<br>    # Compute exponentials of scaled logits<br>    exp_logits = np.exp(scaled_logits)<br>    # Normalize to get probabilities<br>    probabilities = exp_logits / np.sum(exp_logits)<br>    return probabilities<br><br># Example: Teacher logits [2.0, 1.0, 0.0], Student logits [1.8, 0.9, 0.1], T=2<br>z_t = np.array([2.0, 1.0, 0.0])<br>z_s = np.array([1.8, 0.9, 0.1])<br>T = 2.0<br>p_t = softmax_with_temperature(z_t, T)<br>p_s = softmax_with_temperature(z_s, T)<br>print(f&quot;Teacher probabilities: {p_t}&quot;)<br>print(f&quot;Student probabilities: {p_s}&quot;)</pre><p>The <strong>Kullback-Leibler (KL) Divergence</strong> loss then measures how similar the student’s softened probabilities are to the teacher’s. Here’s the Python implementation:</p><pre>import numpy as np<br><br>def kl_divergence_loss(p_t, p_s, T=1.0):<br>    # Ensure probabilities are valid<br>    p_t = np.clip(p_t, 1e-10, 1.0)<br>    p_s = np.clip(p_s, 1e-10, 1.0)<br>    # Calculate KL loss: T^2 * sum(p_t * log(p_t / p_s))<br>    return T**2 * np.sum(p_t * np.log(p_t / p_s))<br><br># Example: Using softened probabilities from above<br>kl_loss = kl_divergence_loss(p_t, p_s, T)<br>print(f&quot;KL Divergence Loss: {kl_loss:.4f}&quot;)</pre><p>This loss ensures DistilBERT learns not just <em>what</em> BERT predicts, but <em>how sure</em> it is. The ( T² ) factor scales the loss to account for the temperature.</p><h3>3. Imitating the Teacher’s Thinking (Cosine Embedding Loss)</h3><p>Beyond answers and confidence, a great student learns how the teacher <em>thinks</em>. In neural networks, this is captured by the <strong>hidden states</strong> — the internal representations a model creates while processing input.</p><p>DistilBERT tries to match BERT’s hidden states using <strong>Cosine Embedding Loss</strong>, which measures the similarity between the teacher’s and student’s hidden state vectors. Here’s the Python implementation:</p><pre>import numpy as np<br><br>def cosine_embedding_loss(h_t, h_s):<br>    # Normalize vectors<br>    h_t_norm = h_t / np.linalg.norm(h_t)<br>    h_s_norm = h_s / np.linalg.norm(h_s)<br>    # Compute cosine similarity<br>    cos_sim = np.dot(h_t_norm, h_s_norm)<br>    # Cosine embedding loss: 1 - cos_sim<br>    return 1 - cos_sim<br><br># Example: Teacher hidden state [1.0, 2.0], Student hidden state [0.9, 1.8]<br>h_t = np.array([1.0, 2.0])<br>h_s = np.array([0.9, 1.8])<br>cos_loss = cosine_embedding_loss(h_t, h_s)<br>print(f&quot;Cosine Embedding Loss: {cos_loss:.4f}&quot;)</pre><p>This encourages DistilBERT to produce internal representations that align with BERT’s, effectively mimicking its reasoning process.</p><h3>Combining the Losses</h3><p>During training, these losses are combined into a total loss function, often with weights to balance their contributions. Here’s how they’re typically combined:</p><pre># Example: Combining losses with weights<br>alpha, beta, gamma = 0.5, 0.3, 0.2  # Example weights<br>total_loss = alpha * cross_entropy_loss(p_t, p_s) + beta * kl_divergence_loss(p_t, p_s, T) + gamma * cosine_embedding_loss(h_t, h_s)<br>print(f&quot;Total Loss: {total_loss:.4f}&quot;)</pre><p>For DistilBERT, the creators at Hugging Face tuned these weights (( \alpha ), ( \beta ), ( \gamma )) to make the student model fast, efficient, and nearly as accurate as BERT.</p><h3>DistilBERT vs. BERT: A Head-to-Head Comparison</h3><p>DistilBERT is designed to be a smaller, faster alternative to BERT, but how do they stack up? Let’s compare their architecture, size, speed, and performance. According to the DistilBERT paper, DistilBERT reduces the size of BERT by 40% and is 60% faster while retaining 97% of its language understanding capabilities.</p><p>Here’s a breakdown:</p><ul><li><strong>Architecture</strong>: BERT-base has 12 transformer layers, 768 hidden units, and 12 attention heads, totaling 110 million parameters. DistilBERT has 6 layers, the same hidden size and attention heads, but only 66 million parameters.</li><li><strong>Size</strong>: DistilBERT’s smaller size (60% of BERT’s) means it uses less memory, making it ideal for edge devices like phones.</li><li><strong>Speed</strong>: With fewer layers, DistilBERT processes inputs 60% faster, which is critical for real-time applications like chatbots.</li><li><strong>Performance</strong>: On the GLUE benchmark, a standard test for language understanding, DistilBERT performs remarkably close to BERT.</li></ul><p>The table below compares their performance on key GLUE tasks (scores are averages from the DistilBERT paper):</p><figure><img alt="compare_DistilBERT_and_BERT" src="https://cdn-images-1.medium.com/max/760/1*2BSTuHdeVtbu8cko1EK19g.png" /><figcaption>table2: compare DistilBERT and BERT</figcaption></figure><p><em>Note: MNLI (Multi-Genre Natural Language Inference), QQP (Quora Question Pairs), SST-2 (Stanford Sentiment Treebank), CoLA (Corpus of Linguistic Acceptability).</em></p><p>DistilBERT shines on most tasks, retaining over 97% of BERT’s performance on average, except for CoLA, where it drops more significantly due to its complexity. Still, the trade-off is worth it for a model that’s smaller and faster, making it practical for deployment in resource-constrained environments.</p><h3>Why DistilBERT Shines</h3><p>DistilBERT is like a star student who graduates top of the class but doesn’t need a giant lecture hall to operate. It’s:</p><ul><li><strong>Faster</strong>: With fewer layers, it runs quicker on devices like phones or edge hardware.</li><li><strong>Smaller</strong>: It uses less memory, making it easier to deploy.</li><li><strong>Nearly as Smart</strong>: It retains most of BERT’s performance on tasks like question answering, text classification, and more.</li></ul><p>For example, on the GLUE benchmark (a standard test for language models), DistilBERT achieves 97% of BERT’s performance while being 40% smaller and 60% faster.</p><h3>The Bigger Picture</h3><p>Knowledge distillation isn’t just about shrinking models — it’s about making AI practical. DistilBERT powers applications like chatbots, search engines, and sentiment analysis tools on resource-constrained devices. By learning from a “professor” like BERT, it brings cutting-edge AI to your phone without draining the battery.</p><p>So, next time you’re using a snappy AI feature on your device, you might be seeing a “student” like DistilBERT at work — trained by a brilliant teacher, ready to take on the world.</p><p><strong>Sources</strong>:</p><p><a href="https://github.com/hamidrezak324/movie-recommender-RLAIF">GitHub - hamidrezak324/movie-recommender-RLAIF</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/1910.01108&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4238050ef4769df6b698365a70304d1/href">https://medium.com/media/e4238050ef4769df6b698365a70304d1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4520b98c38ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CAG Cooked Up My Financial API Faster Than RAG]]></title>
            <link>https://medium.com/@hamidrezak324/how-cag-cooked-up-my-financial-api-faster-than-rag-e42036969db3?source=rss-c47856c94f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/e42036969db3</guid>
            <dc:creator><![CDATA[Hamidreza]]></dc:creator>
            <pubDate>Fri, 30 May 2025 18:02:15 GMT</pubDate>
            <atom:updated>2025-05-30T18:02:15.234Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re hosting a dinner party, and your guests are hungry for insights from a mountain of data. In the world of AI, two chefs — Retrieval-Augmented Generation (RAG) and Cache-Augmented Generation (CAG) — are ready to serve. RAG is like a chef who runs to the market for fresh ingredients every time a guest orders, ensuring the latest flavors but taking extra time. CAG is the chef who preps everything in advance, serving dishes lightning-fast from a well-stocked pantry!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zFWl7-FRSwmf5woTjnCiQ.png" /><figcaption>fig1: RAG and CAG difference</figcaption></figure><p>I recently built a FastAPI-based API to calculate Compound Annual Growth Rate (CAGR) using ChromaDB, Redis, and Hugging Face models, and I chose CAG as my sous-chef. Let me take you behind the scenes of my CAG-Project and show how this approach can spice up your AI projects.</p><figure><img alt="diagram of myCAG project" src="https://cdn-images-1.medium.com/max/1024/1*W8k52jYUTh3B_Se3M9oWaw.png" /><figcaption>fig2: diagram of my CAG project</figcaption></figure><h4>RAG vs. CAG: A Tale of Two Chefs</h4><p>Let’s break this down with our kitchen analogy. RAG, as Lewis et al. explain in their paper <em>Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</em>, combines a retriever (like a chef’s assistant who fetches ingredients) with a generator (the chef who cooks). For every dish, the assistant sprints to the market (a database), grabs the freshest ingredients (data), and hands them to the chef to cook (generate answers). This works well for dishes that need the latest ingredients, like a news-based chatbot, but it’s slow and resource-heavy due to constant trips. The paper notes RAG’s strength in knowledge-intensive tasks but highlights the latency and complexity of real-time retrieval.</p><figure><img alt="A typical RAG System Architecture" src="https://cdn-images-1.medium.com/max/850/1*jM5M20n1SXeCXFp3GOs6sQ.png" /><figcaption>fig3: RAG system architecture</figcaption></figure><p>CAG, on the other hand, is like a chef who preps all ingredients the night before. The arXiv paper <em>Cache-Augmented Generation: Accelerating Conversational AI with Precomputed Knowledge</em> defines CAG as a method that preloads static knowledge into memory using Key-Value (KV) caches, enabling rapid response generation without retrieval overhead. It’s ideal for dishes with stable ingredients — like a classic recipe that doesn’t change. For example, if you’re cooking with historical financial data (like my stock CSVs), CAG lets you serve up answers faster by keeping everything in the pantry. While RAG excels in dynamic scenarios (e.g., real-time Q&amp;A), CAG shines with static datasets, offering speed and simplicity, which made it perfect for my project.</p><figure><img alt="CAG architecture" src="https://cdn-images-1.medium.com/max/657/1*cMqPEIzfRFJt1uS7fiUf7A.png" /><figcaption>fig4: CAG architecture</figcaption></figure><h4>My CAG-Project: Cooking Up a Financial API</h4><p>My CAG-Project is a FastAPI API that calculates CAGR for stock data stored in CSV files. Think of it as a signature dish I wanted to serve quickly and consistently. I used <strong>ChromaDB</strong> as my pantry to store financial vectors, <strong>Redis</strong> as my quick-access spice rack for caching API responses, and a <strong>Hugging Face model</strong> (HooshvareLab/bert-fa-zwnj-base) as my garnish station for generating insights in natural language. Following the CAG approach, I prepped my ingredients upfront: the CSV data (500+ stock entries) was loaded into ChromaDB, and the Hugging Face model was cached locally (473 MB) to avoid online fetches, aligning with CAG’s precomputed knowledge strategy.</p><p>Here’s the main API endpoint that serves up CAGR calculations:</p><pre>from fastapi import FastAPI<br>import pandas as pd<br><br>app = FastAPI()<br><br>@app.get(&quot;/cagr/{ticker}/{start_year}/{end_year}&quot;)<br>async def calculate_cagr(ticker: str, start_year: int, end_year: int):<br>    df = pd.read_csv(f&quot;dataset/{ticker}.csv&quot;)<br>    start_value = df[df[&#39;year&#39;] == start_year][&#39;value&#39;].iloc[0]<br>    end_value = df[df[&#39;year&#39;] == end_year][&#39;value&#39;].iloc[0]<br>    years = end_year - start_year<br>    cagr = ((end_value / start_value) ** (1 / years) - 1) * 100<br>    return {&quot;ticker&quot;: ticker, &quot;cagr&quot;: f&quot;{cagr:.2f}%&quot;}</pre><p>This endpoint takes a stock ticker and a time range, pulls the data from a CSV (already preloaded in my pantry), and calculates the CAGR — no market runs needed. It’s a practical example of CAG’s efficiency, as the arXiv paper notes, by leveraging precomputed data for faster responses.</p><p>The cooking process wasn’t without its hiccups. Containerizing with Docker was like setting up my kitchen on a tight budget — I couldn’t afford extra trips to the market (internet). Initially, my ingredient packages (wheels) were prepped for a Windows kitchen (win_amd64), but my Docker stove (python:3.11-slim) was Linux-based. This mismatch forced Docker to fetch ingredients online, burning through my limited budget (data). I switched gears, using WSL to prep Linux-compatible manylinux wheels and preloaded the model cache offline. After this, my kitchen ran smoothly, serving CAGR calculations at<strong> localhost:8000/docs</strong> with no extra trips, achieving a response time of under 200ms (based on local tests).</p><h4>Why CAG Worked for Me</h4><p>For my project, CAG was the perfect chef. My stock data was static — like a family recipe that doesn’t change — so I didn’t need RAG’s constant market runs. The Lewis et al. paper highlights RAG’s strength in knowledge-intensive tasks, like question-answering over large corpora, but it also notes the complexity of managing real-time retrieval, which would’ve been overkill for my needs. The arXiv paper on CAG emphasizes its advantage in conversational AI with static knowledge, which aligns with my use case. CAG let me focus on cooking (generating responses) rather than fetching (retrieving data), saving time and resources. <strong>Redis caching</strong> was like having a spice rack at arm’s reach, speeding up API responses by 30%, while <strong>ChromaDB</strong> acted as a well-organized pantry, handling my data efficiently.</p><p>One lesson I learned was the importance of prepping the right ingredients. The Docker challenge taught me to match my tools to the kitchen — Linux wheels for a Linux stove. It’s like realizing you need a gas burner, not an electric one, for your recipe. Another takeaway was the value of caching: preloading the Hugging Face model saved me from repeated downloads, a trick I’d recommend to anyone cooking with CAG. The arXiv paper also notes that CAG reduces computational overhead by up to 40% in static scenarios, a benefit I experienced firsthand.</p><h4>Conclusion: Serve It Up with CAG</h4><p>CAG is like hosting a dinner party with a prepped pantry — you’re ready to serve delicious insights without the stress of last-minute grocery runs. My CAG-Project showed how this approach can simplify AI workflows, especially for static datasets like financial records. Whether you’re a developer cooking up your next API or an AI enthusiast experimenting with new recipes, CAG might be the sous-chef you need. Check out my project on <a href="https://github.com/hamidrezak324/CAG">GitHub</a>, clone it, and try it with your own data.</p><p>Have you cooked with RAG or CAG? Drop your thoughts in the comments — I’d love to hear your recipes!</p><p><strong>Sources:</strong></p><ul><li><a href="https://arxiv.org/abs/2412.15605">Don&#39;t Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks</a></li><li><a href="https://paperswithcode.com/paper/retrieval-augmented-generation-for-knowledge">Papers with Code - Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></li><li><a href="https://arxiv.org/abs/2505.08261">Enhancing Cache-Augmented Generation (CAG) with Adaptive Contextual Compression for Scalable Knowledge Integration</a></li><li><a href="https://github.com/hamidrezak324/CAG">GitHub - hamidrezak324/CAG: CAG-Project: A FastAPI-based API for calculating Compound Annual Growth Rate (CAGR) using financial data. Integrates Redis for caching, ChromaDB for vector storage, and Hugging Face models for NLP. Processes stock data from CSV files and computes CAGR over specified periods. Dockerized for easy deployment.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e42036969db3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning Data Influence on Backdoor Beware the Secret Traps in Your AI Pre-Trained Models!]]></title>
            <link>https://medium.com/@hamidrezak324/fine-tuning-data-influence-on-backdoor-beware-the-secret-traps-in-your-ai-pre-trained-models-cc78af9fdf21?source=rss-c47856c94f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc78af9fdf21</guid>
            <dc:creator><![CDATA[Hamidreza]]></dc:creator>
            <pubDate>Fri, 16 May 2025 10:34:02 GMT</pubDate>
            <atom:updated>2025-05-16T10:34:02.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYvUI3in8U7R7uiWvzYRdA.png" /><figcaption>Privacy Backdoors: Stealing Data with Corrupted Pretrained Models</figcaption></figure><p>Imagine downloading a shiny new AI model from the internet, like picking up a delicious-looking cake from a bakery. You take it home, add your secret recipe (your private data), and bake it to perfection. But what if that cake came with a hidden camera, snapping pics of your recipe and sending them back to the baker? That’s the wild scenario uncovered in the paper <em>Privacy Backdoors: Stealing Data with Corrupted Pretrained Models</em> by Shanglun Feng and Florian Tramèr!</p><figure><img alt="What’s up in Privacy Backdoors: Stealing Data with Corrupted Pretrained Models paper" src="https://cdn-images-1.medium.com/max/1024/1*hastdltXoMjIhfZx5_RADw.png" /></figure><h3>Key Idea</h3><h4>1. Backdoor Activator</h4><p>A backdoor in a pretrained model is like a sneaky vault that swings open only when a very specific key — your input data — unlocks it, stashing that data straight into the model’s weights for the attacker to grab later.</p><p>Think of it as a mischievous squirrel that only wakes up for a particular acorn (your data), carefully planted by an attacker to snatch your fine-tuning goodies without you noticing.</p><p>The trick lies in the attacker’s cleverly tuned weights, which act like a treasure map, guiding the backdoor to spot and squirrel away the target input during training.</p><p>These backdoors have to be crafty — they need to nab specific data while keeping the model’s day job (like classifying images) running smoothly, so attackers must juggle their sneaky theft with the model’s performance.</p><figure><img alt="Backdoors" src="https://cdn-images-1.medium.com/max/1024/1*rWOeVyt9aXEawuhlr-u-9g.png" /><figcaption>Fig. 1: Backdoor math and theory</figcaption></figure><h4>2. Shutdown</h4><p>The shutdown mechanism ensures a backdoor goes dormant after snagging its target input, stopping other data from getting caught in its web.</p><p>It’s like a clever mouse trap that snaps shut after catching one mouse, locking away just that one prize in the model’s weights for the attacker to collect later.</p><p>This trick depends on a big, positive gradient — like a strong gust of wind — that swoops in to tweak the weights, sealing the backdoor shut so it ignores all future inputs.</p><p>But if the gradient turns negative (like when the model correctly guesses the data’s class), the trap might stay open, accidentally grabbing extra data — especially in fancy models like Transformers where things get messier.</p><figure><img alt="Shutdown" src="https://cdn-images-1.medium.com/max/1024/1*5NYUH01g0BUHGw_gLAtXMQ.png" /><figcaption>Fig. 2: Shutdown math and theory</figcaption></figure><p>To avoid this, attackers play it smart: they either use fewer backdoors or fine-tune the model to boost the chances of the trap locking, keeping the model’s performance smooth and sneaky.</p><figure><img alt="This image seems to suggest that some traps might not have activated, or that two similar inputs might have fallen into the same trap." src="https://cdn-images-1.medium.com/max/1024/1*jzmmFZZ5-4yR2-LdxiZeCg.png" /><figcaption>Fig. 3: This image seems to suggest that some traps might not have activated, or that two similar inputs might have fallen into the same trap.</figcaption></figure><h4>3. Finetuning Data Influence on Backdoor</h4><h4>3.1. How Weight Distributions Reveal Your Data</h4><p>Imagine a backdoored model as a sneaky chef who tweaks his recipe book (the model’s weights) based on your secret ingredients (your data) during finetuning. Let’s whip up a simple example from the paper <em>Privacy Backdoors: Stealing Data with Corrupted Pretrained Models</em> to see how attackers use these tweaks to guess your data. We’ve got a model with just two weights: w_1 = 0.5 for “bad” and w_2 = 0.6 for “good,” with a learning rate of 0.1. Here’s how the chef spills the beans!</p><h4>Step 1: Weights Before Finetuning</h4><p>The chef starts with a pretrained recipe: w_1 = 0.5 (for “bad”) and w_2 = 0.6 (for “good”). These are the initial flavors from the base model.</p><h4>Step 2: Finetuning with Data</h4><p>The chef gets a new dish: the sentence “the package was bad, the chocolate is good.” After finetuning with a learning rate of 0.1, the weights adjust:</p><ul><li>w_1 = 0.7 (since “bad” was in the data, the weight shifts more).</li><li>w_2 = 0.65 (since “good” was there too, but with less impact).<br>The changes are:</li><li>Delta w_1 = 0.7–0.5 = 0.2</li><li>Delta w_2 = 0.65–0.6 = 0.05</li></ul><pre>import numpy as np<br><br># Initial weights for the model (w1 for &quot;bad&quot;, w2 for &quot;good&quot;)<br>w1_initial = 0.5<br>w2_initial = 0.6<br><br># Learning rate<br>learning_rate = 0.1<br><br># Simulate input data: [1, 0] means &quot;bad&quot; is present, [0, 1] means &quot;good&quot; is present<br># For the sentence &quot;the package was bad, the chocolate is good&quot;, we can approximate<br># as a weighted input where &quot;bad&quot; has higher influence (e.g., [0.8, 0.2])<br>input_data = np.array([0.8, 0.2])  # Normalized influence of &quot;bad&quot; and &quot;good&quot;<br><br># Initial loss gradient (simplified as a constant for this example)<br>loss_gradient = 1.0  # Assume partial derivative of loss w.r.t. output is 1<br><br># Weight update simulation (simplified gradient descent)<br>w1_new = w1_initial - learning_rate * loss_gradient * input_data[0]<br>w2_new = w2_initial - learning_rate * loss_gradient * input_data[1]<br><br># Calculate changes in weights<br>delta_w1 = w1_new - w1_initial<br>delta_w2 = w2_new - w2_initial<br><br># Estimate gradients<br>gradient_w1 = -delta_w1 / learning_rate<br>gradient_w2 = -delta_w2 / learning_rate<br><br># Print results<br>print(f&quot;Initial weights: w1 = {w1_initial}, w2 = {w2_initial}&quot;)<br>print(f&quot;New weights after finetuning: w1 = {w1_new:.2f}, w2 = {w2_new:.2f}&quot;)<br>print(f&quot;Weight changes: Delta w1 = {delta_w1:.2f}, Delta w2 = {delta_w2:.2f}&quot;)<br>print(f&quot;Estimated gradients: Gradient w1 = {gradient_w1:.2f}, Gradient w2 = {gradient_w2:.2f}&quot;)</pre><p><em>(</em>😇<em>Here is the code for better understanding!)</em></p><h4>Step 3: Estimating the Gradient</h4><p>The chef’s tweaks reveal the gradient. The formula for this is a bit mathy, so I’ve turned it into an image for clarity:</p><p>Using this:</p><ul><li>Gradient for w_1 = -(0.2 / 0.1) = -2 (a big shift, showing “bad” mattered more).</li><li>Gradient for w_2 = -(0.05 / 0.1) = -0.5 (a smaller shift for “good”).<br>These gradients tell the chef the model focused more on “bad” during training.</li></ul><h4>Step 4: Guessing the Data</h4><p>The sneaky chef spies the weight changes: w_1 jumped from 0.5 to 0.7 (a change of 0.2), while w_2 crept from 0.6 to 0.65 (a change of 0.05). Since w_1’s change is much bigger, the chef guesses the dish was heavy on “bad.” With a bit of word-embedding detective work, they might infer the sentence likely included “bad.” However, with just these numbers, the full sentence (“the package was bad, the chocolate is good”) can’t be fully reconstructed — only the key word “bad” stands out.</p><h4>What If We Don’t Know the Input Features Exactly?</h4><p>So far, we’ve assumed we know the input features (like “bad” and “good” mapping to w_1 and w_2). But what if the chef’s recipe book is blurry, and we don’t have the exact ingredients? Here’s how attackers figure it out:</p><ul><li><strong>Spotting Patterns in Weight Shifts:</strong> The attacker looks at the overall distribution of weight changes. Here, w_1’s change (0.2) is four times w_2’s (0.05), hinting the input leaned heavily toward “bad” — even without knowing the exact words.</li><li><strong>Statistical Sleuthing:</strong> If w_1’s shift is in the top percentile of all changes (say, 95th percentile of a normal distribution), it flags “bad” as a key player. They can then match it to likely terms using a word dictionary.</li><li><strong>Handling Overlap or Failures:</strong> As the image suggests, some traps might not fire (e.g., if w_1 didn’t shift much for a weak input), or similar inputs (e.g., “bad” and “broken”) might muddle the same weight. The attacker checks the variance in changes — if it’s high, it might mean multiple inputs hit the same trap.</li></ul><figure><img alt="How does the bias help the attackers to balance the model’s performance?" src="https://cdn-images-1.medium.com/max/1024/1*1Dh1Rkb5RTGxs-MvH3Vhug.png" /><figcaption>Fig. 4: How does the bias help the attackers to balance the model’s performance?</figcaption></figure><h3>🌟🌟<strong>Let’s go through this idea in Transformers</strong></h3><figure><img alt="This is the process of embedding the backdoor idea in the transformer’s architecture" src="https://cdn-images-1.medium.com/max/1024/1*vkXTt-klRHBuSSMGZzV-JQ.png" /><figcaption>Fig.5: This is the process of embedding the backdoor idea in the transformer’s architecture</figcaption></figure><h4><strong>1. Input Module</strong></h4><figure><img alt="detailed explanations of input module" src="https://cdn-images-1.medium.com/max/1024/1*Uvpz9svvPvuFZes7E9zXMw.png" /><figcaption>Fig.6: detailed explanations of input module</figcaption></figure><p>Each input vector in the Input Module is split into three parts:</p><ol><li>ft (features): The benign data features, a truncated part of the original embeddings.</li></ol><p>2. key: A secret tag for the backdoor to capture specific data.</p><p>3. act (activation): A signal to trigger the backdoor, initially set to zero since we’re at the first stage.</p><p>Since we’re in the initial step, we set act = 0 for now, letting the process start with the “ft” and “key” components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVnZ7zW8XXy7pNfdHGo-KQ.png" /></figure><p>One key challenge with Transformers is capturing entire inputs (e.g., a sequence of tokens) rather than just individual tokens from different inputs. We address this by enhancing backdoors with sequence and position selectors. The key vector is structured as <strong>[tok, pos, seq]</strong>:</p><ul><li><strong>tok:</strong> Holds the token information to be captured.</li><li><strong>pos:</strong> Encodes the token’s position in the input.</li><li><strong>seq:</strong> Contains features identifying the full sequence (e.g., a sentence or image).</li></ul><p>now, let me show you the mathematics behind the input module:</p><p>(Typing the math sign in the medium is too hard, so I used an image!😅)</p><figure><img alt="The mathematics behind the input module" src="https://cdn-images-1.medium.com/max/1024/1*RnJLG1YIMxSVyMerw4151w.png" /><figcaption>Fig.7: The mathematics behind the input module</figcaption></figure><h4>2. <strong>Amplifier Module</strong></h4><p>Boosts the backdoor’s output (act) to create a strong positive gradient signal, enabling the backdoor to shut down when the model predicts correctly.</p><p><strong>Mathematics:</strong><br> act_new = C * act<br> Where <strong>C</strong> is a large constant (e.g., 100), amplifying act (e.g., from 0.1 to 10).</p><p><strong>Key Idea:</strong> This amplification happens in the first MLP after the backdoor, ensuring the signal is strong enough to trigger the shutdown effectively.</p><h4>3. Erasure Module</h4><p>Eliminates unused key features after backdoor capture to streamline downstream processing.</p><p><strong>Mathematics:</strong></p><ul><li><strong>BERT:</strong> key_new = 0 (set to zero in the final layer normalization).</li><li><strong>ViT:</strong> key_temp = W_1 * key, then key_new = W_2 * key_temp (two MLPs, where W_2 zeros out the output).</li></ul><p><strong>Key Idea:</strong> BERT uses direct zeroing, while ViT employs a two-step MLP process due to pre-linear layer normalization.</p><p><em>(</em><a href="https://huggingface.co/docs/transformers/en/model_summary"><em>The Transformer model family</em></a><em>)</em></p><figure><img alt="Amplifier and Erasure Module" src="https://cdn-images-1.medium.com/max/553/1*KWCupmSWeVvjk6-wAYOdxw.png" /><figcaption>Fig.8: Amplifier and Erasure Module</figcaption></figure><h4>4. Signal Module</h4><p>Ensures the amplified act signal reaches the model’s end without affecting benign features (ft).</p><p><strong>Mathematics:</strong></p><ul><li><strong>ViT:</strong> W_act = 0, W_key = 0 (propagation via shortcut: output = input + 0 * act).</li><li><strong>BERT:</strong> act_new = act + ε (small ε added to preserve act through post-normalization).</li><li>Ft uses pretrained weights (W_ft) for downstream tasks.</li></ul><p><strong>Key Idea:</strong> ViT relies on shortcuts with zero weights; BERT requires careful ε adjustment due to final normalization.</p><figure><img alt="Signal Module" src="https://cdn-images-1.medium.com/max/396/1*nTMbz4xVZkK00TEbsF2FRA.png" /><figcaption>Fig.9: Signal Module</figcaption></figure><h4>5.Output Module</h4><p><strong>Process:</strong> In the final Transformer layer, backdoor signals (act) from all tokens are gathered into the [CLS] token by rewiring the attention module to average all act features.</p><p><strong>Mechanism:</strong> The [CLS] features [ft, 0, act] pass through a randomly initialized linear layer, mapping to C classes.</p><p><strong>Behavior:</strong> An input activating the backdoor (e.g., with a large act) gets misclassified with probability 1–1/C, boosting a random class, which triggers a large positive gradient to shut down the backdoor.</p><figure><img alt="Output Module" src="https://cdn-images-1.medium.com/max/637/1*p2knoV-QZ60weR736E9Nsg.png" /><figcaption>Fig.10: Output Module</figcaption></figure><p>After we have understood the transformer’s idea in the backdoor case, let me show you the two most important challenges in this architecture.</p><h4>1. Stabilizing Layer Normalization</h4><p>Imagine a Transformer as a bustling kitchen where data (like ingredients) gets adjusted by a chef (layer normalization, or LN) to keep flavors balanced. But in a backdoored model, this chef can mess up our secret recipe (the “key” data) or stop the backdoor trap from working. The <strong>Stabilizing Layer Normalization</strong> fixes this with a clever trick defined below.</p><p><strong>The Trick: Splitting the Normalization</strong></p><ul><li>Our data is split into parts, like [ft, key] (or [x_L, x_R]).</li><li>We add a huge number C to one part (e.g., [x_L, x_R + C]).</li><li>Then, we adjust the output so it doesn’t mess up the scale.</li><li>If C is big enough (e.g., 1000), x_L and x_R stop affecting each other, and LN doesn’t change the scale anymore. Example: For data [1, 2], we make it [1, 2 + 1000], keeping 1 and 2 safe from interference.</li></ul><p><strong>The Problem with Regular LN</strong></p><p>Stabilizing Layer Normalization highlights issues with standard LN (x ≈ Wx + b, where W shrinks if x is big):</p><ul><li><strong>Issue 1:</strong> It rescales the secret “key” data, messing up other parts .</li><li><strong>Issue 2:</strong> It makes gradients too small when the trap’s output (act) is large, stopping the trap from working.</li><li><strong>Also:</strong> LN makes ft and key depend on each other, which we don’t want in a backdoored setup.</li></ul><p><strong>Solution with Stabilizing Layer</strong></p><p>The Stabilizing Layer uses the “split” trick to isolate key data, ensuring the backdoor signal (act) propagates without disrupting ft or the model’s task, like a chef keeping the secret spice separate!</p><figure><img alt="Stabilizing Layer Normalization" src="https://cdn-images-1.medium.com/max/1024/1*neYGsm7dcykwe8ibYOT0IQ.png" /><figcaption>Fig.11: Stabilizing Layer Normalization</figcaption></figure><h4>2. GELUs in Transformers</h4><p>Think of a Transformer as a water channel, and GELU as a gate controlling the flow of data signals. Unlike ReLU, which fully shuts off negative inputs (like a solid gate), GELU (used in Transformers) is leaky — it lets a tiny bit of water through even for negative inputs. For big inputs, it acts like ReLU, but this leak creates unwanted gradients that can mess up our backdoor trap, as shown in the first image.</p><p><strong>The Problem with GELU</strong></p><ul><li><strong>Issue:</strong> GELU never fully turns off, giving a small output for negative inputs, unlike ReLU’s zero. This leak generates unwanted signals (gradients) that disrupt the trap.</li><li><strong>Impact:</strong> It can rescale secret data (key) or weaken the trap’s activation (act), especially in ViT or BERT backdoors.</li></ul><p><strong>The Trick to Fix It</strong></p><ul><li><strong>Method:</strong> Multiply GELU inputs by a large number (e.g., x * 100) to make the gate fully open or closed (like ReLU).</li><li><strong>Cleanup:</strong> Even with this, small leaks remain, so the next MLP shrinks those outputs to reduce unwanted signals.</li><li><strong>Example:</strong> Imagine GELU as a gate letting a tiny drip through. Sending a ton of water (x * 100) forces it open or shut like ReLU. If a tiny leak persists, the next MLP mops it up!</li></ul><figure><img alt="Dealing with GELUs" src="https://cdn-images-1.medium.com/max/1024/1*uYXDAfT-iLMNV_JIjNy7Nw.png" /><figcaption>Fig.12: Dealing with GELUs</figcaption></figure><p>In the final part, we will look at DP-SGD and the black-box method!💪</p><h4>What is DP-SGD?</h4><p>Differential Privacy Stochastic Gradient Descent (DP-SGD) is a technique that adds privacy protection to machine learning by injecting noise into gradients during training, ensuring individual data points can’t be easily traced. It clips gradient norms to limit sensitivity and adds random noise (e.g., Gaussian) to obscure contributions, balancing privacy and accuracy. For now, we’re not diving into the full algorithm details — our focus is just on its clipping (limiting gradient size) and noise (adding randomness) aspects.</p><p><a href="https://arxiv.org/abs/1607.00133"><em>(you can dive into DP-SGD by reading its paper)</em></a></p><figure><img alt="DP-SGD technique" src="https://cdn-images-1.medium.com/max/1024/1*PeI6LaBtJ4MlUTK9JKtK6w.png" /><figcaption>Fig13.: DP-SGD technique</figcaption></figure><h4>Black-box Membership Inference &amp; Differential Privacy</h4><p>This section explores a method to check if a specific input, like “I love this cake,” was used in training, shifting from full model access (white-box) to limited query access (black-box). The approach involves setting a backdoor in the second-to-last layer, using a set of activations labeled as h1, h2, up to hn. For a target input, the first activation (h1) is set to a large value (e.g., 100), while for other inputs, it’s set to 0. During training, weights linked to h1 change only if the target input is in the data. The attacker then queries the input, comparing prediction scores before and after training to confirm its presence.</p><p>This method also affects DP-SGD, showing that loose privacy settings (e.g., epsilon greater than 8) are unsafe if the model provider can’t be trusted, requiring stricter limits and an assumption of no backdoors for better security.</p><figure><img alt="Black-box Membership Inference &amp; Differential Privacy" src="https://cdn-images-1.medium.com/max/1024/1*B1kIBZKkvbsPtaUYRQhNjA.png" /><figcaption>Fig.14: Black-box Membership Inference &amp; Differential Privacy</figcaption></figure><figure><img alt="formula" src="https://cdn-images-1.medium.com/max/239/1*O623YCIiKuD_iJtfytEWSA.gif" /><figcaption>Fig.15: This formula reveals how attackers track changes in the model’s weights to uncover hidden data. It compares the final and initial values of target outputs (z) across different classes, divided by a stability factor, helping them reconstruct inputs like images or sentences from black-box queries alone!</figcaption></figure><figure><img alt="Black-box Membership Inference &amp; Differential Privacy math" src="https://cdn-images-1.medium.com/max/1024/1*jqbTTFIsN5tRo1mCZVcwiw.png" /><figcaption>Fig.16: Here is an example and a more detailed explanation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*8nblOo5kdYlFKk4fHAhj1A.png" /><figcaption>Fig.17:Empirical privacy for backdoored models for an endto-end attacker, compared to DP-SGD’s provable upper bound. The estimation in orange is a conservative lower bound of the empirical privacy budget, to account for the target gradients not fully concentrating on the backdoor weights.</figcaption></figure><p>If you do not trust the pre-trained models and they are backdoored, even DP-SGD algorithms, which theoretically protect privacy, can practically suffer from severe information leakage.</p><h4>Towards Black-box Data Reconstruction</h4><p>Finally, we consider the challenging problem of black-box data extraction</p><figure><img alt="Black-box Data Reconstruction" src="https://cdn-images-1.medium.com/max/1024/1*XBR0VUDpqwknROXTzAb6rQ.png" /><figcaption>Fig.17: Black-box Data Reconstruction</figcaption></figure><p>This section reveals a smart way to extract data, like the phrase “I love this cake,” using only black-box access to a model. The goal is to recover the backdoor weights step by step. The backdoor unit is defined as a simple equation: the activation h equals the weight vector times the input vector plus a bias term. The method involves querying the model with specific inputs, such as an input vector where the first element is a value c and all others are zero, to find the value of c that activates h. The output behaves like a ReLU function, and with just two queries, the critical point — where c equals the negative bias divided by the first weight — is identified. This process repeats for each coordinate to reconstruct the weights, ultimately revealing the captured input.</p><p>The cost is low — less than 10,000 queries — making it effective even on a backdoored MLP with the CIFAR-10 dataset, as shown in the paper’s results.</p><figure><img alt="Black-box Data Reconstruction math" src="https://cdn-images-1.medium.com/max/1024/1*S-GlkNkDStJuOf7tgBhw4Q.png" /><figcaption>Fig.18: Black-box Data Reconstruction math</figcaption></figure><p>The paper highlights how an attacker can exploit a backdoored model to uncover sensitive data. By using a specific statistic, the attacker can detect the difference between two scenarios — whether a target input is present or absent in the training data. This estimates the privacy leak and shows that differential privacy guarantees might be weak in practice. Additionally, these findings reveal that if a model has a backdoor, an attacker can extract information by observing weight changes, presenting a worst-case scenario for privacy analysis.</p><p><a href="https://drive.google.com/file/d/1TgODFEppmeocsBAOb0AITOXAZ4esABSf/view?usp=sharing">You can see and download the numeric example by clicking this! </a>🤙</p><h3>Conclusion</h3><p>that’s it! It was all things that I can understand from this sophisticated article. And please be careful about using the pre-trained model , maybe you will be the next victim!🫨😁</p><p>sources:</p><ul><li><a href="https://arxiv.org/abs/1607.00133">Deep Learning with Differential Privacy</a></li><li><a href="https://arxiv.org/abs/2404.00473">Privacy Backdoors: Stealing Data with Corrupted Pretrained Models</a></li><li><a href="https://huggingface.co/docs/transformers/en/model_summary">The Transformer model family</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWwbukAcMM4k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWwbukAcMM4k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWwbukAcMM4k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ceba51fe4b0a620ee67e82f4e9d3fa/href">https://medium.com/media/33ceba51fe4b0a620ee67e82f4e9d3fa/href</a></iframe><p><a href="https://medium.com/@reza.shokrzad">Reza Shokrzad - Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc78af9fdf21" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>