<?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 Oluwaseyi Akinsanya on Medium]]></title>
        <description><![CDATA[Stories by Oluwaseyi Akinsanya on Medium]]></description>
        <link>https://medium.com/@seyiakinsanya3?source=rss-4dac8d180f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xG-C2CUNSa-lCmenex7qUg@2x.jpeg</url>
            <title>Stories by Oluwaseyi Akinsanya on Medium</title>
            <link>https://medium.com/@seyiakinsanya3?source=rss-4dac8d180f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:39:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seyiakinsanya3/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[Building a Fintech Reconciliation Platform from Scratch]]></title>
            <link>https://medium.com/@seyiakinsanya3/building-a-fintech-reconciliation-platform-from-scratch-1b74842ede4a?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b74842ede4a</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 02:54:34 GMT</pubDate>
            <atom:updated>2026-04-19T02:54:34.863Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Here is what I built, why I built it, and what I learned.</em></p><h3>The Problem</h3><p>The business is a cross-border remittance startup. Money comes in from senders in one currency. It goes out to recipients in another. To make that happen, the business relies on multiple payment partners: one for each currency leg, with a crypto rail for certain routing scenarios.</p><p>Every day, each partner generates a transaction export. The operations team would download these files, open them in Excel, and manually match them against the platform’s internal transaction log, looking for discrepancies, missing transactions, and amount mismatches.</p><p>This took hours. It scaled with transaction volume, not team size. On top of that, there was no structured way to record over-the-counter transactions, creating a compliance blind spot that grew more serious as the business scaled.</p><p><strong>So I built a solution.</strong></p><h3>The Solution</h3><p>I built a five-layer system: a Python reconciliation pipeline, a FastAPI backend, a SQLite database, a React dashboard, and on top of that, a Deal Calculator for pre-trade FX pricing and an OTC Deal Logger for compliance tracking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAZ4NsWZ6iimTRs5xkFsYg.png" /><figcaption>Five layers. One pipeline. Built to replace hours of manual work every day.</figcaption></figure><h3>High-Level System Deep Dive</h3><h3>The Reconciliation Pipeline</h3><p>The pipeline runs in four steps. First, it ingests and cleans every partner file, normalizing date formats, stripping currency symbols, filtering cancelled transaction, and extracting customer names from messy narration strings. Each partner has different conventions, none of them documented, which made the cleaning layer the most time-intensive part of the entire build.</p><p>Second, it runs the reconciliation, matching the platform’s internal records against each partner export using amount, timestamp, and normalised name similarity across multiple layers. Anything unmatched is flagged as an exception for the operations team to review.</p><p>Third, it calculates transaction volume across categories, with explicit exclusions for internal liquidity transfers that would otherwise inflate the figures. Finally, it generates formatted Excel reports, one per currency, with reconciliation results, OTC breakdowns, and volume data, ready for the team without any further processing.</p><h3>The OTC Deal Logger</h3><p>In over-the-counter remittance, a customer contacts the business directly to initiate a transaction on their behalf. The money moves through the payment rails as normal, but because the customer is not transacting through the platform themselves, their identity never appears in the payment partner’s transaction data. Only the recipient’s does. This means there is no automated way to link a payout to a specific customer without manual entry.</p><p>The logger enforces a clean data model: every transaction must be linked to a customer record with a unique ID. Free-text entry is blocked. The ops team must search the customer list and select, or explicitly add a new customer. This ensures that when a customer transacts multiple times in a day, all their transactions are correctly aggregated for the daily compliance review.</p><p>I also built a recipient directory, a customer merge tool for handling duplicate records, and bulk import from historical partner exports to seed the customer list from day one.</p><h3>The Deal Calculator</h3><p>Before this tool existed, pricing a deal was done mentally. The calculator is purely client-side, with no API calls, and computes the full fee chain for any deal: sending partner fee, receiving partner fees, crypto exchange fee where applicable, liquidity provider spread, FX spread revenue, net revenue, and margin. The fee structures are shared across the calculator and the OTC logger so any update is instantly reflected in both.</p><h3>Architecture Overview</h3><p>• Python for the pipeline: pandas for data manipulation, openpyxl for Excel generation. The cleaning and reconciliation logic is modular, with each partner having its own preparation function.</p><p>• FastAPI for the backend: async background tasks for long-running pipeline runs, JWT authentication with admin and viewer roles, and clean REST endpoints consumed by the dashboard.</p><p>• SQLite on a persistent cloud disk: no managed database service, no connection pooling overhead. Simple, reliable, and right-sized for the scale.</p><p>• React as a single HTML file: no build step, no bundler. Babel transpiles JSX in the browser. The entire frontend deploys by replacing one file.</p><p>• Shared fee state across features: the transaction fees live at the top of the app and flow down as props, keeping the Deal Calculator and OTC Logger in sync automatically.</p><h3>Lessons Learned</h3><h4>Data cleaning takes longer than the actual logic</h4><p>I spent more time on data cleaning than on the reconciliation matching itself. Every partner has different conventions: date formats, column names, encoding quirks. None of them documented. Build your cleaning layer defensively and test it against real exports from day one.</p><h4>Understand the operation before writing code</h4><p>Blocking free-text entry was not a UI preference. It was a compliance requirement I only understood after talking to the team about how deals actually get recorded. Two rounds of redesign could have been avoided by asking the right questions upfront.</p><h4>Simple infrastructure is a feature</h4><p>SQLite on a persistent disk. A single HTML file frontend. No Kafka, no Spark, no micro-services. For a small team with modest transaction volume, this stack is not a compromise. It is the right tool. Operational simplicity compounds over time.</p><h4>React input lag is a state design problem</h4><p>The Deal Calculator had severe input lag because every keystroke triggered a full re-render. The fix was not optimizing the calculation, which runs in microseconds. It was restructuring state flow: local state per input, propagation to the parent only on blur or Enter, and useMemo for the calculation itself.</p><h4>Build what you understand</h4><p>The system is designed to support multiple corridors and currencies, but I only implemented the ones I fully understood. Others appear in the UI as disabled options. Implementing a pricing calculator for a corridor you do not understand produces something that is confidently wrong, which is worse than not having it at all.</p><h3>Closing Thoughts</h3><p>Building this taught me that the hardest problems in fintech infrastructure are rarely the technical ones. They are understanding what the business actually needs, encoding operational rules correctly, and resisting the urge to over-engineer before the requirements are clear.</p><p><em>Nothing about this stack turns heads. Neither does the problem it solves. But the system replaced hours of daily manual work, replaced a manual compliance audit trail with one that is automated, searchable, and always current, and gave the operations team real-time visibility into their reconciliation health for the first time.</em></p><p><em>And when the business is ready to scale, the architecture is too. The foundation is solid. The rest is just time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b74842ede4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vanishing and Exploding Gradients Problems in Deep Learning]]></title>
            <link>https://medium.com/@seyiakinsanya3/vanishing-and-exploding-gradients-problems-in-deep-learning-e6a1591a1c44?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a1591a1c44</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[exploding-gradient]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 20:01:48 GMT</pubDate>
            <atom:updated>2025-07-27T20:12:57.644Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Vanishing and Exploding Gradients in Deep Learning</h3><p><strong><em>by Oluwaseyi Akinsanya</em></strong></p><p><em>This article is a continuation of my previous </em><a href="https://medium.com/@seyiakinsanya3/gradient-descent-in-classmachine-learning-vs-neural-networks-key-differences-and-implementation-719a24dbff52"><em>Medium</em></a><em> post on </em><strong><em>Gradient Descent Optimization</em></strong><em>, where we explored how gradient-based methods power learning in classical machine learning and neural networks. In this follow-up, we dive deeper into two critical challenges that can arise during the training of neural nets: </em><strong><em>vanishing</em></strong><em> and </em><strong><em>exploding gradients</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7Dpo68uOaKjaxbzxVYJ3g.png" /><figcaption>Gradient Flow in Deep Networks</figcaption></figure><p>Training deep neural networks with <strong>gradient descent</strong> — a foundational optimization algorithm — can become challenging when gradients either become too small or too large during backpropagation. These two issues are known as:</p><ul><li><strong>Vanishing Gradients</strong></li><li><strong>Exploding Gradients</strong></li></ul><p>Understanding and addressing these problems is crucial for building deep models that train efficiently and converge reliably. In this article, we’ll explore the challenges of vanishing and exploding gradients — examining what they are, why they happen, and practical strategies to address them. We’ll also build and train a model to observe these issues firsthand and learn how to effectively handle them during training.</p><h3>What is Vanishing Gradient?</h3><p>The vanishing gradient problem is a challenge that emerges during back-propagation when the derivatives of the activation functions become progressively smaller as we move backward through the layers of a neural network. It is particularly prominent in deep networks with many layers, hindering effective training of the model. The weight updates become extremely tiny, or even exponentially small, it can significantly prolong the training time, and in the worse-case scenario, it can halt the training process altogether.</p><h4>Why the Problem Occurs?</h4><p>During backpropagation, the gradients propagate back through the layers of the network, they decrease significantly. This means that as they leave the output layer and return to the input layer, the gradients become progressively smaller. As a result, the weights associated with the initial levels, which accommodate these small gradients, are updated little or not at each iteration of the optimization process.</p><blockquote>Imagine you’re in a long line of people playing a game of “telephone,” where each person whispers a message to the next. But now, everyone is tired, and whispers more softly than they heard it. By the time the message reaches the first person in the chain, it’s so faint they can barely hear it — or not at all. In a neural network, this is like the vanishing gradient problem. As the correction signals (gradients) pass backward through each layer, they get weaker — especially with activation functions like sigmoid or tanh. The early layers (like the first people in line) barely receive a signal to improve, so they stay almost unchanged, slowing or even stopping the learning process.</blockquote><h4>How can we Identify Vanishing Gradient?</h4><p>Identifying the vanishing gradient problem is like teaching a complex dance routine to a large group of students. If only the students at the front are improving while those at the back remain confused or barely move, it suggests that the instructions aren’t reaching everyone clearly. In neural networks, this appears when performance metrics like accuracy or loss stop improving, or the training behaves erratically. You might also notice that the weights in the earlier layers hardly change at all. Tools like gradient histograms or norm visualizations act like a teacher scanning the room — they help reveal which layers are actively learning and which are being left behind.</p><h4>How can we Solve the Issue?</h4><ol><li><strong>Batch Normalization</strong>: Imagine you’re teaching a student new topics every day, but sometimes you use very hard words and other times very simple ones. The student might struggle to keep up or get confused. If you always used clear and consistent language, the student would learn better and faster. Batch normalization works in a similar way — it helps make the training of a neural network more stable and faster by keeping the inputs to each layer well-balanced. It does this by adjusting the data going into each layer so that it’s not too big or too small. This keeps the learning process smooth and helps the model improve more quickly.</li><li><strong>Activation function</strong>: Activation function like <strong>Rectified Linear Unit (ReLU)</strong> can be used. With <strong>ReLU,</strong> the gradient is 0 for negative and zero input, and it is 1 for positive input, which helps alleviate the vanishing gradient issue. Therefore, ReLU operates by replacing poor enter values with 0, and 1 for fine enter values, it preserves the input unchanged.</li><li><strong>Long Short-Term Memory Networks (LSTMs) and Gated Recurrent Units (GRUs)</strong>: These are special types of neural networks that are good at learning from sequences, like sentences or time series. They have built-in gates that help them remember important information and forget what’s not needed. This helps them avoid the problem where learning becomes too slow or stops completely</li><li><strong>Gradient Clipping</strong>: Gradient clipping involves imposing a threshold on the gradients during backpropagation. It limits the magnitude of gradients during backpropagation, this can prevent them from becoming too small or exploding, which can also hinder learning.</li></ol><h4>Before vs After: Training Loss Comparison (Vanishing Gradients)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7Yx9yfWqg7KlJn_19deRA.png" /><figcaption>Vanishing G</figcaption></figure><p>The <strong>left plot</strong> shows the training loss before applying gradient-related fixes. The curve flattens early, barely improving after initial epochs — an indication of the <strong>vanishing gradient problem</strong>. This happens when gradients become too small to meaningfully update weights, especially in deeper networks or with sigmoid/tanh activations.</p><p>The <strong>right plot</strong>, however, displays a steadily decreasing training loss, reflecting effective learning after the model was modified. This demonstrates that the vanishing gradients were successfully mitigated.</p><h4>Steps Taken to Fix the Vanishing Gradient Problem</h4><p>To address the stagnating loss, the following modifications were applied:</p><ul><li><strong>Deeper Architecture</strong>: Increased the number of layers and neurons to allow the model to learn more abstract features.</li><li><strong>Dropout Layers</strong>: Added dropout after dense layers to reduce overfitting and allow the network to generalize better.</li><li><strong>Early Stopping</strong>: Monitored validation loss and halted training once it stopped improving, avoiding overtraining.</li><li><strong>Learning Rate Adjustment</strong>: Set the learning rate to 0.001, which helped stabilize training without overwhelming weight updates.</li></ul><h3>What is Exploding Gradient?</h3><p>The exploding gradient problem occurs when the numbers used to update a neural network’s weights during training become extremely large. This usually occurs in very deep networks or those that process sequences, like Recurrent Neural Networks (RNNs).</p><h4>Why Exploding Gradient Occurs?</h4><p>Exploding gradients happen when, during backpropagation, the gradients (or slopes) of the network’s layers increase dramatically as they move backward through the layers. This is the opposite of the vanishing gradient problem.</p><p>The main cause lies in large weight values, not the activation function. When weights are too high, they produce very large gradients, leading to big jumps in updated weights. This prevents the model from settling down and can cause it to bounce around instead of learning properly. As a result, the network struggles to find the best solution and may never reach the global minimum. Exploding gradients cause the model to update too aggressively, making learning unstable or impossible.</p><p>The update for the weights during backpropagation in a neural network is given by:</p><p>Δ<em>Wi</em>​ = − <em>α </em>⋅​ ∂<em>L / </em>∂<em>Wi</em></p><p>where,</p><ul><li>Δ<em>Wi</em>​ : The change in the weight <em>Wi</em>​</li><li><strong>α</strong>: The learning rate, a hyperparameter that controls the step size of the update.</li><li><strong>L</strong>: The loss function that measures the error of the model.</li><li>​∂<em>L / </em>∂<em>Wi</em>​: The partial derivative of the loss function with respect to the weight <em>Wi</em>​, which indicates the gradient of the loss function with respect to that weight.​</li></ul><h4>How can we Identify the Problem?</h4><p>Detecting exploding gradients in deep neural networks involves closely monitoring the training process. Here are some common indicators:</p><ul><li>The loss function behaves unpredictably, fluctuating sharply instead of gradually decreasing. This indicates that large gradients are causing the network’s weights to be updated too drastically, disrupting steady learning and preventing proper convergence.</li><li>The training process runs into “NaN” (Not a Number) values in the loss function or during intermediate steps, indicating numerical instability.</li><li>If network weights, during training exhibit significant and rapid increases in their values, it suggests the presence of exploding gradients.</li><li>Visualization tools such as TensorBoard can help monitor and track the gradients as they move through the network.</li></ul><h4>How can we Solve the Issue?</h4><ul><li><strong>Gradient Clipping</strong>: It sets a maximum threshold for the magnitude of gradients during backpropagation. Any gradient exceeding the threshold is clipped to the threshold value, preventing it from growing unbounded.</li><li><strong>Batch Normalization:</strong> This technique normalizes the activations within each mini-batch, effectively scaling the gradients and reducing their variance. This helps prevent both vanishing and exploding gradients, improving stability and efficiency.</li></ul><h4>Before vs After: Training Loss Comparison (Exploding Gradients)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TX8GrQk5CnB960vzKgcyw.png" /></figure><p>The <strong>left plot</strong> displays the training loss before resolving the exploding gradient issue. The curve fluctuates dramatically across epochs, showing unstable and erratic training. This is a hallmark of <strong>exploding gradients</strong>, where excessively large gradient values cause the weights to overshoot optimal values, making it impossible for the model to converge.</p><p>In contrast, the <strong>right plot</strong> shows the training loss after mitigation. The curve follows a smooth downward trajectory, indicating stable convergence and effective learning.</p><h4>Steps Taken to Fix Exploding Gradients</h4><p>To address the training instability, the following changes were applied to the model:</p><ul><li><strong>Applied Max-Norm Constraint: </strong>Limited the maximum norm of the weight vectors (max_norm(2.0)) to prevent weights from growing too large during training.</li><li><strong>Used Glorot (Xavier) Uniform Initialization: </strong>Chose glorot_uniform to initialize weights with a balanced variance. This helps keep activations and gradients within a manageable range across layers, reducing the chance of exploding gradients.</li><li><strong>Used Smooth Activation (</strong><strong>tanh): </strong>While tanh can risk vanishing gradients in deeper networks, in this case, it helped regulate the flow of information and avoided overly steep gradients.</li><li><strong>Lower Learning Rate</strong>: Reduced the learning rate to prevent aggressive updates that could cause instability.</li></ul><blockquote>By carefully initializing weights, constraining weight norms, and regulating activation flow, the model overcame instability and achieved smooth convergence — effectively solving the exploding gradient issue.</blockquote><h3>Final Thoughts</h3><p>Training deep neural networks isn’t just about stacking layers — it’s about understanding how gradients behave during backpropagation. In this article, we walked through <strong>what vanishing and exploding gradients look like</strong>, why they happen, and how to fix them using practical techniques like proper initialization, gradient constraints, and architectural tuning.</p><p>We backed up the discussion with clear visuals and side-by-side comparisons of model performance <em>before and after</em> applying these fixes.</p><p>💡 <strong>If you’re a technical reader or practitioner</strong>, I’ve included the <strong>complete source code</strong> used for all experiments and visualizations below — feel free to explore, tweak, and build on it.</p><p>Source Code: <a href="https://github.com/zooviee/Medium-Series/blob/main/credit_card.ipynb">notebook</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/seyi-a-852314184/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a1591a1c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent in ClassMachine Learning vs Neural Networks: Key Differences and Implementation]]></title>
            <link>https://medium.com/@seyiakinsanya3/gradient-descent-in-classmachine-learning-vs-neural-networks-key-differences-and-implementation-719a24dbff52?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/719a24dbff52</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 06:48:24 GMT</pubDate>
            <atom:updated>2025-07-24T07:16:04.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gradient Descent in Classical Machine Learning vs Neural Networks: Key Differences and Implementation</h3><p><strong><em>By Oluwaseyi Akinsanya</em></strong></p><figure><img alt="Gradient Descent: ML vs Neural Networks" src="https://cdn-images-1.medium.com/max/1024/1*GgSJTUva6brJGtFx6ddGkg.png" /><figcaption>Gradient Descent: Machine Learning vs Neural Networks</figcaption></figure><p>Gradient descent is the backbone of most learning algorithms. Whether you’re training a simple linear regression model or a deep neural network, gradient descent is likely the optimization engine behind the scenes. But while the concept is universal, its application differs significantly between traditional machine learning and deep learning. This article explores these key differences and provides implementation examples for both scenarios.\</p><h3>What is Gradient Descent?</h3><p>Gradient descent is an optimization algorithm used to minimize a cost (or loss) function by iteratively updating model parameters in the opposite direction of the gradient.</p><p>At its core, gradient descent updates parameters θ as:</p><p>θ = θ − α ⋅ ∇J(θ)</p><p>Where:</p><ul><li>α is the learning rate</li><li>θ are the parameters of the model (slope / weights, bias / intercept)</li><li>∇J(θ) is the gradient of the cost function with respect to the parameters</li></ul><h3>Types of Gradient Descent</h3><ul><li>Batch: Uses the entire dataset for each update.</li><li>Stochastic: Uses one random sample per update.</li><li>Mini-batch: Uses small random subsets of data for each update.</li></ul><h3>⚖️ Gradient Descent in ML vs Neural Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2R8TCJyvmA0LblGleSBbHA.png" /></figure><h3>🧪 Part 1: Gradient Descent in Traditional Machine Learning</h3><p>The image below features two graphs: the left graph displays house prices versus size, illustrating the errors evaluated by the cost function. The right graph demonstrates how gradient descent iteratively updates parameters, moving downhill along the cost curve to reduce error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCAYiyHL3H5UK0TveRzUHA.png" /><figcaption><strong>Gradient Descent in Linear Regression</strong></figcaption></figure><h3>Why Use Gradient Descent for Linear Regression?</h3><p>Linear regression aims to determine the best-fit line for a dataset by minimizing the difference between actual and predicted values. This difference is quantified using a cost function, typically the Mean Squared Error (MSE). The objective is to find the optimal values for the model parameters — <strong>slope m</strong> and <strong>intercept b</strong> — that minimize this cost.</p><p>In simple linear regression, parameters can be calculated directly using formulas like the Normal Equation. However, for large datasets or high-dimensional data, these direct methods become inefficient due to:</p><ul><li>Intensive matrix computations</li><li>Memory constraints</li></ul><p>Additionally, in models such as polynomial regression, the cost function becomes more complex and non-linear, making analytical solutions impractical. In such cases, gradient descent becomes essential, especially for:</p><ul><li>Handling large-scale data</li><li>Complex, high-dimensional problems.</li></ul><h3>How Does Gradient Descent Work in Linear Regression?</h3><p>Let’s see the various steps involved in the working of Gradient Descent in Linear Regression:</p><ol><li><strong>Initializing Parameters</strong>: Start with random initial values for the slope (m) and intercept (b).</li><li><strong>Calculate the Cost Function</strong>: Measure the error using the Mean Squared Error</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dY06jdCw7vvlUCt01yhYA.png" /></figure><p><strong>3. Compute the Gradient</strong>: Calculate how much the cost function changes with respect to <em>m </em>and <em>b</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQFE3gfAnYAjoCVrqe9pnw.png" /></figure><ul><li>For slope <em>m</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQpIvtWGisY4anYHoMIk-w.png" /></figure><ul><li>For intercept <em>b</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP7bkMNRtnmiPK-EIlsAxg.png" /></figure><p><strong>4. Update Parameters</strong>: Change <em>m</em> and <em>b</em> to reduce the error:</p><ul><li>For slope <em>m</em> :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Pzlz7GWYQBUQ0K6cR9chZQ.png" /></figure><ul><li>For intercept <em>b</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BfYiPoitNeR76IgcXTinTA.png" /></figure><p>Here <strong><em>α</em></strong> is the learning rate that controls the size of each update.</p><p><strong>5. Repeat</strong>: Keep repeating steps 2–4 until the error stops decreasing significantly.</p><h3>Implementation of Gradient Descent in Linear Regression</h3><pre>import numpy as np <br>import math<br><br># Implementation of Gradient Descent Algorithm<br>def gradient_descent(X, y, alpha, num_iters, tol=1e-20, log_interval=1000):<br>    &quot;&quot;&quot;    <br>    Performs gradient descent to learn theta.<br><br>    Parameters:<br>    X : numpy array<br>        The input feature matrix.<br>    y : numpy array<br>        The output values.<br>    alpha : float<br>        Learning rate.<br>    num_iters : int<br>        Number of iterations for gradient descent.<br>    tol : float<br>        Tolerance for early stopping.<br>    log_interval : int<br>        How often to print progress (in iterations).<br>    <br>    Returns:<br>    slope: float<br>        The optimized slope of the line.<br>    intercept: float<br>        The optimized intercept.<br>    &quot;&quot;&quot;<br>    slope = 0<br>    intercept = 0<br>    n = len(X)<br>    prev_cost = float(&#39;inf&#39;)<br><br>    for iter in range(num_iters):<br>        y_predicted = slope * X + intercept<br>        cost = (1/n) * np.sum((y - y_predicted) ** 2)<br>        <br>        if math.isclose(cost, prev_cost, rel_tol=tol):<br>            print(f&quot;Converged at iteration {iter}&quot;)<br>            break<br>        <br>        dm = -(2/n) * np.sum(X * (y - y_predicted))<br>        db = -(2/n) * np.sum(y - y_predicted)<br>        slope -= alpha * dm<br>        intercept -= alpha * db<br>        prev_cost = cost<br><br>        if iter % log_interval == 0:<br>            print(f&quot;Iteration {iter}: slope = {slope:.4f}, intercept = {intercept:.4f}, cost = {cost:.4f}&quot;)<br>    <br>    return slope, intercept<br><br><br>X = np.array([92, 56, 88, 70, 80, 49, 65, 35, 66, 67])<br>y = np.array([98, 68, 81, 80, 83, 52, 66, 30, 68, 73])<br><br># Run Gradient Descent<br>result = gradient_descent(X, y, alpha=0.0002, num_iters=415000)<br>print(&quot;\nFinal Result (slope, intercept):&quot;, result)</pre><p>The model reached convergence at <strong>iteration 411,473</strong> when the change in the cost function became negligible, meeting the early stopping condition. At this point, further updates to the slope and intercept no longer significantly reduced the error, indicating that the optimal parameters had been found.</p><h3>🤖 Part 2: Gradient Descent in Neural Networks</h3><p>In linear regression, gradient descent updates a simple set of parameters — slope and intercept — to minimize a convex cost function like <strong>Mean Squared Error</strong>, making convergence straightforward. In contrast, neural networks involve multiple layers of weights and biases, where gradient descent is applied via <strong>back-propagation</strong> using the chain rule. This makes optimization more complex, often non-convex, and prone to issues like <strong>vanishing</strong> or <strong>exploding gradients</strong>.</p><pre>def sigmoid_numpy(X):<br>   return 1/(1+np.exp(-X))<br><br>def log_loss(y_true, y_predicted):<br>    epsilon = 1e-15<br>    y_predicted_new = [max(i,epsilon) for i in y_predicted]<br>    y_predicted_new = [min(i,1-epsilon) for i in y_predicted_new]<br>    y_predicted_new = np.array(y_predicted_new)<br>    return -np.mean(y_true*np.log(y_predicted_new)+(1-y_true)*np.log(1-y_predicted_new))</pre><pre>class myNN:<br>    def __init__(self):<br>        self.w1 = 1 <br>        self.w2 = 1<br>        self.bias = 0<br>        <br>    def fit(self, X, y, epochs, loss_thresold):<br>        self.w1, self.w2, self.bias = self.gradient_descent(X[&#39;age&#39;],X[&#39;affordibility&#39;],y, epochs, loss_thresold)<br>        print(f&quot;Final weights and bias: w1: {self.w1}, w2: {self.w2}, bias: {self.bias}&quot;)<br>        <br>    def predict(self, X_test):<br>        weighted_sum = self.w1*X_test[&#39;age&#39;] + self.w2*X_test[&#39;affordibility&#39;] + self.bias<br>        return sigmoid_numpy(weighted_sum)<br><br>    def gradient_descent(self, age,affordability, y_true, epochs, loss_thresold):<br>        w1 = w2 = 1<br>        bias = 0<br>        rate = 0.5<br>        n = len(age)<br>        for i in range(epochs):<br>            weighted_sum = w1 * age + w2 * affordability + bias<br>            y_predicted = sigmoid_numpy(weighted_sum)<br>            loss = log_loss(y_true, y_predicted)<br>            <br>            w1d = (1/n)*np.dot(np.transpose(age),(y_predicted-y_true)) <br>            w2d = (1/n)*np.dot(np.transpose(affordability),(y_predicted-y_true)) <br><br>            bias_d = np.mean(y_predicted-y_true)<br>            w1 = w1 - rate * w1d<br>            w2 = w2 - rate * w2d<br>            bias = bias - rate * bias_d<br>            <br>            if i%50==0:<br>                print (f&#39;Epoch:{i}, w1:{w1}, w2:{w2}, bias:{bias}, loss:{loss}&#39;)<br>            <br>            if loss&lt;=loss_thresold:<br>                print (f&#39;Epoch:{i}, w1:{w1}, w2:{w2}, bias:{bias}, loss:{loss}&#39;)<br>                break<br><br>        return w1, w2, bias</pre><p>The model reached convergence at <strong>iteration 366</strong> when the change in the cost function became negligible, meeting the early stopping condition. At this point, further updates to the slope and intercept no longer significantly reduced the error, indicating that the optimal parameters had been found.</p><h3>🧠 Why It’s More Complicated in Neural Nets</h3><ul><li>Neural networks often have <strong>millions of parameters</strong>.</li><li>You need <strong>back-propagation</strong> to compute gradients efficiently.</li><li>The optimization surface is <strong>non-convex</strong>, which introduces local minima and plateaus.</li><li>Choosing the right <strong>optimizer (Adam, RMSprop)</strong> and <strong>learning rate schedule</strong> becomes critical.</li></ul><h3>✨Conclusion</h3><p>Determining whether an optimization problem is convex or non-convex is essential, as it directly impacts the choice of optimization strategy, the ability to guarantee a global optimum, and the overall complexity of the solution process. Recognizing the nature of the problem — whether convex with a single global minimum or non-convex with multiple local optima — helps in selecting the right optimization techniques and setting realistic expectations about convergence and solution quality. This understanding ensures more effective model training and better-informed decisions in machine learning and deep learning applications.</p><p>While gradient descent serves as the foundational optimization technique in both traditional machine learning and neural networks, its practical implementation differs substantially. Traditional ML implementations tend to be simpler and more straightforward, while neural network implementations require sophisticated optimizers and careful consideration of computational constraints. Understanding these differences is crucial for selecting the right approach for your specific machine learning task.</p><p>👉 <a href="https://github.com/zooviee/Gradient-Descent">GitHub Repo With Code</a></p><p><strong>Connect With Me:</strong></p><p>👉 <a href="https://github.com/zooviee">GitHub</a></p><p>👉 <a href="https://www.linkedin.com/in/oluwaseyi-akinsanya-852314184">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719a24dbff52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Time Series Analysis with LSTM: Predicting Stock Trends]]></title>
            <link>https://medium.com/@seyiakinsanya3/time-series-analysis-with-lstm-predicting-stock-trends-90eeb6f2bfb5?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/90eeb6f2bfb5</guid>
            <category><![CDATA[lstm-model]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 19:09:32 GMT</pubDate>
            <atom:updated>2025-07-14T20:07:26.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FCiLfzUODhB711zKFIwBw.png" /></figure><p>Time series analysis has become a crucial skill for data analysts and financial researchers. From predicting sales to modeling stock market behavior, this technique helps us understand how data evolves over time. One of its most powerful applications lies in forecasting stock prices — a notoriously noisy but fascinating problem.</p><p>In this article, I walk through how I used <strong>LSTM (Long Short-Term Memory)</strong> neural networks to forecast the closing price of a stock listed on India’s NSE: <strong>POWERGRID.NS</strong>. Along the way, I cover the fundamentals of time series data, visualization, and deep learning-based forecasting using Python.</p><h3>What is Time Series Analysis?</h3><p>Time series analysis involves techniques for analyzing time-ordered data points. It differs from other types of data analysis because:</p><ul><li>Chronological order matters.</li><li>Data points are often autocorrelated.</li><li>The goal is typically forecasting or understanding temporal patterns.</li></ul><p>Some key components include:</p><ul><li><strong>Trend</strong> — represents long-term movement or directionality of the data over time.</li><li><strong>Seasonality</strong> — refers to periodic fluctuations or patterns that occur at regular intervals within the time series.</li><li><strong>Cycle variations — </strong>are longer-fluctuations in the time series that do not have a fixed period like seasonality.</li><li><strong>Noise</strong> — refers to the unpredictable or random variation in the data that cannot be attributed to trend, seasonality, or cyclical variations.</li></ul><h3>Collecting Stock Data with yfinance</h3><p>To start, I used the yfinance library to retrieve historical price data for POWERGRID.NS from 2015 to the end of 2024:</p><blockquote>import yfinance as yf</blockquote><blockquote>df = yf.download(‘POWERGRID.NS’, start=’2015–01–01&#39;, end=’2024–12–31&#39;)</blockquote><h3>Exploratory Data Analysis (EDA)</h3><p>I explored the stock’s <strong>Open</strong>, <strong>Close</strong>, <strong>High</strong>, <strong>Low</strong>, and <strong>Volume</strong> using matplotlib and plotly. This helped to understand the underlying behavior before modeling:</p><h4>📊 Sample Visualizations:</h4><ul><li>Line charts of opening and closing prices over time.</li><li>Candlestick plots using Plotly.</li><li>Volume trends indicating trading activity.</li></ul><p>These plots revealed strong trends and volatility — both of which are important signals for model training.</p><h3>Data Preparation for LSTM</h3><p>LSTMs expect <strong>3D input</strong> shaped like (samples, time steps, features). To prepare the data:</p><ul><li>I normalized the closing price using MinMaxScaler.</li><li>I created sequences (sliding windows) of past 100 days to predict the 101st.</li><li>Split the data into training and testing sets.</li></ul><h3>Building the LSTM Model</h3><p>To capture long-term dependencies in the stock’s price behavior, I constructed a <strong>deep LSTM model</strong> using Keras. The model consists of <strong>4 stacked LSTM layers</strong> with increasing units, each followed by a <strong>Dropout layer</strong> to prevent overfitting.</p><h4>📌 Why This Architecture?</h4><ul><li><strong>Stacked Layers</strong> allow the network to learn hierarchical temporal features — from simple to complex.</li><li><strong>Increasing units (50 → 120)</strong> help the model progressively capture deeper patterns.</li><li><strong>Dropout Layers</strong> are essential for preventing overfitting, especially in financial data where noise is high.</li><li><strong>ReLU Activation</strong> was used instead of the default tanh to experiment with faster convergence and avoid vanishing gradients.</li></ul><h4>📈 Model Training</h4><p>The model was trained for 50 epochs. The loss steadily decreased, showing the model’s ability to learn patterns from historical closing prices.</p><h3>Visualizing the Prediction</h3><p>The final output compared the predicted closing prices against actual values. The LSTM model was able to <strong>capture the trend</strong>, though some lag was observed — common with financial data due to its stochastic nature.</p><h3>Reflections and Challenges</h3><p><strong>Pros</strong>:</p><ul><li>LSTM handles sequential dependencies well.</li><li>Moving averages and volume analysis helped improve preprocessing.</li></ul><p><strong>Challenges</strong>:</p><ul><li>High sensitivity to hyperparameters (like window size).</li><li>Stock prices are influenced by exogenous events (news, policies, earnings).</li></ul><h3>Conclusion</h3><p>Stock price forecasting is not about predicting the market perfectly, but about identifying useful trends and improving decision-making. LSTM-based time series models provide a powerful way to do just that, especially when paired with strong domain knowledge.</p><p>In the future, I plan to:</p><ul><li>Incorporate external features (sentiment, news headlines).</li><li>Try hybrid models (ARIMA + LSTM).</li></ul><p><strong>👉 Want to try it yourself?</strong> The source code is available on<a href="https://github.com/zooviee/Stock-Trend-Prediction/blob/main/Stock%20Price%20Prediction%20.ipynb"> <strong><em>GitHub</em></strong></a> and the app is live on <a href="https://zooviee-stock-trend-prediction-app-lmc5tj.streamlit.app/"><strong><em>Streamlit</em></strong></a><strong><em>.</em></strong></p><p>💡 The Streamlit app lets you enter <strong>any stock ticker symbol</strong> (like AAPL, GOOGL, or TSLA) and instantly view a summary of the stock’s performance from 2015 to 2024. You’ll get statistical insights like average prices, volume trends, and a visualized closing price chart. Give it a spin and explore stock trends on your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86R63VLU35NXXQRXHp89JQ.jpeg" /></figure><p>Connect with me:</p><p><a href="http://www.linkedin.com/in/seyi-a-852314184"><strong><em>LinkedIn</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90eeb6f2bfb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nature, Neural Nets, and a Shortcut to Smarter Models with Transfer Learning]]></title>
            <link>https://medium.com/@seyiakinsanya3/nature-neural-nets-and-a-shortcut-to-smarter-models-with-transfer-learning-46a700c79904?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a700c79904</guid>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 09:03:36 GMT</pubDate>
            <atom:updated>2025-07-07T09:14:19.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*0KLT9v_xUAth0fCsvcfOqQ.jpeg" /><figcaption><strong>Nature Scene</strong></figcaption></figure><p>Over the past week, I’ve been diving into the fundamentals of artificial neural networks — learning how these layered models mimic the human brain to recognize patterns in data. I also explored data augmentation techniques, which artificially expand datasets through transformations like flipping, rotating, or zooming images. But what truly stood out was transfer learning — the concept of reusing pre-trained models as a starting point for new tasks, saving both time and computational effort.</p><p>Armed with this knowledge, I set out to build a Nature Vision Classification App. My goal was simple: help users identify natural scenes (like forests, mountains, and glaciers) using machine learning. The idea was exciting, the dataset was rich, and I was motivated. But soon, I hit a wall. Training a deep learning model from scratch was slow and demanding, and even with thousands of images, the model struggled to generalize.</p><p>That’s when I fully appreciated the power of transfer learning. It turned out to be the true driving force behind this project — accelerating training, improving accuracy, and turning a slow-learning model into a smart, responsive application.</p><h3>🌱 What Is Transfer Learning (and Why Should You Care)?</h3><p>Imagine teaching a child to recognize animals. If they already know what a cat looks like, it’s easier to teach them about tigers. Transfer learning works the same way. Instead of training a model from scratch, we <strong>start with a pre-trained model</strong> — one that already knows how to “see” thanks to millions of images it’s seen during training — and <strong>fine-tune it</strong>for our specific use case.</p><p>In my case, I used several pre-trained models like <strong>Xception, InceptionV3</strong>, and <strong>VGG16</strong> which was originally trained on the <strong>ImageNet </strong>dataset (think: over 14 million images). All I had to do was <strong>retrain the last few layers</strong> to recognize the categories in the intel-image dataset.</p><h3>🚀 Why Transfer Learning Was a Game-Changer</h3><p>Here’s what transfer learning gave me:</p><ol><li><strong>Speed</strong>: What would’ve taken days to train now took a few hours.</li></ol><p><strong>2. Accuracy</strong>: The model had a “head start” and produced better results even with fewer samples.</p><p><strong>3. Scalability</strong>: I could deploy the model on Streamlit and update it easily without needing a supercomputer.</p><p><strong>4. Reduced Overfitting</strong>: With a smaller dataset, training from scratch would’ve led to overfitting. Transfer learning helped the model generalize better.</p><h3>🌍 Beyond the Code: Reaching Real Users</h3><p>Thanks to transfer learning, I was able to build a robust and interactive app — one that can be used by nature enthusiasts, educators, or anyone curious about the world around them. And I did it without needing a massive dataset or cloud GPUs.</p><p>The beauty of transfer learning is that it levels the playing field. Whether you’re a student, a solo developer, or part of a small team — you can build powerful AI models with limited resources.</p><h3>💡 Final Thoughts</h3><p>Transfer learning isn’t just a shortcut — it’s a smarter way to build and deploy machine learning solutions. For projects like Nature Vision Classification, it’s the difference between <strong>“just a project”</strong> and <strong>“a deployable, impactful application.”</strong></p><p>So before diving into building an image classifier from the ground up, ask yourself: could transfer learning fast-track your results and save you from reinventing the wheel?</p><p><a href="https://github.com/zooviee/nature_vision_classification"><strong><em>GitHub Repository</em></strong></a></p><p><a href="http://www.linkedin.com/in/seyi-a-852314184"><strong><em>LinkedIn</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a700c79904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Engineering & BigQuery: A Friendly Intro to Smarter Data]]></title>
            <link>https://medium.com/@seyiakinsanya3/feature-engineering-bigquery-a-friendly-intro-to-smarter-data-d5f3718c5678?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f3718c5678</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 20:48:40 GMT</pubDate>
            <atom:updated>2025-06-22T21:01:46.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQ2yLnBOetnEcR4wvtKj0g.png" /><figcaption><em>Feature engineering transforms raw data into predictive signals</em></figcaption></figure><p>Feature engineering is the art of transforming raw data into meaningful features that improve machine learning model accuracy and performance. The guiding principle is simple:</p><blockquote>A <strong>feature</strong> is just a piece of information about something you’re trying to predict.</blockquote><blockquote>For example, if you’re trying to predict a house’s price, features could be the <strong>size of the house</strong>, the <strong>number of bedrooms</strong>, or the <strong>year it was built</strong>. Each feature is like a clue that helps your model make a better prediction.</blockquote><blockquote>So, a feature is useful only if your model can understand how that clue connects to the final answer (the target)</blockquote><p>For example, linear models like Linear Regression can only learn linear relationships. So, if the true relationship is non-linear (e.g., age vs. income — income grows rapidly in early career but plateaus later), you must transform features (e.g., using techniques like log, square root, or polynomial terms) to make them linearly related.</p><p>Another notable example involves tree-based models which may not know “morning” and “evening” are different unless you engineer a time-of-day feature from a timestamp.</p><p>If your model can’t naturally learn certain relationships, you can create them through feature transformations and engineering. As you build your feature set, consider what additional information would help your model perform at its best.</p><h3>How to Discover Good Features</h3><ol><li><strong>Check Data Documentation</strong>: Many datasets (e.g., on Kaggle) include descriptions explaining what each column means.</li><li><strong>Domain Knowledge: </strong>Research the problem. For example: <em>In real estate, </em><strong><em>price per sqft</em></strong><em> may be more predictive than t</em><strong><em>otal square footage</em></strong><em>. In e-commerce, </em><strong><em>time since last purchase </em></strong><em>could be more useful than raw </em><strong><em>transaction count</em></strong><em>.</em></li><li><strong>Mutual Information vs. Correlation</strong>: Correlation measures linear relationships (e.g., Pearson’s <strong>r</strong>). Mutual Information (MI) detects <em>any</em> relationship (non-linear, categorical).</li></ol><h3>Principal Component Analysis</h3><p>Clustering groups data points by similarity, while PCA (Principal Component Analysis) breaks down the variation in your dataset. PCA is powerful for uncovering key patterns and can even help generate more meaningful features.</p><p>You can leverage PCA for feature engineering in two ways:</p><ol><li>As an exploratory tool to understand your data’s structure.</li><li>By using the principal components directly as input features for your model.</li></ol><h3>Processes Involved in Feature Engineering</h3><p>Feature engineering in machine learning involves five key steps:</p><ol><li>Feature Creation (Designing new features)</li><li>Feature Transformation (Modifying existing features)</li><li>Feature Extraction (Reducing dimensionality)</li><li>Feature Selection (Choosing the most relevant features)</li><li>Feature Scaling (Normalizing numerical data)</li></ol><p>This process is iterative — experimentation and testing are crucial to finding the optimal feature set for a given problem. Ultimately, a model’s performance hinges on the quality of its features, making feature engineering one of the most impactful steps in machine learning.</p><h3>Techniques Used in Feature Engineering</h3><p>The following are some of the commonly used feature engineering techniques:</p><ol><li><strong>One-Hot Encoding</strong>: One-hot encoding transforms categorical data into a numerical format that machine learning algorithms can process. This method creates new binary (0/1) columns for each category within a feature.</li></ol><p>For example: For a “Color” feature with values [Black, White], one-hot encoding generates two new columns:</p><blockquote>Color_Black: 1 if Black, 0 otherwise</blockquote><blockquote>Color_White: 1 if White, 0 otherwise</blockquote><p>2. <strong>Target Encoding: </strong>Replaces categories with the mean target value (e.g., replacing “Region” with average sales in that region). Great for high-cardinality features but can lead to overfitting — use smoothing or cross-validation.</p><p>3. <strong>Binning</strong>: Binning is a technique that converts continuous variables into categorical ones by dividing their range into discrete intervals called bins. Each bin represents a specific value range and is assigned a categorical label. For example, a continuous “Age” variable ranging from 18 to 80 could be binned into categories like 18–25, 26–35, 36–50, and 51–80, with each range treated as a distinct group. This approach helps simplify complex numerical data, handle outliers, and reveal patterns that might be harder to detect in raw continuous form.</p><p>4. <strong>Scaling</strong>: The most common scaling techniques are standardization and normalization. Standardization scales the variable so that it has zero mean and unit variance. Normalization scales the variable so that it has a range of values between 0 and 1.</p><h3>Getting Started with SQL in BigQuery: A Quick Guide for Beginners</h3><p>Google BigQuery is a powerful cloud data warehouse designed for analyzing massive datasets using SQL — the standard language for working with data. If you’re already familiar with SQL basics, getting started in BigQuery is easy. Here’s a quick overview to help you dive in.</p><ol><li><strong>Understanding the Table Format</strong></li></ol><p>In BigQuery, tables are organized using the format:</p><pre>`project_id.dataset.table`</pre><p>Always wrap it in backticks to avoid syntax issues, especially when using public datasets.</p><p>Example:</p><pre>SELECT *<br>FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips`<br>LIMIT 10;</pre><p>2. <strong>Writing Queries with Flexibility</strong></p><p>You can filter, calculate, group, and sort data just like in standard SQL:</p><pre>SELECT <br>  start_station_name,<br>  COUNT(*) AS trip_count,<br>  AVG(duration_minutes) AS avg_trip_duration<br>FROM `my_project.bike_data.trips`<br>WHERE start_time BETWEEN &#39;2025-06-01&#39; AND &#39;2025-06-07&#39;<br>GROUP BY start_station_name<br>ORDER BY trip_count DESC;</pre><p>3. <strong>Saving Query Results to a New Table</strong></p><p>To save your results:</p><pre>CREATE OR REPLACE TABLE `my_project.bike_data.weekly_summary` AS<br>SELECT ...</pre><p>This is useful for building reports or reusable tables.</p><p>4. <strong>Performance and Cost Tips</strong></p><p>BigQuery charges based on the amount of data <strong>scanned</strong>, not the number of rows returned. To reduce cost:</p><ul><li>Use SELECT specific_columns instead of SELECT *.</li><li>Filter with WHERE clauses early.</li><li>Partition large tables by date when possible.</li></ul><p>5. <strong>Explore Public Datasets</strong></p><p>BigQuery provides free public datasets for practice and exploration. You can find them under bigquery-public-data in your BigQuery UI.</p><h3>✅ Final Thoughts</h3><p>SQL in BigQuery feels familiar but gives you massive analytical power. Whether you’re querying millions of rows or building dashboards, it’s a great tool for modern data workflows. If you’re comfortable with SQL, you’re already halfway there. BigQuery just scales it up.</p><p>That’s it — clean relationships, thoughtful encodings, and a few concise SQL patterns will take you a long way in both modeling and BigQuery.</p><p><strong>Connect with me:</strong></p><ul><li><a href="https://www.linkedin.com/in/oluwaseyi-akinsanya-852314184">LinkedIn</a></li><li><a href="https://github.com/zooviee">GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f3718c5678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistency, Curiosity, and Code: What Revisiting the Basics Taught Me About Becoming a Data…]]></title>
            <link>https://medium.com/@seyiakinsanya3/consistency-curiosity-and-code-what-revisiting-the-basics-taught-me-about-becoming-a-data-b8a374ab651b?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8a374ab651b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[curiosity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 04:13:33 GMT</pubDate>
            <atom:updated>2025-06-15T04:13:33.423Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Consistency, Curiosity, and Code: What Revisiting the Basics Taught Me About Becoming a Data Scientist</strong></h3><p>When you’re doing a master’s in data science, there’s a quiet pressure to always be “doing something advanced” — deep learning, big models, or shiny dashboards. But recently, something unexpected helped me feel more like a real data scientist: going back to the basics.</p><p>This article is part of my journey to build visibility and stay consistent — something my mentor encouraged me to do. Writing this is not just a reflection, but a form of <strong>online accountability</strong>. Here’s what revisiting Python, Pandas, and data visualization taught me — through a more focused, intentional lens.</p><h4><strong>🐍 Python: A Language for Structured Curiosity</strong></h4><p>Python is like the universal remote for data. It is often one of the first tools we meet in data science. But it’s easy to treat it like a to-do list: learn lists, check. Loops, check. Functions, check. I started with the basics: variables, lists, loops. It felt like I was just typing syntax without meaning — until</p><p>for item in list: became second nature.</p><p>Imagine you’re organizing your closet. Each shirt has a tag: color, size, brand. Python lets you go: <em>“Show me all the blue shirts from Nike.”</em></p><blockquote><em>for shirt in closet: if shirt.color == &#39;blue&#39; and shirt.brand == &#39;Nike&#39;: print(shirt)</em></blockquote><blockquote>Python helped me realize that <strong>code is just structured curiosity.</strong> It’s asking questions and getting answers — fast.</blockquote><h4>🐼 Pandas: The Excel You Didn’t Know You Needed</h4><p>Pandas is the library that is used for data manipulation. Feel like I have a toolbox that can tidy up any chaos and pull out insights on command. It helps you load, clean, filter, and reshape data with ease. Imagine you’re handed a customer list in Excel. Some names are misspelled, ages are missing, and purchase amounts are in weird formats.<br>With Pandas, I learned to:</p><ul><li>Fix spelling with .replace()</li><li>Remove missing values with .dropna()</li><li>Summarize spending with .groupby()</li></ul><h4>📊 Visualization: The Bridge Between Data and Action</h4><p>Numbers are useful, but <strong>pictures make people care</strong>. Let the numbers speak through insightful visuals.</p><p>Imagine you’re a café owner. Sales are down. You plot a bar chart of daily revenue and realize:</p><blockquote><em>“Mondays are always dead.”<br></em>The numbers didn’t lie — they had something to say.</blockquote><p>From histograms to line charts, I learned that visualization is <strong>how data talks to humans</strong>. A well-placed plot can influence decisions more than a 10-page report.</p><h4>🎯 Why This Article Exists</h4><p>This isn’t just a recap of what I’ve learned — it’s a reminder to myself (and maybe to you): You don’t have to do advanced things to be taken seriously in data science.</p><p>✅ <strong>Don’t memorize syntax — build intuition</strong><br> Ask real-world questions and try to solve them.</p><p>✅ <strong>Always visualize before you analyze (Exploratory Data Analysis)</strong><br> It helps you find patterns, outliers, and even errors.</p><p>✅ <strong>Communicating patterns simply</strong><br> Simplicity is not lack of depth — it’s clarity.</p><p>Those are <strong>deep skills</strong>, not just beginner ones.</p><p>My mentor reminded me that building a career isn’t just about projects — it’s about <strong>visibility</strong> and <strong>consistency</strong>. So here I am, writing. Not because I’ve mastered anything, but because I’m practicing in public.</p><h4>💡 Final Thought</h4><p>Are you thinking about getting into data science or are you in the early stages of your data science journey? Don’t rush to be impressive. Learn to be curious, clear, and consistent. The impact comes later — but the habit starts now. If you can think clearly, ask curious questions, and learn tools like Python and its packages like Pandas, Matplotlib, and Seaborn— you’re already on the path.</p><p>And if you’ve ever made a shopping list, sorted your wardrobe, or tracked your steps — you’ve already practiced data science. You just didn’t call it that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8a374ab651b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behavioural Customer Segmentation with KMeans: A Practical Walkthrough]]></title>
            <link>https://medium.com/@seyiakinsanya3/behavioural-customer-segmentation-with-kmeans-a-practical-walkthrough-0b0484d6e158?source=rss-4dac8d180f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b0484d6e158</guid>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[python-data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kmeans-clustering]]></category>
            <dc:creator><![CDATA[Oluwaseyi Akinsanya]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 03:33:19 GMT</pubDate>
            <atom:updated>2025-04-26T03:33:19.776Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Have you ever wondered how businesses know which customers are big spenders and which ones need a push? In this project, I used KMeans clustering to identify behavioural segments based on two simple features: <em>income</em> and <em>spending score.</em></p><h4>Objective</h4><p>My aim was to practice customer segmentation using unsupervised learning techniques — not for a business case, but purely for educational purposes and to deepen my understanding of clustering algorithms.</p><h4><strong>The Dataset</strong></h4><p>For this project, I used a publicly available customer dataset from the <a href="https://github.com/DataThinkers/Datasets/blob/main/DS/Mall_Customers.csv">Data Thinkers GitHub repository</a> which includes demographic and behavioural data of mall customers. While the full dataset contained additional details like customer ID, age, and gender, I focused on two core features:</p><ul><li><strong>Annual Income (k$)</strong> — an indicator of a customer’s financial capacity</li><li><strong>Spending Score (1–100)</strong> — a metric representing customer spending behaviour and engagement</li></ul><p>These two variables were ideal for behavioural segmentation, offering a simple yet powerful view into how customers spend relative to their income.</p><h4>Exploratory Data Analysis (EDA)</h4><p><strong><em>Histogram Plots</em></strong></p><p>The <strong>Annual Income (k$)</strong> histogram shows that customer income is fairly spread out between $15k and $140k, but with noticeable concentrations around $60k and $75k. The distribution is slightly right-skewed, meaning there are fewer customers with very high incomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sRc1P_tswQXb3RjRI0O5Q.png" /></figure><p>The <strong>Spending Score (1–100)</strong> histogram reveals a more diverse pattern: while some customers have low or high spending scores, many are concentrated around the middle range (40–60). There are also multiple peaks, suggesting that customers exhibit distinct spending behaviours rather than following a single trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ameeQh9Znm2jU_0ytKHujQ.png" /></figure><p><em>Boxplots</em></p><p>The <strong>boxplot of Annual Income (k$)</strong> shows that the middle 50% of customers earn between roughly $40k and $75k. The distribution is fairly symmetric, but there is one notable outlier above $130k, indicating a customer with exceptionally high income.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5_Z_RJz72Ur0G6DHGIRIg.png" /></figure><p>The <strong>boxplot of Spending Score (1–100)</strong> suggests that most customers have a spending score between 40 and 60. The data is more spread out compared to income, but without extreme outliers, indicating that customer spending habits are more balanced across the range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTZnvVdssOR7-AjfyABThA.png" /></figure><blockquote><em>“While minor skewness and a few outliers were observed in the data, for the purpose of this educational project, I proceeded without applying outlier treatment, focusing on the natural patterns within the majority of the customers.”</em></blockquote><h4>Choosing the Right Number of Clusters</h4><p>I plotted the Within-Cluster Sum of Squares (WCSS) for K=1 to 10, and identified an elbow at K=5 as the optimal number of clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVqcyBFqosznqcCaHOkp-g.png" /></figure><h4>Clustering with KMeans</h4><blockquote><em>“K-Means clustering partitions data into K groups by minimizing the distance between data points and their nearest cluster center.”</em></blockquote><p>The code used to train the clustering algorithm is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rygwGnSWnijPIQ6zfE2DFA.png" /></figure><p>Visualizing the clusters using a scatter plot. Each point represents a customer (based on features like <strong>Annual Income</strong> and <strong>Spending Score</strong>). Points are colored by their cluster group (Cluster 1, Cluster 2, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeSc9nu-Twx4mMzQ9_jOzw.png" /></figure><h4><strong>Interpreting the Segments</strong></h4><p>After applying K-Means clustering to the selected features — <strong>Annual Income</strong> and <strong>Spending Score</strong> — the model segmented customers into distinct groups based on their financial behaviour. Each cluster represents a unique customer profile, capturing spending habits relative to income levels.</p><ul><li><strong>Cluster 1:</strong><br> <strong>“Average Spenders”</strong><br> <em>(Customers with medium annual income and medium annual spend)</em></li><li><strong>Cluster 2:</strong><br> <strong>“High Rollers”</strong><br> <em>(Customers with high annual income and high annual spend)</em></li><li><strong>Cluster 3:</strong><br> <strong>“Value Shoppers”</strong><br> <em>(Customers with low annual income but high annual spend)</em></li><li><strong>Cluster 4:</strong><br> <strong>“Budget-Conscious Shoppers”</strong><br> <em>(Customers with high annual income and low annual spend)</em></li><li><strong>Cluster 5:</strong><br> <strong>“Frugal Customers”</strong><br> <em>(Customers with low annual income and low annual spend )</em></li></ul><h3>Bonus: Building a Simple GUI for Customer Segmentation</h3><p>As an extra touch, I created a basic <strong>Tkinter-based graphical user interface (GUI)</strong> that allows users to input a customer’s annual income and spending score, then instantly predicts the customer’s segment based on the trained K-Means model.</p><p>This lightweight app is especially useful for quick experimentation or demos without writing code every time.</p><h3>💡 How It Works:</h3><p>The user enters two values: <strong>Annual Income</strong> and <strong>Spending Score</strong>.</p><p>When the <strong>“Predict”</strong> button is clicked, the app:</p><ul><li>Loads the trained K-Means clustering model,</li><li>Feeds the input into the model,</li><li>Displays the predicted <strong>customer segment</strong> and a brief description of that segment’s behavior.</li></ul><p>Here’s a quick preview of the interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWIWsteDjzl_hb5xpEYBbw.png" /></figure><p>This kind of user-friendly tool can be easily extended or embedded in real-world applications, helping businesses classify new customers in real time.</p><h3>Conclusion</h3><p>Behavioural customer segmentation, even with just two simple features like income and spending score, can reveal powerful patterns that drive smarter business decisions. By grouping customers based on real-world behaviour, companies can personalize experiences, target marketing more effectively, and build stronger customer relationships.</p><p>This project shows how accessible unsupervised learning can be — and I encourage you to try clustering on your own dataset. You might be surprised at what you discover. 🚀</p><p><em>If you enjoyed this, follow me for more data science walkthroughs!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b0484d6e158" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>