<?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 Islam Kassem on Medium]]></title>
        <description><![CDATA[Stories by Islam Kassem on Medium]]></description>
        <link>https://medium.com/@elcaiseri?source=rss-8573d8902876------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2PpbZE93pQkKu8Ri_JLQNg.jpeg</url>
            <title>Stories by Islam Kassem on Medium</title>
            <link>https://medium.com/@elcaiseri?source=rss-8573d8902876------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:12:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elcaiseri/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[OpenFPL Scout AI : What a Full Season of Blind Validation Actually Proved]]></title>
            <link>https://medium.com/data-science-collective/openfpl-scout-ai-what-a-full-season-of-blind-validation-actually-proved-755bb680d146?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/755bb680d146</guid>
            <category><![CDATA[fantasy-premier-league]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 18:25:32 GMT</pubDate>
            <atom:updated>2026-08-31T18:25:32.861Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Third in the OpenFPL series, following </em><a href="https://elcaiseri.medium.com/master-fantasy-premier-league-with-fantasyltx-a-data-driven-approach-to-fpl-success-a1f7527f72af"><em>Master Fantasy Premier League with FantasyLTX</em></a><em> and </em><a href="https://elcaiseri.medium.com/openfpl-scout-ai-data-driven-fantasy-premier-league-success-2882c6266ca9"><em>OpenFPL Scout AI: Data-Driven Fantasy Premier League Success</em></a><em>.</em></p><p>Every Fantasy Premier League model claims it’s good. Almost none of them prove it on a season they’ve never touched.</p><p>I’ve been building OpenFPL Scout AI for a while now — it forecasts FPL points for every player and assembles a legal 15-man squad each gameweek. But this summer I stopped trusting my own training metrics and did the thing that actually matters: I held an entire season back, trained on nothing but the two seasons before it, and scored the result exactly once. Not tuned against it. Not peeked at. One evaluation, 29,747 player-gameweeks the models had never been fitted on.</p><p>Here’s the headline that came out the other side, and I think it’s more useful precisely because it isn’t triumphant: <strong>OpenFPL will not tell you what a player is about to score. It will reliably tell you which players are worth more than others this week — and that ordering was good enough to beat every naive strategy I tested it against, over a full season.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*to0txIEFpDUak3tK" /><figcaption>Photo by <a href="https://unsplash.com/@sonance?utm_source=medium&amp;utm_medium=referral">Viktor Forgacs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why the test had to be this strict</h3><p>Football is a time series. Shuffle your training data randomly and you let a model learn from May to predict September — your accuracy numbers become fiction the moment real fixtures arrive. So the setup was deliberately boring: fit on 2023/24 and 2024/25 only (57,008 rows), then score once against the entirety of 2025/26 (29,747 rows), with estimators that had never seen a single row of the season they were being judged on.</p><p>I’ll admit the one place this isn’t perfectly clean: the hyperparameters were chosen using cross-validation folds, and two of those five folds fall inside the held-out season. That’s a much weaker leak than actually fitting on the data — it amounted to picking from about five candidates per model, on curves that were already shallow — but it means I read the results as mildly optimistic rather than pristine. The current training code closes this gap; the numbers below come from the version that doesn’t, and I’d rather flag that than pretend otherwise.</p><h3>The numbers that mattered</h3><p>Four models — Ridge, XGBoost, CatBoost, and an MLP — trained on the same 38 features and averaged. Against the full held-out season:</p><ul><li><strong>RMSE: 1.92</strong> points per player-gameweek, against a season where actual scores had a standard deviation of 2.35. That’s a real reduction in uncertainty, but a bounded one.</li><li><strong>Rank correlation: 0.70</strong> average Spearman ρ between forecast and outcome, across all 38 gameweeks.</li><li><strong>Squad points per gameweek: 70.6</strong>, versus 56.0 for FPL’s own published expected-points ranking, on identical selection rules. A random legal squad scores 17.6; a squad picked with perfect hindsight scores 170.7. OpenFPL landed at roughly 41% of that theoretical ceiling.</li><li><strong>Gameweeks won: 31 of 38</strong> against a 5-gameweek rolling-form squad, and 32 of 38 against FPL’s own expected-points squad.</li></ul><p>That’s about a 25% points-per-gameweek edge over the best baseline I tested — and it held up across the season rather than coming from a handful of lucky weeks. It also lost sometimes, visibly: three gameweeks fell short of both baselines, and one was a genuinely bad miss, 57 points against 82 for the form squad. Any single week is high variance. The edge shows up over a season, not in any one gameweek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxnNrGYcackxsimzMF8QKQ.png" /></figure><h3>The part I didn’t expect: ensembling barely helped</h3><p>The four models clustered tightly — RMSE between 1.926 and 1.938 — and averaging them bought a further 0.001. CatBoost alone was actually marginally better on mean absolute error than the full ensemble.</p><p>The reason turned out to be visible in the cross-validation curves: all four models moved together across folds. The same fold was hardest for all of them, the same fold was easiest for three of the four. Models that fail in the same places can’t cover for each other, so combining them adds resilience — the service only needs three of four to return a valid prediction — rather than accuracy.</p><p>Where the models did earn their keep was ranking, not point estimates. Grouped into ten deciles by forecast, every decile outscored the one below it — exactly the monotonic property a squad-picker needs — and the curve actually rose <em>above</em>the diagonal at the top end: the highest-forecast decile was predicted at 3.64 points and returned 3.90. The system under-promises on its best picks, which is the safer direction to be wrong in.</p><p>Weekly ranking skill was remarkably flat after the opener: Spearman ρ sat between 0.65 and 0.76 in all 37 remaining gameweeks, averaging 0.72, with no decay across the season and no catastrophic week. Gameweek 1 was the one real exception — ρ collapsed to 0.12, because there’s zero current-season match history to build rolling features from. Production handles that honestly: gameweek 1 skips the models entirely and ranks players by ownership and availability instead, a crowd-following heuristic rather than a forecast.</p><p>Captaincy is where the ranking edge compounds fastest, since the captain’s score counts twice. The ensemble’s captain pick averaged 6.84 points across the season, against 4.53 for FPL’s own expected-points ranking and 4.42 for form — worth roughly 2.3 extra points per gameweek on top of the squad advantage above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hg1qUpq_ovOAidodgwcX6g.png" /></figure><h3>Where it’s still weak</h3><p>I’d rather list these than bury them:</p><ul><li><strong>Individual forecasts carry real error.</strong> RMSE of 1.92 against a standard deviation of 2.35 means roughly a third of the variance in FPL points is explained and two-thirds isn’t. A single goal is worth 4–6 points and arrives close to randomly. Read a 5.2 forecast as an ordering, never as a promise of five points.</li><li><strong>Defenders are the hardest position to call</strong>, RMSE 2.11 against 1.42 for goalkeepers, and the model is systematically conservative about them — predicting 1.01 points on average against an actual mean of 1.24. Clean sheets are binary events it reads cautiously.</li><li><strong>New players have thin history.</strong> Every feature is a five-match rolling mean, so summer signings, promoted-club players, and anyone back from a long injury layoff have little for the model to work with — and player identity itself is a meaningful input. Early-season forecasts for unfamiliar names are the least trustworthy thing this system produces.</li><li><strong>Nothing here models budget, transfers, or chips.</strong> Selection ignores price entirely. The output is a shortlist and a captaincy signal, not a team sheet you can copy onto a £100m budget.</li><li><strong>The training data ends with 2025/26</strong>, and the deployed models are now forecasting a season with zero data of their own — a step beyond even the held-out season, which at least sat adjacent to its training years. The closest measured proxy for this is the hardest cross-validation fold, which was about 0.2 RMSE worse than each model’s easiest fold. Expect the system to be weakest at the start of a new season, and to sharpen as the year’s data accumulates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*pO9qJzvmnYRdsXgF6k8PdQ.png" /></figure><h3>Why publish the misses alongside the wins</h3><p>None of this is a hypothetical caveat section — it’s what the backtest actually measured, run against the same rules a real squad would face. I’d rather a reader trust the 70.6 because they’ve seen the 57-point week too.</p><p>The full report, the training pipeline, every backtest behind these numbers, and the API itself are open source at <a href="https://github.com/elcaiseri/OpenFPL-Scout-AI">github.com/elcaiseri/OpenFPL-Scout-AI</a>. If a number looks off, you can check it yourself — that’s kind of the point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755bb680d146" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/openfpl-scout-ai-what-a-full-season-of-blind-validation-actually-proved-755bb680d146">OpenFPL Scout AI : What a Full Season of Blind Validation Actually Proved</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Large Language Models: A Beginner’s Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://elcaiseri.medium.com/understanding-large-language-models-a-beginners-guide-147a6bf3e4c0?source=rss-8573d8902876------2"><img src="https://cdn-images-1.medium.com/max/2600/0*InTysgq249KWNecI" width="5184"></a></p><p class="medium-feed-snippet">Imagine a machine that can write essays, answer your questions, summarize articles, or even chat with you like a human. This isn&#x2019;t science&#x2026;</p><p class="medium-feed-link"><a href="https://elcaiseri.medium.com/understanding-large-language-models-a-beginners-guide-147a6bf3e4c0?source=rss-8573d8902876------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://elcaiseri.medium.com/understanding-large-language-models-a-beginners-guide-147a6bf3e4c0?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/147a6bf3e4c0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 17:56:01 GMT</pubDate>
            <atom:updated>2026-02-25T17:56:01.141Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[OpenFPL-Scout-AI: Data-Driven Fantasy Premier League Success]]></title>
            <link>https://elcaiseri.medium.com/openfpl-scout-ai-data-driven-fantasy-premier-league-success-2882c6266ca9?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/2882c6266ca9</guid>
            <category><![CDATA[fantasy-premier-league]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 05:02:01 GMT</pubDate>
            <atom:updated>2025-08-11T05:02:01.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1Sf4y6-5zI4425f" /><figcaption>Photo by <a href="https://unsplash.com/@bullterriere?utm_source=medium&amp;utm_medium=referral">Simon Hurry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Fantasy Premier League (FPL) is a game of decisions. Each week, millions of managers face the same challenge: how to pick the best team, captain, and transfers with limited information and endless uncertainty. After years of relying on gut instinct and generic prediction tools, I set out to build something different — a transparent, data-driven solution that leverages machine learning and modern web technologies to give FPL managers a genuine edge.</p><blockquote><em>Whether you’re a developer or simply passionate about Fantasy Premier League, you can explore</em></blockquote><p><a href="https://github.com/elcaiseri/OpenFPL-Scout-AI">GitHub - elcaiseri/OpenFPL-Scout-AI: AI-powered FPL Scout using historical and live data with ML models (Linear Regression, XGBoost, CatBoost) to predict player performance and optimize team selection.</a></p><blockquote><em>Developers can dive straight into the full code and run it locally, while FPL enthusiasts can use the tool’s predictions and insights without touching a single line of code. Live demo at the end.</em></blockquote><h3>The Limitations of Traditional FPL Tools</h3><p>Most FPL tools offer basic projections or static spreadsheets. They rarely adapt to new data, and their predictions often lack transparency. I wanted to create a platform that not only predicts player points with accuracy but also explains its reasoning and presents results in an intuitive, actionable way.</p><h3>The OpenFPL-Scout-AI Approach</h3><p>OpenFPL-Scout-AI is built on three core principles:</p><ul><li><strong>Data-Driven Decision Making:</strong> Every prediction is grounded in real, up-to-date data and rigorous feature engineering.</li><li><strong>Ensemble Machine Learning:</strong> By combining multiple models, we capture a wider range of patterns and interactions.</li><li><strong>User-Centric Design:</strong> Insights are delivered through a clean, interactive web interface that makes complex data easy to understand.</li></ul><h3>Data Loading and Preparation</h3><p>The foundation of any predictive system is quality data. OpenFPL-Scout-AI loads and processes a comprehensive dataset of over 27,000 player-game records, ensuring both breadth and depth. The data pipeline identifies and separates categorical features (such as player names, team names, opponent teams, and home/away status) from numerical features (including minutes played, goals, assists, expected goals, defensive actions, and more).</p><h3>Feature Engineering</h3><p>Feature selection is critical. OpenFPL-Scout-AI uses a curated set of features that capture both attacking and defensive contributions, as well as contextual factors like opponent strength and home advantage. This includes advanced stats such as expected goals (xG), expected assists (xA), and defensive metrics like tackles and recoveries.</p><h3>Ensemble Machine Learning</h3><p>Rather than relying on a single model, OpenFPL-Scout-AI employs an ensemble of three complementary algorithms:</p><ul><li><strong>Linear Regression:</strong> Provides a strong baseline and captures linear relationships.</li><li><strong>XGBoost:</strong> Excels at modeling complex, non-linear interactions.</li><li><strong>CatBoost:</strong> Handles categorical variables natively and efficiently.</li></ul><p>Each model is tuned with cross-validation to find the best hyperparameters. For example:</p><pre>Linear Regression: fit_intercept=False, positive=True<br>XGBoost: learning_rate=0.1, max_depth=6, n_estimators=200, subsample=0.8<br>CatBoost: depth=6, iterations=200, learning_rate=0.2</pre><h3>Feature Importance and Transparency</h3><p>Understanding which features drive predictions is essential for trust and improvement. The models consistently highlight the importance of defensive actions (tackles, recoveries), attacking output (shots on target, goals), and contextual factors (home/away, opponent team).</p><p><strong>Top features across models:</strong></p><ul><li>Shots on Target (SoT)</li><li>Opponent team name</li><li>Selected by percent (ownership)</li></ul><p>This transparency allows users to see not just what the model predicts, but why.</p><h3>Backend and Web Interface</h3><p>The backend is built with FastAPI, supporting asynchronous processing and smart caching to deliver rapid predictions. Users can upload their FPL CSV, and the system processes and returns predictions in seconds.</p><p>The frontend visualizes your optimal team on a virtual pitch, complete with kit colors, player positions, and captain/vice-captain indicators. The design is mobile-responsive and supports one-click screenshot export for easy sharing.</p><h3>Data-Driven, Open, and Extensible</h3><p>OpenFPL-Scout-AI is open source and designed for customization. Users can adjust model weights, add new features (such as injury tracking), or integrate additional data sources. The focus on data quality and transparency makes it easy for the community to contribute and improve the system.</p><h3>Lessons Learned</h3><ul><li><strong>Data quality is paramount:</strong> The best models are only as good as the data they use. Most of the development time was spent on cleaning and engineering features.</li><li><strong>User experience matters:</strong> Early versions were command-line only and saw little use. The web interface transformed engagement.</li><li><strong>Caching is essential:</strong> Efficient caching ensures that predictions are delivered instantly, even with large datasets.</li></ul><h3>Looking Ahead</h3><p>Future plans include integrating injury and suspension data, optimizing transfer strategies, and adding community features for sharing and comparing teams. The goal is to keep pushing the boundaries of what data-driven FPL management can achieve.</p><blockquote><strong><em>Finally, here’s the Live Demo</em></strong><em> so you can explore predictions in real time:</em></blockquote><p><a href="https://openfpl-scout-ai-186049008266.europe-west1.run.app/">OpenFPL Scout AI Team - Fantasy Premier League AI Recommendations</a></p><h3>Conclusion</h3><p>OpenFPL-Scout-AI is not about guaranteeing perfect results — football remains unpredictable. But by combining rigorous data analysis, ensemble machine learning, and user-friendly design, it empowers FPL managers to make smarter, more confident decisions.</p><p>The code is open, the predictions are live, and the next breakthrough in your FPL season could be just one upload away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2882c6266ca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPT-2 Works: Building a Transformer Language Model From Scratch in PyTorch]]></title>
            <link>https://elcaiseri.medium.com/how-gpt-2-works-building-a-transformer-language-model-from-scratch-in-pytorch-b4abc4a7a7b7?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4abc4a7a7b7</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 18:20:30 GMT</pubDate>
            <atom:updated>2025-04-12T18:20:30.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYko0ndIMzZ25zzc" /><figcaption>Photo by <a href="https://unsplash.com/@davideragusa?utm_source=medium&amp;utm_medium=referral">davide ragusa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Large language models like <strong>GPT-2</strong> might seem intimidating at first glance — but under the hood, they’re beautifully simple.</p><p>In this post, we’ll break down <strong>GPT-2 architecture</strong> and rebuild it <strong>from scratch</strong> using <strong>PyTorch</strong>.</p><p>If you love understanding models deeply and getting your hands dirty with code, this is for you.</p><p>The full code is available here:</p><p><a href="https://github.com/elcaiseri/gpt2-from-scratch">GitHub - elcaiseri/gpt2-from-scratch: gpt2-from-scratch using torch</a></p><h3>📚 1. Understanding GPT-2 Architecture</h3><p>At a high level, <strong>GPT-2</strong> is just a <strong>stack of transformer decoder blocks</strong>.</p><p>Here’s the architecture step-by-step:</p><ol><li><strong>Token Embedding:</strong> Turn input tokens into continuous vectors.</li><li><strong>Positional Embedding:</strong> Inject information about token order.</li><li><strong>Transformer Blocks:</strong></li></ol><ul><li><strong>Self-Attention:</strong> Each token attends to previous tokens (causal masking).</li><li><strong>Feed Forward Network (MLP):</strong> Processes each token independently after attention.</li><li><strong>Layer Normalization + Residual Connections:</strong> Stabilize and accelerate training.</li></ul><ol><li><strong>Language Modeling Head:</strong></li></ol><ul><li>Project transformer outputs back to vocabulary size to predict next token.</li></ul><p><strong>Full Pipeline Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArUaT6tV0ZSLXANFsSG57Q.png" /><figcaption><a href="https://www.ericjwang.com/assets/images/gpt_arch.png">https://www.ericjwang.com/assets/images/gpt_arch.png</a></figcaption></figure><p>The key ideas:</p><ul><li><strong>Left-to-right generation:</strong> Tokens can only attend to the past.</li><li><strong>Stacked blocks:</strong> More blocks = more reasoning power.</li><li><strong>Shared architecture:</strong> GPT-2 reuses the same structure over and over.</li></ul><h3>🧱 2. Building GPT-2 From Scratch (Class-by-Class)</h3><p>Now, let’s build it <strong>bottom-up</strong>, starting from the simplest building block.</p><h3>🔹 GPT2Attention: The Self-Attention Layer</h3><p>This layer allows each token to look at previous tokens.</p><pre>class GPT2Attention(nn.Module):<br>    def forward(self, x):<br>        x = self.c_attn(x)  # Linear projection to Q, K, V<br>        q, k, v = x.split(self.split_size, dim=-1)<br>        q, k, v = map(self._split_heads, (q, k, v))<br><br>        attn_output = self._attn(q, k, v)  # Scaled dot-product attention<br>        attn_output = self._merge_heads(attn_output)<br><br>        attn_output = self.c_proj(attn_output)  # Project back<br>        return self.resid_dropout(attn_output)</pre><p>🛡️ <strong>Masked Attention:</strong> We apply a lower triangular mask so a token can’t attend to future tokens.</p><h3>🔹 GPT2MLP: The Feed-Forward Network</h3><p>After attention, each token passes through a small neural network independently.</p><pre>class GPT2MLP(nn.Module):<br>    def forward(self, x):<br>        x = self.c_fc(x)<br>        x = self.act(x)    # GELU activation<br>        x = self.dropout(x)<br>        x = self.c_proj(x)<br>        return x</pre><h3>🔹 GPT2Block: The Transformer Block</h3><p>Each block combines <strong>attention</strong> and <strong>MLP</strong>, with <strong>residual connections</strong> and <strong>layer normalization</strong>.</p><pre>class GPT2Block(nn.Module):<br>    def forward(self, x):<br>        x = x + self.attn(self.ln_1(x))<br>        x = x + self.mlp(self.ln_2(x))<br>        return x</pre><ul><li><strong>First:</strong> Normalize → Self-Attention → Add skip connection</li><li><strong>Then:</strong> Normalize → MLP → Add skip connection</li></ul><p>These residuals are crucial for training very deep networks.</p><h3>🔹 GPT2Model: The Transformer Encoder</h3><p>Now we stack many GPT2Block layers.</p><pre>class GPT2Model(nn.Module):<br>    def forward(self, input_ids, position_ids=None):<br>        input_embeds = self.wte(input_ids) + self.wpe(position_ids)<br>        x = self.drop(input_embeds)<br><br>        for block in self.h:<br>            x = block(x)<br><br>        x = self.ln_f(x)<br>        return x</pre><ul><li>wte: Word token embeddings</li><li>wpe: Positional embeddings</li><li>h: List of transformer blocks</li></ul><h3>🔹 GPT2LMHeadModel: The Final Language Model</h3><p>Finally, we add a <strong>linear head</strong> on top to predict next tokens.</p><pre>class GPT2LMHeadModel(nn.Module):<br>    def forward(self, input_ids, position_ids=None):<br>        hidden_states = self.transformer(input_ids, position_ids)<br>        logits = self.lm_head(hidden_states)<br>        return logits</pre><p>It also includes a generate method to produce text:</p><pre>@torch.no_grad()<br>def generate(self, input_ids, max_length=50, temperature=0.7, do_sample=False):<br>    ...</pre><h3>🚀 3. Example Usage</h3><p>Here’s how you can create the model and use it for inference:</p><pre>model = GPT2LMHeadModel(vocab_size=50257, n_ctx=1024, n_embd=768, n_layer=12, n_head=12)<br>input_ids = torch.randint(0, 50257, (1, 5))  # Random tokens<br>logits = model(input_ids)<br>print(logits.shape)  # (batch_size, sequence_length, vocab_size)</pre><p>To generate text:</p><pre>output = model.generate(input_ids, max_length=20, temperature=0.8, do_sample=True)<br>print(output)</pre><h3>📚 Conclusion</h3><p>Building GPT-2 from scratch might sound intimidating, but once you break it down into blocks, it’s very manageable.</p><p>You’ll get a much deeper understanding of <strong>attention</strong>, <strong>transformers</strong>, and <strong>language modeling</strong>.</p><p>👉 Full project: <a href="https://github.com/elcaiseri/gpt2-from-scratch">GitHub — elcaiseri/gpt2-from-scratch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4abc4a7a7b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an ML-Powered Survey Analysis System with RAG: A Deep Dive]]></title>
            <link>https://elcaiseri.medium.com/building-an-ml-powered-survey-analysis-system-with-rag-a-deep-dive-b6797d5a8ff2?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6797d5a8ff2</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 23:54:20 GMT</pubDate>
            <atom:updated>2024-10-18T23:54:20.128Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building an ML-Powered Survey Analysis System with RAG: A Deep Dive — Part 1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-xcF2Vi6mr1bC2m7" /><figcaption>Photo by <a href="https://unsplash.com/@kimonmaritz?utm_source=medium&amp;utm_medium=referral">Kimon Maritz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The <strong>Survey Analysis RAG System</strong> offers an innovative way to analyze survey data by combining <strong>Retrieval-Augmented Generation (RAG)</strong> with OpenAI’s language models. This article explores the <strong>ML </strong>system, breaking down the use of machine learning and data retrieval techniques that bring survey insights to life.</p><p>If you’re interested in the complete source code and want to dive deeper into the <strong>Survey Analysis RAG System</strong>, visit the <strong>GitHub repository</strong> linked below.</p><p><a href="https://github.com/elcaiseri/Survey-Analysis-RAG-System">GitHub - elcaiseri/Survey-Analysis-RAG-System: A web application using Retrieval-Augmented Generation (RAG) to analyze and compare survey datasets. Built with FastAPI, Nginx, and OpenAI&#39;s models. Fully containerized with Docker for easy deployment.</a></p><p>It includes:</p><ul><li><strong>Detailed ML backend modules</strong> such as document loaders, vector store, prompt templates, and the QA pipeline.</li><li><strong>Setup instructions</strong> for deploying with <strong>Docker</strong> and <strong>FastAPI</strong>.</li><li>Sample datasets and configuration examples to get you started quickly.</li></ul><p><strong>What Is RAG and Why It Matters?</strong></p><p>Retrieval-Augmented Generation (RAG) enhances <strong>LLMs</strong> by combining <strong>retrieval techniques</strong> with generative models. Instead of relying on a model’s limited internal knowledge, it retrieves relevant documents to generate more accurate, context-aware responses. This is especially valuable for survey analysis, where precise context drives meaningful insights.</p><p><strong>1. Document Handling: Loading and Splitting Excel Files</strong></p><p>Survey data is stored in Excel files and loaded by the DocumentLoader.</p><ul><li>UnstructuredExcelLoader splits Excel files into smaller, manageable chunks.</li><li>Each document is tagged with a <strong>dataset ID</strong> (extracted from the filename) for easy filtering.</li><li><strong>Logging</strong> ensures that every file processed is tracked for transparency.</li></ul><pre>from langchain_community.document_loaders import UnstructuredExcelLoader<br><br>class DocumentLoader:<br>    def __init__(self, file_paths):<br>        self.file_paths = file_paths<br><br>    def load_documents(self):<br>        docs = [UnstructuredExcelLoader(fp).load_and_split() for fp in self.file_paths]<br>        for doc in docs:<br>            doc.metadata[&#39;dataset_id&#39;] = fp.split(&quot;/&quot;)[-1].split(&quot;_&quot;)[0]<br>        return sum(docs, [])</pre><p>This layer prepares data for the next phase, ensuring the RAG system has access to clean, well-organized survey information.</p><p><strong>2. Embeddings and Vector Store: Building the Retrieval Layer</strong></p><p>The heart of fast information retrieval lies in <strong>FAISS (Facebook AI Similarity Search)</strong>. The VectorStore class uses FAISS to build a vectorized representation of the documents.</p><ul><li><strong>OpenAI embeddings</strong> transform documents into high-dimensional vectors using the text-embedding-3-large model.</li><li>FAISS indexes these vectors to perform rapid similarity-based searches, enabling the system to find relevant content with ease.</li></ul><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import FAISS<br><br>class VectorStore:<br>    def __init__(self, documents, embedding_model):<br>        self.vectorstore = FAISS.from_documents(documents, OpenAIEmbeddings(embedding_model))</pre><p>This vector store powers the <strong>retriever</strong>, which fetches relevant documents in response to user queries.</p><p><strong>3. Prompt Engineering: Defining the Query Structure</strong></p><p>The PromptTemplateFactory defines how queries interact with the model. A well-structured prompt guides the language model to generate precise answers.</p><ul><li>The prompt template ensures the assistant is <strong>specialized in survey data analysis</strong>, instructing it to use retrieved context to generate answers.</li><li>Responses are limited to <strong>three sentences</strong>, keeping them concise and actionable.</li><li>If the answer is unknown, the model is prompted to respond accordingly.</li></ul><pre>from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate<br><br>class PromptTemplateFactory:<br>    @staticmethod<br>    def create_prompt_template():<br>        return ChatPromptTemplate(<br>            input_variables=[&#39;context&#39;, &#39;question&#39;],<br>            messages=[<br>                HumanMessagePromptTemplate(<br>                    prompt=(<br>                        &quot;Use the following context to answer the question.&quot;<br>                        &quot;If unsure, respond with &#39;I don&#39;t know&#39;.\n&quot;<br>                        &quot;Question: {question}\nContext: {context}\nAnswer:&quot;<br>                    )<br>                )<br>            ]<br>        )</pre><p>This structure ensures that the generated insights are concise, relevant, and easy to interpret.</p><p><strong>4. LLM and QA Chain: The End-to-End Query Process</strong></p><p>The SurveyAnalysisRAGSystem integrates all components into a seamless QA pipeline. Here’s how it works:</p><ol><li><strong>Loading Documents:</strong> The system loads Excel files into the vector store.</li><li><strong>Retrieving Data:</strong> Using <strong>Maximal Marginal Relevance (MMR)</strong>, it retrieves relevant documents based on the query.</li><li><strong>Formatting Context:</strong> Retrieved documents are formatted and passed through the QA chain.</li><li><strong>Generating Answers:</strong> The prompt interacts with the <strong>GPT-4o-mini</strong> model to generate answers.</li><li><strong>Performance Tracking:</strong> Time taken to generate responses is logged for monitoring efficiency.</li></ol><pre>from langchain_openai import ChatOpenAI<br><br>class SurveyAnalysisRAGSystem:<br>    def __init__(self, file_path, embedding_model=&quot;text-embedding-3-large&quot;, llm_model=&quot;gpt-4o-mini&quot;):<br>        self.vectorstore = VectorStore(DocumentLoader(file_path).load_documents(), embedding_model).vectorstore<br>        self.llm = ChatOpenAI(model=llm_model)<br><br>    def generate_answer(self, query, dataset_id, k=16):<br>        retriever = self.vectorstore.as_retriever(search_type=&quot;mmr&quot;, search_kwargs={&#39;k&#39;: k})<br>        context = &quot;\n\n&quot;.join([doc.page_content for doc in retriever.retrieve(query)])<br>        prompt = PromptTemplateFactory.create_prompt_template()<br>        return self.llm.invoke({&quot;context&quot;: context, &quot;question&quot;: query})</pre><p><strong>How Everything Comes Together</strong></p><p>At a high level, the system acts as a <strong>specialized survey assistant</strong>. Users input questions, and the system:</p><ul><li>Retrieves relevant survey data from indexed documents.</li><li>Generates natural language insights using OpenAI’s LLM.</li><li>Delivers concise, context-aware responses that make survey analysis easier and faster.</li></ul><p><strong>Conclusion: A Scalable Solution for Survey Analysis</strong></p><p>The ML design of the <strong>Survey Analysis RAG System</strong> showcases how <strong>RAG</strong> can unlock insights from complex datasets. With <strong>FAISS-powered retrieval</strong>, <strong>OpenAI embeddings</strong>, and <strong>prompt engineering</strong>, the system ensures high-quality responses to user queries. By deploying this ML backend with <strong>FastAPI</strong> and <strong>Docker</strong>, it becomes a scalable, efficient tool for organizations looking to make data-driven decisions from survey results.</p><p><strong>Next Steps: Part 2 — Deployment Details</strong></p><p>Stay tuned for <strong>Part 2</strong>, where we’ll cover step-by-step deployment details to get the system running locally or in the cloud. Explore the complete codebase on <a href="https://github.com/elcaiseri/Survey-Analysis-RAG-System">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6797d5a8ff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Fantasy Premier League with FantasyLTX: A Data-Driven Approach to FPL Success]]></title>
            <link>https://elcaiseri.medium.com/master-fantasy-premier-league-with-fantasyltx-a-data-driven-approach-to-fpl-success-a1f7527f72af?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f7527f72af</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fpl]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[fantasy-premier-league]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 13:36:53 GMT</pubDate>
            <atom:updated>2024-09-13T13:36:53.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fMJ0mQCNAY4pMTM" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=medium&amp;utm_medium=referral">Daria Nepriakhina 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As an FPL addict, I developed Fantasy-Premier-League-LTX (FPLLTX) to gain an edge over rivals using machine learning models like Linear Regression and XGBoost. FPLLTX leverages historical data and match stats to optimize team selections, predict player performances, and make data-driven decisions that transform your FPL strategy from guesswork into precision.</p><p><strong>Follow Along on X.com: Weekly ML-Based FPL Insights</strong></p><p>I’m constantly sharing updates on X.com about how FPLLTX is transforming my FPL strategy. I post weekly team picks, captains, and performance analyses to showcase the power of data-driven decisions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/elcaiseri/status/1834575016203063500&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/572bb862483855bdfc450adf147b9df9/href">https://medium.com/media/572bb862483855bdfc450adf147b9df9/href</a></iframe><p>You can follow my journey and get insights on how to use FPLLTX to boost your own FPL game <a href="https://x.com/elcaiseri/status/1834575016203063500">here</a>.</p><p><strong>Introducing FPLLTX: My Machine Learning Tool for FPL</strong></p><p>I built FPLLTX to bring the power of data analytics to FPL. By leveraging historical player data and match stats, FPLLTX helps you optimize team selections, choose captains, and even select the perfect squad within your budget. The tool’s predictive capabilities ensure that each decision is backed by solid data rather than guesswork.</p><p><strong>Getting Started with FPLLTX</strong></p><p>FPLLTX is designed to be easy to set up and use. Simply clone the repository from GitHub, set up your Python environment, and configure the tool according to your preferences. The project includes all the scripts you need for data preparation, feature engineering, and predictive analysis. Commands like python main.py — run_top_players allow you to identify the best players for upcoming gameweeks, while python main.py — run_best_team helps you build the most optimized squad.</p><p><strong>How FPLLTX Optimizes Your Team</strong></p><p>FPLLTX doesn’t just predict top players — it goes further by analyzing fixtures, player form, and budget constraints to recommend the ideal squad. For instance, instead of making decisions based on popular opinion, FPLLTX evaluates players on expected goals, assists, and other advanced metrics, giving you a comprehensive view of potential outcomes. This approach transforms every decision from a gamble into a calculated move.</p><p><strong>The Results: Rising Through the Ranks</strong></p><p>Since incorporating FPLLTX into my strategy, I’ve seen a significant improvement in my rankings and consistency. The tool has empowered me to make smarter decisions, outperforming managers who rely purely on intuition. It doesn’t just validate my football instincts — it enhances them with data, turning my passion into a competitive advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8qFHOMdL3AfDcKZy.png" /><figcaption>Best Team For GW4–2025</figcaption></figure><p>The best part? FPLLTX is for everyone. Whether you’re a seasoned manager or just starting, it elevates your FPL game by blending football knowledge with machine learning insights.</p><p><strong>Take Your FPL Game to the Next Level</strong></p><p>Ready to take your FPL strategy to the next level? Explore FPLLTX on <a href="https://github.com/elcaiseri/Fantasy-Premier-League-LTX">GitHub</a> and start leveraging data to dominate your leagues. This tool is more than a predictor — it’s your new secret weapon in the quest for FPL glory. From optimizing your squad to making gameweek-specific adjustments, FPLLTX helps you transform from a casual player into a strategic manager.</p><p>With FPLLTX, every decision becomes an opportunity to gain an edge. Embrace the future of fantasy football and watch as your team climbs the rankings week after week. GLORY!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f7527f72af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a K-Nearest Neighbors (KNN) Classifier from Scratch: A Comprehensive Guide]]></title>
            <link>https://elcaiseri.medium.com/building-a-k-nearest-neighbors-knn-classifier-from-scratch-a-comprehensive-guide-dd756f17a50b?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd756f17a50b</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 13:27:27 GMT</pubDate>
            <atom:updated>2024-08-27T13:27:27.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J2c_x6OBqsB8V8JW" /><figcaption>Photo by <a href="https://unsplash.com/@dburka?utm_source=medium&amp;utm_medium=referral">Daniel Burka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The K-Nearest Neighbors (KNN) algorithm is one of the most straightforward and intuitive methods in the world of machine learning. Despite its simplicity, KNN is remarkably effective for a variety of tasks, including classification, regression, and even recommendation systems. In this story, we’ll dive deep into how you can implement a KNN classifier from scratch using Python, giving you a clear understanding of how this algorithm works under the hood.</p><p>For more details and the full implementation, check out the <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch">Machine-Learning-from-Scratch repository</a>.</p><p><a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch">GitHub - elcaiseri/Machine-Learning-from-Scratch: Machine Learning using NumPy</a></p><p><strong>What is K-Nearest Neighbors (KNN)?</strong></p><p>K-Nearest Neighbors is a non-parametric, lazy learning algorithm that classifies data points based on the majority class among its nearest neighbors. The “K” in KNN represents the number of neighbors considered in the classification. The algorithm is called “lazy” because it doesn’t learn a discriminative function from the training data but rather memorizes the training dataset and performs classification during inference.</p><p>KNN can be used for both classification and regression tasks, making it a versatile tool in a data scientist’s arsenal.</p><p><strong>How Does KNN Work?</strong></p><p>The KNN algorithm works in three primary steps:</p><ol><li><strong>Calculate Distance</strong>: For each point in the test data, calculate the distance (usually Euclidean) between the test point and all training points.</li><li><strong>Identify Neighbors</strong>: Select the “K” nearest neighbors based on the calculated distances.</li><li><strong>Vote for Labels</strong>: The test point is classified based on the majority vote from its nearest neighbors.</li></ol><p><strong>Implementing KNN from Scratch</strong></p><p>The <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch/blob/main/knn.py">GitHub repository</a> contains a clean and well-documented implementation of the KNN algorithm. Let’s walk through the key steps involved in building this model.</p><p><strong>1. Data Preparation</strong></p><p>Before applying the KNN algorithm, data must be prepared and normalized. Normalization ensures that each feature contributes equally to the distance calculations.</p><p><strong>2. Calculating Distances</strong></p><p>The most commonly used distance metric in KNN is the Euclidean distance. This metric calculates the straight-line distance between two points in a multi-dimensional space.</p><pre>import numpy as np<br><br>def euclidean_distance(x1, x2):<br>    return np.sqrt(np.sum((x1 - x2) ** 2))</pre><p><strong>3. Predicting the Class of a New Data Point</strong></p><p>For each new data point, the algorithm calculates the distance to all training data points, identifies the nearest neighbors, and assigns the class based on the majority vote.</p><pre>from collections import Counter<br><br>def _predict(self, x):<br>    # Compute distances between x and all examples in the training set<br>    distances = [euclidean_distance(x, x_train) for x_train in self.X_train]<br>    # Sort by distance and return the labels of the first k neighbors<br>    k_indices = np.argsort(distances)[:self.k]<br>    k_nearest_labels = [self.y_train[i] for i in k_indices]<br>    # Return the most common class label<br>    most_common = Counter(k_nearest_labels).most_common(1)<br>    return most_common[0][0]</pre><p><strong>4. Evaluating the Model</strong></p><p>Once the KNN model is built, it’s essential to evaluate its performance on a test dataset. This involves comparing the predicted labels with the actual labels to calculate accuracy.</p><p><strong>Advantages of KNN</strong></p><ul><li><strong>Simplicity</strong>: Easy to implement and understand.</li><li><strong>No Training Phase</strong>: The model is trained in real-time as new data points are introduced.</li><li><strong>Versatility</strong>: Can be used for classification, regression, and recommendation tasks.</li></ul><p><strong>Applications</strong></p><p>KNN is widely used in:</p><ul><li><strong>Image recognition</strong>: Identifying objects in images based on similarity.</li><li><strong>Recommendation systems</strong>: Suggesting items to users based on similar preferences.</li><li><strong>Medical diagnosis</strong>: Classifying diseases based on patient data.</li></ul><p><strong>Conclusion</strong></p><p>Building a KNN classifier from scratch is a rewarding exercise that deepens your understanding of one of the most fundamental algorithms in machine learning. By implementing it yourself, you not only learn the theory behind KNN but also gain the practical skills to apply it to real-world datasets.</p><p>For a detailed look at the implementation, check out the full code in the <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch/blob/main/knn.py">GitHub repository</a>. Whether you’re new to machine learning or looking to revisit the basics, this project provides a solid foundation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd756f17a50b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Naive Bayes Classifier from Scratch: A Step-by-Step Guide]]></title>
            <link>https://elcaiseri.medium.com/building-a-naive-bayes-classifier-from-scratch-a-step-by-step-guide-557638e2d878?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/557638e2d878</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[probabilistic-models]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 13:11:42 GMT</pubDate>
            <atom:updated>2024-08-26T13:11:42.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t95xAWGXJA85zfMY" /><figcaption>Photo by <a href="https://unsplash.com/@eduardmilitaru?utm_source=medium&amp;utm_medium=referral">eduard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of machine learning, understanding the fundamental algorithms is crucial for building a solid foundation. One such algorithm that stands out for its simplicity and effectiveness is the <strong>Naive Bayes classifier</strong>. Often used for text classification, spam filtering, and sentiment analysis, this algorithm is a powerful tool in a data scientist’s toolkit.</p><p>In this story, we’ll dive into how you can build a Naive Bayes classifier from scratch using Python. This hands-on approach not only solidifies your understanding of the algorithm but also gives you the flexibility to customize and experiment with the model.</p><p>For more details and the full implementation, check out the <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch">Machine-Learning-from-Scratch repository</a>.</p><p><a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch">GitHub - elcaiseri/Machine-Learning-from-Scratch: Machine Learning using NumPy</a></p><p><strong>What is Naive Bayes?</strong></p><p>The Naive Bayes classifier is a probabilistic machine learning algorithm based on Bayes’ Theorem. It assumes that the presence of a particular feature in a class is independent of the presence of any other feature. Despite this “naive” assumption, it performs surprisingly well in many real-world scenarios, especially in text classification tasks.</p><p><strong>Bayes’ Theorem</strong> can be mathematically expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*LhU9_IGQ1ZrKmehK.png" /></figure><p>Where:</p><ul><li>P(C|X) is the probability of class C given the feature X (posterior probability).</li><li>P(X|C) is the probability of feature X given class C (likelihood).</li><li>P(C) is the probability of class C (prior probability).</li><li>P(X) is the probability of feature X (evidence).</li></ul><p><strong>Implementing Naive Bayes from Scratch</strong></p><p>The <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch/blob/main/naiveBayes.py">GitHub repository</a> contains a clean and well-documented implementation of the Naive Bayes classifier. Let’s walk through the key steps involved in building this model.</p><p><strong>1. Data Preparation</strong></p><p>Before feeding data into the Naive Bayes classifier, we need to preprocess it. This typically involves converting text into numerical features, such as word frequencies or TF-IDF scores, if we’re working with text data.</p><p><strong>2. Model Initialization and Fitting</strong></p><p>The first step in implementing the Naive Bayes classifier is initializing the model and fitting it to the data.</p><pre>class NaiveBayes:<br>    def __init__(self) -&gt; None:<br>        self.classes = None<br>    <br>    def fit(self, X, y):<br>        n_samples, featuers = X.shape  # (samples, features)<br>        self.classes = np.unique(y)<br>        n_classes = len(self.classes)<br>        self.mean = np.zeros((n_classes, featuers))<br>        self.var = np.zeros((n_classes, featuers))<br>        self.Py = np.zeros(n_classes)<br>        <br>        for idx, c in enumerate(self.classes):<br>            y_mask = (y == c)<br>            X_ = X[y_mask, :]<br>            <br>            self.mean[c, :] = X_.mean(axis=0)  # (classes, featuers)<br>            self.var[c, :] = X_.var(axis=0)  # (classes, featuers)<br>            self.Py[c] = X_.shape[0] / n_samples</pre><p><strong>3. Calculating Probabilities</strong></p><p>The core of the Naive Bayes algorithm is calculating the prior and likelihood probabilities for each class. These probabilities are used to predict the class of new, unseen data points.</p><pre>def _pdf(self, x, mean, var):<br>    c1 = np.sqrt(2 * np.pi * var)<br>    c2 = np.exp( -(x - mean) ** 2 / (2 * var))<br>    return np.log(c2 / c1)</pre><p>In the implementation, we calculate:</p><ul><li>Prior probability: P(C)</li><li>Likelihood probability: P(X|C)</li></ul><p><strong>4. Making Predictions</strong></p><p>For a given set of features, the classifier computes the posterior probability for each class and assigns the class with the highest probability to the data point.</p><pre>def predict(self, X):     <br>    Pyx = []<br>    for c in self.classes:<br>        pyx = np.sum(self._pdf(X, self.mean[c, :], self.var[c, :]), axis=1) + np.log(self.Py[c])<br>        Pyx.append(pyx)<br>    return np.argmax(Pyx, 0)</pre><p>This simple yet powerful approach allows the Naive Bayes classifier to make quick and accurate predictions.</p><p><strong>Advantages of Naive Bayes</strong></p><ul><li><strong>Simplicity</strong>: Easy to implement and computationally efficient.</li><li><strong>Speed</strong>: Works well with large datasets and is particularly fast in making predictions.</li><li><strong>Versatility</strong>: Can be used for both binary and multi-class classification problems.</li></ul><p><strong>Applications</strong></p><p>Naive Bayes is widely used in:</p><ul><li><strong>Spam filtering</strong>: Classifying emails as spam or not spam.</li><li><strong>Sentiment analysis</strong>: Determining whether a piece of text expresses positive or negative sentiment.</li><li><strong>Document classification</strong>: Categorizing documents into different topics.</li></ul><p><strong>Conclusion</strong></p><p>Building a Naive Bayes classifier from scratch is an excellent exercise for understanding the mechanics of one of the foundational algorithms in machine learning. By diving into the code and implementing it yourself, you gain deeper insights into how probabilistic models work and how they can be applied to solve real-world problems.</p><p>For a detailed look at the implementation, check out the full code in the <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch/blob/main/naiveBayes.py">GitHub repository</a>. Whether you’re a beginner in machine learning or looking to strengthen your understanding of core algorithms, this project provides a hands-on learning experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557638e2d878" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Similarity Estimation Using a Siamese Network with Triplet Loss: A Practical Guide]]></title>
            <link>https://elcaiseri.medium.com/image-similarity-estimation-using-a-siamese-network-with-triplet-loss-a-practical-guide-124938e24b3a?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/124938e24b3a</guid>
            <category><![CDATA[image-similarity]]></category>
            <category><![CDATA[triplet-loss]]></category>
            <category><![CDATA[siamese-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 23:30:45 GMT</pubDate>
            <atom:updated>2024-08-24T23:30:45.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ru2VlbRg-LEaC--O" /><figcaption>Photo by <a href="https://unsplash.com/@usgs?utm_source=medium&amp;utm_medium=referral">USGS</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the realm of machine learning, one of the fascinating challenges is determining the similarity between images. This task is pivotal in various applications, from detecting duplicates to facial recognition. A robust approach to this problem is using a <strong>Siamese Network</strong> combined with a <strong>Triplet Loss</strong> function.</p><p>In this article, we’ll explore how to build and train a Siamese Network to estimate image similarity using a practical example from a <a href="https://github.com/elcaiseri/Siamese-Network">GitHub repository</a></p><p><a href="https://github.com/elcaiseri/Siamese-Network">GitHub - elcaiseri/Siamese-Network: Image similarity estimation using a Siamese Network with a triplet loss</a></p><p><strong>Introduction to Siamese Networks</strong></p><p>A <strong>Siamese Network</strong> is a type of neural network architecture that contains two or more identical subnetworks. These subnetworks are designed to generate feature vectors for each input, which can then be compared to estimate similarity. The key idea is that the same network is used to process each input, ensuring consistent and comparable outputs.</p><p>This architecture is especially useful for tasks like detecting duplicates, finding anomalies, and facial recognition. In the implementation we’ll explore, the network is set up with three identical subnetworks. Each network processes one of three images: an anchor image, a positive sample (similar to the anchor), and a negative sample (unrelated to the anchor).</p><p><strong>The Power of Triplet Loss</strong></p><p>To train the Siamese Network effectively, we use a <strong>Triplet Loss</strong> function. This loss function encourages the network to bring the anchor and positive samples closer in the feature space while pushing the anchor and negative samples further apart. The loss function is defined as:</p><p><em>L(A, P, N) = max(‖f(A) — f(P)‖² — ‖f(A) — f(N)‖² + margin, 0)</em></p><p>Here, <strong>A</strong> is the anchor image, <strong>P</strong> is the positive image, and <strong>N</strong> is the negative image. The function f(x) represents the embedding generated by the network, and the margin is a small positive value that helps ensure the network doesn’t collapse all embeddings to the same point.</p><p><strong>Setting Up the Siamese Network</strong></p><p>In this implementation, we start by loading the <strong>Totally Looks Like</strong> dataset, which contains images we use to create triplets for training the network.</p><p><strong>1. Data Preparation</strong></p><p>The dataset is processed using TensorFlow’s tf.data API to create triplets of images. This involves setting up a data pipeline where each triplet consists of an anchor, a positive, and a negative image. The images are preprocessed by resizing them to a target shape and normalizing their pixel values.</p><pre>def preprocess_image(filename):<br>    image_string = tf.io.read_file(filename)<br>    image = tf.image.decode_jpeg(image_string, channels=3)<br>    image = tf.image.convert_image_dtype(image, tf.float32)<br>    image = tf.image.resize(image, target_shape)<br>    return image<br><br>def preprocess_triplets(anchor, positive, negative):<br>    return (<br>        preprocess_image(anchor),<br>        preprocess_image(positive),<br>        preprocess_image(negative),<br>    )</pre><p>Here’s an example of triplets generated from the dataset, where the first two images in each row are similar (anchor and positive) and the third one is different (negative):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*HGT53m9eTYZQHb2tjW3yxg.png" /><figcaption><em>Figure 1: Triplets generated during data preparation. The first two images in each row are similar (anchor and positive), and the third is different (negative).</em></figcaption></figure><p><strong>2. Building the Embedding Generator</strong></p><p>The heart of our Siamese Network is the embedding generator, which is constructed using a <strong>ResNet50</strong> model pretrained on ImageNet. By freezing the weights of most layers in ResNet50 and fine-tuning only the final layers, we can leverage transfer learning to reduce training time and improve performance.</p><pre>base_cnn = resnet.ResNet50(<br>    weights=&quot;imagenet&quot;, input_shape=target_shape + (3,), include_top=False<br>)<br><br>flatten = layers.Flatten()(base_cnn.output)<br>dense1 = layers.Dense(512, activation=&quot;relu&quot;)(flatten)<br>dense1 = layers.BatchNormalization()(dense1)<br>dense2 = layers.Dense(256, activation=&quot;relu&quot;)(dense1)<br>dense2 = layers.BatchNormalization()(dense2)<br>output = layers.Dense(256)(dense2)<br><br>embedding = Model(base_cnn.input, output, name=&quot;Embedding&quot;)<br><br># Freeze all layers until the layer conv5_block1_out<br>trainable = False<br>for layer in base_cnn.layers:<br>    if layer.name == &quot;conv5_block1_out&quot;:<br>        trainable = True<br>    layer.trainable = trainable</pre><p><strong>3. Constructing the Siamese Network</strong></p><p>The Siamese Network is set up to take in three images at a time (anchor, positive, and negative). A custom DistanceLayer computes the distances between the anchor-positive pair and the anchor-negative pair. The model is then trained to minimize the distance between similar images and maximize the distance between dissimilar ones.</p><pre>class DistanceLayer(layers.Layer):<br>    def call(self, anchor, positive, negative):<br>        ap_distance = tf.reduce_sum(tf.square(anchor - positive), -1)<br>        an_distance = tf.reduce_sum(tf.square(anchor - negative), -1)<br>        return (ap_distance, an_distance)<br><br>anchor_input = layers.Input(name=&quot;anchor&quot;, shape=target_shape + (3,))<br>positive_input = layers.Input(name=&quot;positive&quot;, shape=target_shape + (3,))<br>negative_input = layers.Input(name=&quot;negative&quot;, shape=target_shape + (3,))<br><br>distances = DistanceLayer()(<br>    embedding(resnet.preprocess_input(anchor_input)),<br>    embedding(resnet.preprocess_input(positive_input)),<br>    embedding(resnet.preprocess_input(negative_input)),<br>)<br><br>siamese_network = Model(<br>    inputs=[anchor_input, positive_input, negative_input], outputs=distances<br>)</pre><p><strong>4. Training and Evaluation</strong></p><p>The model is trained using a custom training loop where the triplet loss is computed and used to update the network’s weights. The training process is carefully monitored, and the model’s performance is evaluated by inspecting the learned embeddings.</p><pre>class SiameseModel(Model):<br>    def __init__(self, siamese_network, margin=0.5):<br>        super(SiameseModel, self).__init__()<br>        self.siamese_network = siamese_network<br>        self.margin = margin<br>        self.loss_tracker = metrics.Mean(name=&quot;loss&quot;)<br><br>    def train_step(self, data):<br>        with tf.GradientTape() as tape:<br>            loss = self._compute_loss(data)<br>        gradients = tape.gradient(loss, self.siamese_network.trainable_weights)<br>        self.optimizer.apply_gradients(<br>            zip(gradients, self.siamese_network.trainable_weights)<br>        )<br>        self.loss_tracker.update_state(loss)<br>        return {&quot;loss&quot;: self.loss_tracker.result()}<br><br>    def _compute_loss(self, data):<br>        ap_distance, an_distance = self.siamese_network(data)<br>        loss = ap_distance - an_distance<br>        loss = tf.maximum(loss + self.margin, 0.0)<br>        return loss</pre><p><strong>5. Inspecting the Results</strong></p><p>After training, we can evaluate how well the network has learned to separate similar and dissimilar images by comparing the cosine similarity between the embeddings of the anchor-positive pairs and anchor-negative pairs.</p><pre>cosine_similarity = metrics.CosineSimilarity()<br><br>positive_similarity = cosine_similarity(anchor_embedding, positive_embedding)<br>print(&quot;Positive similarity:&quot;, positive_similarity.numpy())<br><br>negative_similarity = cosine_similarity(anchor_embedding, negative_embedding)<br>print(&quot;Negative similarity:&quot;, negative_similarity.numpy())</pre><p>Below is an example of triplets as evaluated by the trained model. The network successfully identifies the similarities and differences between the images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*LR01LkGhaspkCaTJN-wflg.png" /><figcaption><em>Figure 2: Output from the trained Siamese Network, where the first two images in each row are identified as similar by the model, and the third as different.</em></figcaption></figure><p><strong>Conclusion</strong></p><p>This implementation showcases how a Siamese Network with Triplet Loss can effectively estimate image similarity. By using a pretrained ResNet50 model and fine-tuning its layers, we can create a powerful model that can be applied to various tasks requiring similarity estimation.</p><p>The full implementation, including detailed code and explanations, is available in the <a href="https://github.com/elcaiseri/Siamese-Network">Siamese Network GitHub repository</a>. Whether you’re a beginner looking to learn about Siamese Networks or an expert seeking to refine your approach, this project provides a comprehensive guide to understanding and applying this powerful technique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124938e24b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Logistic Regression Model from Scratch with NumPy]]></title>
            <link>https://elcaiseri.medium.com/building-a-simple-logistic-regression-model-from-scratch-with-numpy-c8cf2439d059?source=rss-8573d8902876------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cf2439d059</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[binary-classification]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Islam Kassem]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 16:46:41 GMT</pubDate>
            <atom:updated>2024-07-15T16:46:41.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_rU5K_z_V-bu6NCO" /><figcaption>Photo by <a href="https://unsplash.com/@designedbyflores?utm_source=medium&amp;utm_medium=referral">Omar Flores</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Logistic regression is a fundamental algorithm used for binary classification problems where the outcome belongs to one of two classes. It predicts the probability that a given input falls into a certain class. Unlike linear regression, which predicts continuous outcomes, logistic regression maps input features to probabilities between 0 and 1 using the sigmoid function.</p><p>For more details, you can check the <a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch/blob/main/logisticRegression.py">source code on GitHub</a>.</p><p><a href="https://github.com/elcaiseri/Machine-Learning-from-Scratch">GitHub - elcaiseri/Machine-Learning-from-Scratch: Machine Learning using NumPy</a></p><h3>The Sigmoid Function</h3><p>At the heart of logistic regression is the sigmoid function. This function converts any real-valued number into a value between 0 and 1, representing the probability of the input belonging to the positive class. The formula for the sigmoid function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/0*BGBO19Fzfpe_b2lB.jpg" /><figcaption><em>The Sigmoid Function</em></figcaption></figure><h3>The Logistic Regression Model</h3><p>In logistic regression, we model the relationship between the input features (independent variables) and the binary outcome (dependent variable) using a linear combination of the input features, followed by the application of the sigmoid function. Mathematically, this can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*9M1WpWV_N2wnOCL3-384iw.png" /></figure><p>Here:</p><ul><li>X : represents the input features.</li><li>w : represents the weights associated with the features.</li><li>b : is the bias term.</li><li>sigma : is the sigmoid function.</li></ul><h3>Training the Model</h3><p>Training a logistic regression model involves finding the optimal weights w and bias b that minimize the error in the predictions. This is typically done using a method called gradient descent. Gradient descent is an iterative optimization algorithm used to minimize a function by adjusting the parameters in the opposite direction of the gradient of the function with respect to those parameters.</p><h3>Gradient Descent in Logistic Regression</h3><p>The key steps in training a logistic regression model using gradient descent are:</p><ol><li><strong>Initialize Parameters</strong>: Start with initial guesses for the weights and bias, usually set to zero.</li></ol><pre>self.w = np.zeros(m)  # Initialize weights<br>self.b = 0  # Initialize bias</pre><p><strong>2. Compute Predictions</strong>: Use the current weights and bias to compute the predicted probabilities for the input data using the sigmoid function.</p><pre>lr = (self.w @ X.T + self.b) / n<br>yhat = self._sigmoid(lr)</pre><p><strong>3. Calculate the Loss</strong>: Measure the difference between the predicted probabilities and the actual outcomes using a loss function. For logistic regression, the common loss function is the binary cross-entropy loss.</p><p><strong>4. Compute Gradients</strong>: Calculate the gradient of the loss function with respect to each parameter. The gradients indicate how much the loss would change if the parameter were adjusted slightly.</p><pre>db = 1 / n * np.sum(-y + yhat) <br>dw = 1 / n * (-y + yhat) @ X </pre><p><strong>5. Update Parameters</strong>: Adjust the weights and bias by moving them in the opposite direction of their respective gradients, scaled by a learning rate. This step is repeated for a specified number of iterations or until the loss converges.</p><pre>self.b -= self.learning_rate * db<br>self.w -= self.learning_rate * dw</pre><h3>Making Predictions</h3><p>After training the model, making predictions on new data involves computing the linear combination of the input features using the learned weights and bias, applying the sigmoid function to get predicted probabilities, and converting these probabilities into class labels based on a chosen threshold (typically 0.5).</p><pre>def predict(self, X):<br>    lr = self.b + self.w @ X.T<br>    return self._sigmoid(lr) &gt; self.th</pre><h3>Evaluating the Model</h3><p>To assess the performance of a logistic regression model, metrics like accuracy, precision, recall, and the F1 score are commonly used. These metrics provide a comprehensive view of the model’s classification performance.</p><h3>Practical Application</h3><p>Let’s put logistic regression into practice by predicting whether a tumor is malignant or benign using the breast cancer dataset. Here’s a step-by-step implementation:</p><pre>if __name__ == &quot;__main__&quot;:<br>    from sklearn.model_selection import train_test_split as tts <br>    from sklearn import datasets as ds <br>    import matplotlib.pyplot as plt<br>    <br>    # Create dataset<br>    np.random.seed(1234)   <br>    bc = ds.load_breast_cancer()<br>    X, y = bc.data, bc.target<br>    X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2, random_state=1234)<br>    <br>    # Model<br>    lr = LogisticRegression(1000, 0.01, 0.5)<br>    lr.fit(X_train, y_train)<br>    y_pred = lr.predict(X_test)<br>    <br>    # Evaluate<br>    acc = (y_test == y_pred).mean()<br>    print(&quot;Logistic Regression Test Accuracy:&quot;, acc)</pre><h3>Conclusion</h3><p>Logistic regression is a powerful algorithm for binary classification problems. By understanding its mathematical foundation and the steps involved in training the model, you can appreciate how logistic regression makes predictions and why it is widely used in various fields, from medical diagnostics to marketing. Building a logistic regression model from scratch enhances your understanding and equips you to implement more complex machine learning models.</p><p>Experiment with different datasets, tweak parameters, and explore advanced techniques like regularization to prevent overfitting. The more you practice, the more proficient you will become in leveraging logistic regression to solve real-world problems. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cf2439d059" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>