<?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 Jay on Medium]]></title>
        <description><![CDATA[Stories by Jay on Medium]]></description>
        <link>https://medium.com/@dlifeofjay?source=rss-4f3c86d3fc5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HiHx2xIIUnBH634EQBTVYA@2x.jpeg</url>
            <title>Stories by Jay on Medium</title>
            <link>https://medium.com/@dlifeofjay?source=rss-4f3c86d3fc5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:56:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dlifeofjay/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[Using Consumer Demand Behavior and Machine Learning to Determine Optimal Pricing]]></title>
            <link>https://medium.com/@dlifeofjay/using-consumer-demand-behavior-and-machine-learning-to-determine-optimal-pricing-a7ba1ea55a8a?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7ba1ea55a8a</guid>
            <category><![CDATA[business-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 13:23:46 GMT</pubDate>
            <atom:updated>2026-07-12T13:43:44.125Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier this week I was curious. Curious on the question “How does business determine the best price to place on their products at the right time?”, The kind of price that gives them the highest possible profit and at the same time helps them keep their market share.</p><h4><strong>THE PROBLEM</strong></h4><p>Here are the key questions:</p><ol><li>Should we put a low price on a product to attract more customers and increase sales?</li><li>Should we put a high price so we can make more profit?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDxbG9gzlbD5eHT2aO8N2g.png" /><figcaption>Image by ChatGPT</figcaption></figure><p>But here is the thing, The primary aim of most businesses is actually to make money (profit) right? and pricing efficiently is a key driver in actually attaining this primary goal.</p><p>The problem is, if a business decides to price too low in an attempt to make more sales, they might be losing more money without realizing it and if they decide to price high in an attempt to increase profit, there is a high risk of losing sales, economics 101, right? Let me explain deeply.</p><p>The thing is determining the right price of a typical product or service is mostly influenced by the <strong>customers behavior</strong>, what I mean is an average person will buy more of his average items if they are cheap and buy less if they become expensive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwQ2KGmmfZTGXgGjP__1lg.png" /><figcaption>Law of Demands for Normal Goods</figcaption></figure><p>For a business, the solution to this is to:</p><blockquote>Find the right price that makes me the best profit and at the same time keeps my market share.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do1tGPhOCkmal-2ajgzB8Q.png" /><figcaption>Relationship Between Price and Profit</figcaption></figure><p>The plot above simply shows that when price was low, we made low profit because the price to cost margin (markup ratio) was too close, but demand was high. And when price was high, we made low profit because demand was low and wasn’t able to increase sales. The green dot shows a point where we actually make profit with a certain price. Our goal is to find that certain price.</p><p><strong>THE SOLUTION</strong></p><p>The problem is, “How do we actually find this price?”. Because best way to find this price is to be able to tell how customers will react to different prices at different time given certain conditions, but we don&#39;t want to test that in the real world and risk losing customers, do we?</p><p>But AI/ML can! you see, machine learning is the perfect solution for this scenario because it can determine the number of sales if given certain factors, the goal is to find a way for the model not to be 100% accurate but very close to real world cases, and once that is possible, we can simulate different pricing scenarios in order to catch that perfect price that actually makes us money and at the same time, keep customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHbwJ654LXI_LUQffUbJeQ.png" /><figcaption>Demand Prediction Performance on test dataset</figcaption></figure><p>What determines the success of this is the result of the above image. By knowing this, we can then simulate different prices and find that exact price that makes the highest profit.</p><p><strong>Observe The Result Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnA4tzafoxlC8CRJ8CEmaQ.png" /><figcaption>Result Dashboard</figcaption></figure><p>The above dashboard simulated different price point from the original product price, then recommends the best price for that particular product for that point in time that actually gives the most profit.</p><p>The dashboard shows that the original price was between 150 and 160, generating a profit of around 42k for that particular week. However, if we increase the price to the optimal price of 191.47, which is a 24% increase over the current price, the projected profit rises to almost 50k for the same week. This allows the business to generate more profit by charging the optimal price rather than relying on its current pricing strategy.</p><h4><strong>CONCLUSION</strong></h4><p>This project allowed me showcase basic economic principle and apply it to a well-known business problem. It can be applied to retail, e-commerce, restaurants, hospitality, airlines, consumer goods or any kind of businesses where pricing affects demand and also actually wants to make more money.</p><p>Link To Dashboard: <a href="https://price-optim.streamlit.app/">https://price-optim.streamlit.app/</a></p><p>Github Repo Link: <a href="https://github.com/dlifeofjay/Price-Optimization">github.com/dlifeofjay/Price-Optimization</a></p><p>Thanks For Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7ba1ea55a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marriot vs Radisson Blu: Using Data Science to Find the Competitive Gaps in Lagos Premium Hotel…]]></title>
            <link>https://medium.com/@dlifeofjay/marriott-vs-69ce85ece087?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ce85ece087</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 17:14:13 GMT</pubDate>
            <atom:updated>2026-07-01T08:46:29.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Marriott vs. Radisson Blu: Using Data Science to Find the Competitive Gaps in Lagos Premium Hotel Rivalry</h3><h3>Introduction</h3><p>Marriott and Radisson Blu are two premium hotels located in the Government Reserved Area (GRA), Ikeja, Lagos Nigeria. Situated just 1,084 meters apart, they directly compete in the same market, offering similar services including accommodations, food &amp; beverage, events, conferences, and wellness facilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TYT0mJOIxqes9zZ9cIklQ.png" /><figcaption>Blue for Marriott, Red for Radisson Blu</figcaption></figure><p>This article uses data science techniques to analyze 1,240 Google reviews (from 2017 to June 2026) to uncover what guests truly think about these hotels and what it means for their competitive positioning.</p><h3><strong>What Do Customer’s Expect?</strong></h3><p>In this article, we explore customer sentiment through word clouds, VADER sentiment analysis, and zero-shot classification AI model to identify the key drivers of satisfaction and dissatisfaction for both hotels.</p><h4><strong>Lagos Marriott Hotels Ikeja</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YxkI3pHfRcma7JKAX30NA.jpeg" /><figcaption>Marriott Hotel</figcaption></figure><p>Lagos Marriott Hotel Ikeja commenced operations on 19 May 2021 and positions itself as a premium hospitality brand. An analysis of early customer reviews reveals that, even before full operational maturity, guests expressed strong positive sentiments toward the hotel’s architectural design, luxurious ambience, and aesthetically pleasing interior and exterior layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTUXnBDcPo8jXLuQK3PmUQ.png" /><figcaption>Pre 2021 Reviews</figcaption></figure><p><strong>Temporal Insights</strong></p><p>From the year of operation till date, a total of 1,237 reviews were posted, where the year of opening itself (2021) has the lowest number of reviews and the following year (2022) has the highest number of reviews overall, this could be the effect of growing brand awareness and a positive marketing effect.</p><p>June has recorded a constant high rate of reviews out of all months over the years from 2022 till 2025, A hypothesis was explored that the recurring spike in June reviews was driven by annual events. However, the available review data did not provide sufficient evidence to support this explanation. Additionally, reviews are posted most frequently on Thursdays to Sundays, indicating higher guest activity and engagement during the latter part of the week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhYO_KGGcAkk0dVFZV-t6g.png" /><figcaption>Temporal Plots</figcaption></figure><p><strong>What Guests are Really Saying:</strong></p><p>Customer reviews center primarily around five key areas: rooms, food, staff, service, and the overall hotel experience. These themes reflect the core aspects guests value most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7jUS_PAUgW_FfsIQs7sBA.png" /><figcaption>Overall Word Cloud</figcaption></figure><p>The overall word cloud shows that customers frequently discuss the hotel’s core offering both negatively and positively. However, some varies in word repetitions, for example, hotel rooms are frequently discussed positively than negatively, same for food. And also, services are also mentioned in most negative review discussions than in most positive discussions, same for staff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9xN8gKjOeFPcMMy14_7RQ.png" /><figcaption>Negative &amp; Positive Review Word Count</figcaption></figure><p>Out of all complaints, customers are most dissatisfied with room related experience and service delivery. Staff-related issues recorded the least number of complaints.</p><p>However, room and food received the highest volume of positive reviews, highlighting their importance as key strengths for the hotel.</p><p>The percentage of negative reviews by category relative to the total is as follows:</p><ul><li>Services — 9%</li><li>Room — 9%</li><li>Staff — 8%</li><li>Food — 5%</li></ul><p>Overall, while service delivery and room related experience remain the primary areas of customer dissatisfaction, food emerges as one of the key strengths. It consistently ranks among the highest in positive mentions and one of the lowest in negative complaints, making it one of the hotel’s strongest competitive advantages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJLAgDh6izntvuVZYIKOhg.png" /><figcaption>counts of classified reviews in negative and positive</figcaption></figure><p>The overall volume of negative reviews remains minimal compared to the significantly higher number of positive reviews.</p><p>As of 2026, most complaints are room related, with a total of (8 reviews). This is followed by service-related complaints (2 reviews) and staff-related complaints (1 review). Notably, there were zero negative food-related reviews in 2026, further reinforcing food as one of the recent hotel’s key strengths.</p><p>In contrast, positive reviews show consistent praise across all major categories in 2026, most especially in room and food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFs6aVDYRdaNQgVUeJtaGg.png" /><figcaption>Month-Year review frequency of negative and positive reviews</figcaption></figure><h4>Radisson Blu Hotels Ikeja</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*k1c1-4H7-uS-FXBXk6g5sg.jpeg" /><figcaption>Radisson Blu Hotels</figcaption></figure><p>Radisson Blu Ikeja commenced operations in January 2018, several years earlier than its direct competitor, Marriott. The hotel positions itself to offer similar value and premium services as Marriott, competing directly in the upscale hospitality segment in Ikeja.</p><p><strong>Temporal Insights</strong></p><p>2025 recorded the highest number of reviews for Radisson Blu Ikeja, followed by 2024. Even though 2026 is still mid-year, the hotel has already seen a significant increase in review volume.</p><p>Similar to Marriott, Radisson Blu shows a consistent pattern of high review activity in June across all years from 2018 to 2025 but as of 2026, May seems to be the current highest. Customers seem to prefer review engagements early in the week (Sunday &amp; Monday)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5q4EEvGhHEFNgVJ_8vYsgA.png" /><figcaption>Temporal Plots</figcaption></figure><p><strong>What Guests are Really Saying:</strong></p><p>Discussions in reviews centers mostly around words like room, staff, services, food, how nice and great the hotel is in general which reflects what customers evaluate experience on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6LQRMXx8_yj5haL4hQYww.png" /><figcaption>Overall Word Cloud (Radisson Blu)</figcaption></figure><p>These words appeared frequently in both positive and negative kind of reviews, giving a strong suggestion that customers primarily evaluate their experiences based on these core service dimensions. However, the larger prominence of words such as room and service in positive reviews compared to negative reviews indicates that these aspects of the hotel’s offerings receive more praise than criticism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVFWkVPmffeR6nOnGZyBKg.png" /><figcaption>Negative &amp; Positive Review Word Count (Radisson Blu)</figcaption></figure><p>However, the relatively greater occurrence of food-related terms and the word guest in negative reviews suggests areas of customer dissatisfaction. Further investigation revealed that these terms frequently appeared in reviews describing poor service delivery, food quality issues, and operational shortcomings, indicating that these areas may require managerial attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uhyWsMbgvzjDvFB8luV_g.png" /><figcaption>Example of food related complaint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xh5jzmrfGZmmeuB1mikpJA.png" /><figcaption>Example of Negative Reviews with the word Guests</figcaption></figure><p>Negative reviews were primarily driven by service and room related complaints, with staff related complaints occurring less frequently.</p><p>Positive reviews were dominated by praise for food quality and overall service delivery. This suggests that although the majority of customers had positive experiences, some customers encountered service failures that adversely affected their satisfaction.</p><p>The percentage of each class negative review to it overall reviews are:</p><ul><li>Room — 8%</li><li>Services — 6%</li><li>Food — 4%</li><li>Staff — 4%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnpg5S3c_kotmT5p-Eblnw.png" /><figcaption>Counts of Classified Reviews in Positive and Negative (Radisson Blu)</figcaption></figure><p>The overall counts of negative reviews remain low compared to that of positive reviews.</p><p>As of 2026, services remain the main area of concern among all complain category, they are (6 counts) of complaints followed by room related complaint (4), then food related complaints.</p><p>Relatively, there have been praises by other customers regarding these review segments</p><p>Overall, service delivery appears to represent the primary source of customer dissatisfaction at Radisson Blu Ikeja.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CIj-DmSa4ECk3aAHBFLBw.png" /><figcaption>Month-Year negative and positive reviews</figcaption></figure><h3>SWOT Analysis</h3><p><strong>Strength</strong></p><p>Food stands out as one of the key strengths for <strong>Marriott Hotels</strong> because of the high praise it receives, and the low count of negative reviews recorded. It has the lowest negative review percentage (5%) out of the four customer evaluation criteria, and as of 2026, there have been zero food-related complaints, which strengthens its food-related advantage.</p><p><strong>Radisson Blu’s</strong> core area of strength is also food. It has the highest count of positive reviews out of all customer evaluation criteria, and also one of the lowest complaint percentages (4%). However, as of 2026, there have been 4 food-related complaints, which management should look into and address to maintain food as a strength going forward.</p><p>Overall, both hotels share the same core strength, but as of 2026, Marriott has the edge over Radisson on food, having recorded zero food-related complaints compared to Radisson’s four.</p><p><strong>Weakness</strong></p><p>One of <strong>Marriott’s </strong>main weaknesses is room-related complaints. It is the highest among all four complaint categories, with a 9% complaint rate. As of 2026, there have been 8 room-related complaints, making it the hotel’s core area of challenge.</p><p>A key issue at <strong>Radisson Blu</strong> is service delivery, which has affected both guest service and food service, as evident in the word count analysis. It carries a 6% complaint rate, room (8%) have also been an area of challenge. As of 2026, there have been 6 service-related complaints, followed by room-related complaints.</p><p>Overall, both hotels stand to gain an edge by improving the quality of their service delivery, strengthening their position in the hospitality industry.</p><p><strong>Opportunity</strong></p><p>The opportunity for both hotels lies in capitalizing on each other’s weaknesses. If <strong>Marriott </strong>strengthens its room issues, it can take advantage of <strong>Radisson’s </strong>services and room<strong> </strong>shortcomings, helping it retains customer satisfaction and reinforce its premium positioning. The same logic applies to Radisson Blu, which could capitalize on Marriott’s room-related weakness by emphasizing its own room quality.</p><p><strong>Threats</strong></p><p>Marriott faces a threat from Radisson Blu: if its room-related issues remain unresolved, guests dissatisfied with room quality may switch to Radisson, especially since rooms are not Radisson’s biggest weakness as of 2026.</p><p><strong>Dashboarding and Future Monitoring</strong></p><p>A Distilbert classification machine learning model was finetuned to be able to predict future reviews and packaged to a streamlit dashboard for easy management monitoring</p><p>App Link: <a href="https://marriott-dash.streamlit.app/">Streamlit</a></p><p>Link to Repo: <a href="https://github.com/dlifeofjay/Customer-Review-DS-ML/tree/main/data">Customer-Review-DS-ML/data at main · dlifeofjay/Customer-Review-DS-ML</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ce85ece087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Modelling with LSTM]]></title>
            <link>https://medium.com/@dlifeofjay/language-modelling-with-lstm-30dd4adf669c?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dd4adf669c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 16:12:26 GMT</pubDate>
            <atom:updated>2026-06-17T16:28:50.740Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>INTRODUCTION</strong></h3><p>If you opened this it either mean you are an AI/ML enthusiast or you just love to know how things work in general. How do i know? trust me, i’m both and you are about to enjoy a not so technical article.</p><p>Something happened few days ago when i was thinking out loud about modern day AI chatbots, thinking? “Since modern day chatbots or ‘AI Systems’ are just trying to predict the next token(s) based on the previous sequential tokens, have they actually tried using LSTM architecture for modelling before heading straight to Transformers architecture?”.</p><p>Firstly, let me start by explaining what LSTM is and how they work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*JHa_cqoqwRwf2NqQH_9NGw.png" /><figcaption>Visual Representation of LSTM Architecture</figcaption></figure><h4><strong>LSTM Explanation</strong></h4><p>LSTM short for (Long Short-Term Memory) was introduced to solve a big problem. What problem? The previously existing architecture for sequence-to-sequence modeling — RNN short for (Recurrent Neural Networks), had an extreme vanishing gradient problem. What do I mean by that? The way RNNs were built, they tend to remember information relating to the immediate inputs or the token just before the current one much better than earlier tokens.</p><p>For example, given tokens [1, 2, 3, 4, 5, 6], when predicting the next token, the RNN remembers information about tokens 5 and 6 much better than tokens 1 and 2.</p><p>So, how does LSTM solve this? While RNN has only 1 main component for its memory, LSTM has 4 key components that work together. This gives it a much better ability to remember information from much earlier tokens or values — not just the immediate previous ones.</p><h3>LSTM and Language Models</h3><p>Remember what I thought out loud? After doing some research, I found out that before the invention of the Transformer architecture in 2017, most language models were powered by LSTM. Although LSTM was really good for tasks like sentence completion, autocorrect, and short sentence generation, it wasn’t as effective as modern Transformers.<br>The main reason? Memory limitations.</p><p>What I’m saying is even though LSTM is much better than plain RNNs, it still forgets earlier tokens when the sequence gets very long. Because of this, it ends up predicting incorrect or unrealistic output.</p><h3>Let&#39;s Build a Language Model with LSTM</h3><p>Building a language model requires understanding of the fundamental steps of what machine learning models expects, in this section i will carry you along on how i trained a simple next word predictor using LSTM</p><p>First off, let me list and explain the steps for a one-word prediction model</p><ol><li>Data Gathering: Its general knowledge that data is the input of any model. Data gathering is an important task in the machine learning process, we need lots of textual data, be it pdfs, articles, books, etc, having in mind that the goal is to gather enough words, sentence etc for the model to grasp meaning of.</li></ol><pre># Import LSTM and &quot;Attention is All You Need&quot; paper<br>lstm = PdfReader(r&quot;C:\Users\USER\Downloads\LSTM.pdf&quot;)<br>ailyn = PdfReader(r&quot;C:\Users\USER\Downloads\AILYN.pdf&quot;)<br><br>text = &quot;&quot;<br><br>for i in lstm.pages:<br>    text += i.extract_text() + &quot;\n&quot;<br><br>for j in ailyn.pages:<br>    text += j.extract_text() + &quot;\n&quot;</pre><p>2. Data Cleaning. As much as data gathering is important, data cleaning is also equally important. There is a saying “garbage in, garbage out” what you give your model is what you get, rigorous data cleaning must take place because one of the reason an existing “AI company” is better than the other is how they clean their training data before the following tasks.</p><pre># Basic Text Cleaning<br>def clean_text(text):<br>    # Standardize common PDF ligatures<br>    text = text.replace(&quot;ﬁ&quot;, &quot;fi&quot;).replace(&quot;ﬀ&quot;, &quot;ff&quot;).replace(&quot;ﬂ&quot;, &quot;fl&quot;).replace(&quot;ﬃ&quot;, &quot;ffi&quot;)<br>    <br>    # Remove citations like [1] or [12, 15]<br>    text = re.sub(r&#39;\[\d+(?:,\s*\d+)*\]&#39;, &#39;&#39;, text)<br>    <br>    # Clean punctuation and lowercase<br>    clean = str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)<br>    text = text.translate(clean)<br>    # Output as list of words<br>    text = text.replace(&quot;\n&quot;, &quot; &quot;).lower().split()<br>    <br>    return text<br><br>text = clean_text(text)<br>print(text)</pre><p>3. Tokenization: This is simply taking the cleaned data, splitting it into words or sub words or even sentences ‘depending on the tokenizer you plan to use’, then converting it into numbers called tokens because computer can&#39;t process words. There are open-sourced tokenizers but i built one for practice.</p><pre># Word level tokenization<br>def tokenizer(tokens):<br><br>    # unique words<br>    unique_tokens = list(dict.fromkeys(tokens))<br>    <br>    # value assignment<br>    word_to_id = {word: idx for idx, word in enumerate(unique_tokens, start=1)}<br>    <br>    # Add UKN for incoming unknown words<br>    word_to_id[&quot;&lt;UKN&gt;&quot;] = 0<br>    <br>    # convert tokens to id<br>    data = [word_to_id.get(idx) for idx in tokens]<br>  <br>    return data, word_to_id<br><br>data, word_to_id = tokenizer(text)</pre><p>4. Sequencing: This is where we create the input and sample data. The idea is to take list of texts and predict the next in stages. For example, given the sentence “I want to eat”, we start by taking the “I want” as the first input to predict “to” as the first output then move to “want to” as the second input to predict “eat” as the second output. It all depends on the sequencing method you prefer.</p><pre># create window function and transform to array<br><br>def window(tokens, input_length, output_length):<br><br>    # Init list<br>    X_train = []<br>    y_train = []<br>    <br>    # loop through entire length of tokens after subtracting input and outputs and adding 1 so we wont go over available data length<br>    for i in range(len(tokens) - input_length - output_length + 1):<br><br>        # take from current loop number to input sequence + current loop number<br>        # e.g if loop=0 and input=30, from row 0 to 30+0<br>        X = tokens[i:input_length+i]<br>        <br>        # Take the value of the next row after X<br>        # e.g still using above values and target is 1 word prediction 0+30 to 30+1<br>        y = tokens[i+input_length:i+input_length+output_length]<br>        <br>        # Add them to the list in each loop<br>        X_train.append(X)<br>        y_train.append(y)<br><br>    # Return array<br>    return np.array(X_train, dtype=np.int32), np.array(y_train, dtype=np.int32).squeeze(-1)</pre><p>5. Tensors, Data Loading, Embeddings, Forward Pass Architecture and Training: You will carry out your entire pytorch process here by getting the data ready for the deep learning architecture.</p><p>The embedding part is also important, it takes each token then convert it to vectors (list of numbers or scalers) then feed those values to the model, by doing this the model tends to understand words better and generalizes which enables it to make accurate predictions.</p><p>A keynote is to treat this as a supervised learning task where the input will be number of unique tokens and output will also be the same.</p><p>Please refer to link to the notebook here:</p><p><a href="https://github.com/dlifeofjay/LSTM-Next-Word-Predictor">GitHub - dlifeofjay/LSTM-Next-Word-Predictor: This project simulates how olden days language models work using LSTM</a></p><h3><strong>Conclusion</strong></h3><p>After training my model suffered underfitting which main cause is expected to be the data and the basic preprocessing and tokenization carried out by me which led me to increase the epoch to 100 leading to severe overfitting. The model is deployed on streamlit for anyone testing</p><p>Link To the App Below:</p><p><a href="https://lstm-lm.streamlit.app/">https://lstm-lm.streamlit.app/</a></p><p>Next steps are to gather large amount of dataset with effective and rigorous cleaning and open-source tokenization to see it performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dd4adf669c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science & Business Problem Solving]]></title>
            <link>https://medium.com/@dlifeofjay/data-science-business-problem-solving-29f86d31dc7c?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f86d31dc7c</guid>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Fri, 29 May 2026 20:52:52 GMT</pubDate>
            <atom:updated>2026-05-29T20:52:52.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyMrGbCcKIzFMY9u2zthVw.png" /><figcaption>AI Generated Image</figcaption></figure><p><strong>What is Data Science all About?</strong></p><p>Data science is really not about building models and updating stacks and all, its about picking a problem from any domain going to the root of that problem by breaking the problems into bits and pieces and then finding the solution to those problems using data science techniques.</p><p><strong>What do Businesses Really Want?</strong></p><p>At its core, the primary goal of most businesses is to make profit. To truly understand business problems, we first need to understand what profit consists of.</p><p>Profit is fundamentally driven by two components:</p><ul><li>Revenue</li><li>Costs</li></ul><p>A business can improve profitability by:</p><ul><li>increasing revenue,</li><li>reducing costs,</li><li>or achieving both simultaneously.</li></ul><p>However, revenue and costs are influenced by far more than just product price, quantity sold, or production cost. They are affected by a wide range of business decisions and operational factors.</p><p>For revenue, important drivers include:</p><ul><li>pricing strategy,</li><li>customer purchasing behavior,</li><li>marketing effectiveness,</li><li>promotional campaigns,</li><li>product positioning,</li><li>customer experience,</li><li>and market demand.</li></ul><p>For costs, businesses must consider:</p><ul><li>production and operational expenses,</li><li>logistics and supply chain costs,</li><li>employee and administrative expenses,</li><li>maintenance and infrastructure costs,</li><li>customer acquisition costs,</li><li>and other expenses required to keep the business running efficiently.</li></ul><p><strong>How does Data Science Help Businesses Achieve their Primary Goal?</strong></p><ol><li>Increase Revenue: Data science solves this by identifying revenue drivers, look for ways to optimize it using data and data science statistical and modelling techniques</li><li>Reduce Cost: Data science helps businesses reduce costs by identifying key cost drivers, analyzing their root causes, and using data analysis, statistical methods, and machine learning models to optimize operations and minimize unnecessary expenses.</li><li>Improve Efficiency: Improving efficiency has to do with identifying tasks or workflow that makes business processes slow or inefficient and then using data, AI or ML for optimization, this has an indirect positive impact to both revenue growth and cost reduction.</li><li>Reduce Risk: Many business decisions involve significant uncertainty and risk. Data science helps reduce this risk by analyzing historical data and using statistical and predictive models to estimate the likely outcomes of decisions under different scenarios. This enables businesses to make more informed, data driven decisions with greater confidence.</li></ol><ul><li>Maximize Profit Sustainably: Data science helps businesses make decisions that ensure long-term profitability and business continuity. This includes applications such as cash flow prediction, customer retention analysis, and operational stability optimization.</li></ul><p><strong>Business Problem Bracket:</strong></p><p>Most business problems can be framed around a progression of key questions that support decision-making:</p><ol><li>What happened? — Analytics</li><li>Why did it happen? — Diagnostic Analysis</li><li>What will happen? — Predictive Modelling</li><li>What should we do? — Prescriptive Analytics</li><li>Can this be automated? — AI/ML Systems.</li></ol><p>Data science plays a central role in enabling businesses to answer these questions by transforming raw data into actionable insights, predictions, recommendations, and automated systems that support decision-making.</p><h3>Conclusion:</h3><p>All businesses aim to generate profit, yet many do not have clear answers to the challenges they face on a daily basis. By understanding business objectives and the key drivers that influence performance, data scientists can provide significant value by turning data into actionable insights that support better decision making, improved efficiency, and long term profitability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f86d31dc7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errors Are All You Need]]></title>
            <link>https://medium.com/@dlifeofjay/errors-are-all-you-need-a789f14d10c7?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a789f14d10c7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Wed, 06 May 2026 10:54:38 GMT</pubDate>
            <atom:updated>2026-05-06T10:54:38.409Z</atom:updated>
            <content:encoded><![CDATA[<p>Tackling uncertainties is still one of the core challenges across industries, where one wrong call or decision can have significant negative consequence for individuals and organizations alike. whether in financial markets, energy sector, sports analytics or healthcare.</p><p>Even the most advanced machine learning models can struggle to accurately determine the most likely outcome of a real-world event.</p><h3>WHY ERRORS?</h3><p>When evaluating regression models, we often focus on metrics such as MSE, MAE, and RMSE to assess overall model performance. However, these global metrics can sometimes hide important patterns within the model’s prediction errors, especially when certain errors are tied to specific conditions, factors, environments, or classes present in the dataset.</p><p>In many real-world problems, prediction errors are not entirely random. Instead, they may systematically occur under particular scenarios or for specific groups within the data. As a result, a model that appears accurate on average may still perform poorly or behave inconsistently under certain conditions in that same dataset.</p><p>Taking a highly volatile domain like sports analytics as an example, predicting full-time football scores can be extremely difficult due to the unpredictable nature of the game. The historical error patterns associated with a team may be significantly different with another team irrespective of their home advantage, making future predictions less reliable under certain conditions.</p><p>These differences can emerge from what the model has learned about each team’s playing style, consistency, tactical behavior, attacking strength, defensive structure, and overall match volatility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3D3T5_4NuH2UCBEXIG27Q.png" /><figcaption>Serie A Teams Error Patterns</figcaption></figure><p>The image above illustrates that different teams exhibit distinct error patterns. For example, looking at teams like Inter and Cagliari in the chart, a clear difference in error behavior emerges.</p><p>For Inter, the error pattern appears more volatile, with fluctuations ranging from approximately +4 goal underestimation to -1 goal overestimation, indicating higher variance and instability in the model’s predictions for that team. While Cagliari shows a much more stable error distribution, where most errors cluster around -1 or zero, suggesting the model either slightly overestimate the team or correctly predicts the actual score in many cases.</p><p>This contrast highlights how prediction errors can vary significantly across teams rather than following a uniform global pattern.</p><h3><strong>WHAT DO WE DO WITH THIS INFORMATION?</strong></h3><p>Once we identify and analyze the historical error patterns associated with each team, the next step is to leverage this information to better understand the uncertainty surrounding future predictions.</p><p>Rather than treating a model’s prediction as a single guaranteed outcome, the historical error behavior can be used to generate a range of realistic scenarios around that prediction. This allows us to estimate not only what the model expects to happen, but also how uncertain or volatile that prediction may be under different conditions.</p><h3>Experimental Application of the Technique Using Roma vs Fiorentina as a Case Study</h3><p>This past weekend, the actual scoreline for these 2 teams is <strong>4–0</strong> a win for Roma and the prediction from our Deep Learning Model was <strong>2–1</strong>.</p><p>The objective of this experiment is to analyze the range of possible goal outcomes and the probability for the match by combining the model’s predicted scoreline with the historical prediction errors from each team’s last 20 matches. Using these inputs, we construct a scenario-based probabilistic framework and compare the experimental results with the actual match outcome.</p><ol><li><strong>Grabbing the errors: </strong>The errors are part of the input for the success of this framework and experimentation; we focused on each team last 20 games asides from the match they played against each other</li></ol><p>The Code:</p><pre># 1. Getting Roma and Fior last games errors as a list<br><br># Grab roma last 20 games error asides from the one against fiorentina<br>roma = seriea[seriea[&quot;Team&quot;] == &quot;Roma&quot;][&quot;Home_Error&quot;].tail(20).iloc[:-1].to_list()<br># Grab fiorentina last 20 games error asides from the one against roma<br>fior = seriea[seriea[&quot;Team&quot;] == &quot;Fiorentina&quot;][&quot;Home_Error&quot;].tail(20).iloc[:-1].to_list()<br><br>print(f&quot;Number of errors for Roma: {len(roma)}&quot;)<br>print(f&quot;Number of errors for Fiorentina: {len(fior)}&quot;)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OqOxlQbtsvlbTqTJ98FVsw.png" /><figcaption>Number of Total Errors for Roma and Fiorentina</figcaption></figure><p>This was less that 10% of the dataset, most matches were already used as training data</p><p>2. <strong>Unique Error Percentage: </strong>Checking the percentage of occurence for each unique error values will help us know how frequent a particular error type occur and this gives us a sence of possibility of that error happening again</p><p>The Code:</p><pre># 2. Getting percentage of occurence for each errors<br><br># For roma<br>roma_dict = {}<br><br># For each of the unique values in the error list<br>for i in set(roma):<br>    # create a percentage for each of the values<br>    count_pers = roma.count(i) / len(roma)<br><br>    # The unique value the key and the percentage the value<br>    roma_dict[i] = count_pers<br><br># Same thing for fiorentina<br>fior_dict = {}<br><br>for i in set(fior):<br>    count_perc = fior.count(i) / len(fior)<br><br>    fior_dict[i] = count_perc<br><br>print(f&quot;Roma Error Percentage Occurence: {roma_dict}&quot;)<br>print(f&quot;Fiorentina Error Percentage Occurence: {fior_dict}&quot;)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpUgYNTzw-2QCalFpXQOZw.png" /><figcaption>Percentage of each error type occurrence</figcaption></figure><p>Each error value has a particular percentage attached to them, this percentage represents the rate of occurrence of the error in the list of errors, looking at roma error percentage, 0 has a 46% occurrence rate meaning the model preicted the actual values accurately 46% of the time in the test dataset same for fiorentina.</p><p>3. <strong>Adding Predicted Goals to Different Error Scenarios: </strong>The goal in this stem is to take the model predictions and add it to each of the error, this gives us a picture of different scenarios happening and the percentage of it happening</p><p>The Code:</p><pre># 3. Checking the percentage of each goal scenerio happening<br><br># Model predicted goals<br>r_goal = 2<br>f_goal = 1<br><br># Save results<br>roma_prob = {}<br>fior_prob = {}<br><br><br># Check each items in the error dictionary<br>for key, value in roma_dict.items():<br>    # Add roma predicted goal to each of the error<br>    new_key = r_goal + key<br>    # Make The prediction + error the key and the percentage of it happening the value<br>    roma_prob[new_key] = value<br><br># Same for fiorentina<br>for key, value in fior_dict.items():<br>    new_key = f_goal + key<br>    fior_prob[new_key] = value<br><br># The result of fiorentina will bring a negative result were error is -2 and prediction is 1 = -1.<br># So we took the percentage of -1 result and added it to 0 goals scenerio<br>for key, value in fior_prob.items():<br>    if key &lt; 0:<br>        fior_prob[0] += value<br><br># Delete the -1 goal scenerio from the dict<br>fior_prob.pop(-1)<br><br>print(f&quot;Roma Probability of scoring amount of goals: {roma_prob}&quot;)<br>print(f&quot;Fiorentina Probability of scoring amount of goals: {fior_prob}&quot;)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_wnoQFpNa48ke65bUIBsA.png" /><figcaption>Probability of Different Goal Scenarios Happening for each Team Based on Past Error Patterns</figcaption></figure><p>The above gives us a sense of different goal possibilities for each team, the above results show Roma has high chances scoring 2 or 3 goals, while fiorentina has high chances scoring 1 or 0 goals</p><p>4. <strong>Calculating Intervals: </strong>This helps us see different goal range possibilities for each team and the percentage associated with it, e.g Roma having 1–3 goals interval at 70%, etc.</p><p>The Code:</p><pre># 4. creating different goal intervals<br><br># Sort data keys for order arrangement<br>roma_prob = dict(sorted(roma_prob.items()))<br>fior_prob = dict(sorted(fior_prob.items()))<br><br><br># Starting from Roma<br>roma_int = {}<br><br># First loop through all the items in the dict<br>for key, value in roma_prob.items():<br><br>    # For each llop in the first loop, loop all in this second loop<br>    for k, v in roma_prob.items():<br><br>        # need this for interval placement e.g (1-3)<br>        low = min(key, k)<br>        high = max(key, k)<br><br>        # Find values in between the inervals e.g (find 2 in between 1-3)<br>        middle_values = [j for i, j in roma_prob.items() if low &lt; i &lt; high]<br><br>        # Dont add the 2 values together if both keys in the loops are same<br>        if key == k:<br>            roma_int[f&quot;{low} - {high}&quot;] = value<br>        else:<br>            roma_int[f&quot;{low} - {high}&quot;] = value + sum(middle_values) + v<br><br># Same for fiorentina<br>fior_int = {}<br><br>for key, value in fior_prob.items():<br><br>    for k, v in fior_prob.items():<br><br>        low = min(key, k)<br>        high = max(key, k)<br><br>        middle_values = [j for i, j in fior_prob.items() if low &lt; i &lt; high]<br><br>        if key == k:<br>            fior_int[f&quot;{low} - {high}&quot;] = value<br><br>        else:<br>            fior_int[f&quot;{low} - {high}&quot;] = value + v + sum(middle_values)<br><br><br>print(f&quot;Roma Possible Scenerios and it percentage: {roma_int}&quot;)<br>print(&quot;=&quot; * 144)<br>print(&quot;=&quot; * 144)<br>print(f&quot;Fiorentina Possible Scenerios and it percentage: {fior_int}&quot;)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgRY09mZNMBiv-4ZUltXsw.png" /><figcaption>Goal Intervals and Their Probability for Roma and Fiorentina</figcaption></figure><p>Analyzing the results above, using Roma as an example, the probability of the team scoring between 3 and 4 goals is estimated at 38%, which is significantly higher than the probability of scoring between 0 and 1 goal at 15%.</p><p>The highest cumulative probability occurs within the 0 to 4 goal intervals, reaching 100%, indicating that, based on the model’s historical error behavior and scenario construction, all realistic scoring outcomes for Roma were concentrated within that range.</p><p>5. <strong>Total Goals Scenario: </strong>The objective of the Total Goals Scenario is to evaluate the different possible combined goal outcomes for both teams and estimate the probability of each scenario occurring.</p><p>We will achieve this by combining the predicted goal outcomes and historical error patterns of both teams to simulate multiple match scoreline possibilities. Each possible score combination is then assigned a probability based on how frequently similar error behaviors have occurred in the past.</p><p>The Code:</p><pre># 5. Initialize lists to store our data points<br><br># Initialize dictionary<br>team_conv = {<br>    &quot;Possible Scores&quot;: [],<br>    &quot;Total Goals&quot;: [],<br>    &quot;Probability&quot;: []<br>}<br><br># 1. Loop through Roma errors<br>for b_error, b_p in roma_dict.items():<br>    # 2. Loop through Fiorentina errors<br>    for m_error, m_p in fior_dict.items():<br>        <br>        # Add the predicted goal by each looped error, the maximum between the sum and 0 to cancel negative values<br>        home_score = max(0, r_goal + b_error)<br>        away_score = max(0, f_goal + m_error)<br>        <br>        # Calculate metrics<br>        total_goals = home_score + away_score<br>        joint_prob = b_p * m_p  # Probability of BOTH happening<br>        <br>        # Append to our lists<br>        team_conv[&quot;Possible Scores&quot;].append(f&quot;{home_score} - {away_score}&quot;)<br>        team_conv[&quot;Total Goals&quot;].append(total_goals)<br>        team_conv[&quot;Probability&quot;].append(joint_prob)<br><br># 3. Convert to a beautiful DataFrame<br>conv_df = pd.DataFrame(team_conv)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*LzuWqI_6CQQ_NfXHtsvPGg.png" /><figcaption>Possible Goals and scoreline With Probability in Descending Order</figcaption></figure><p>The highest probability scenarios generated by the probabilistic system consistently favor Roma winning the match, with most of the top outcomes projecting Roma to score at least 2 goals.</p><p>Additionally, the most probable scorelines, such as 2–1 and 3–1, suggest that the model’s historical error behavior and scenario simulations leaned toward a relatively strong attacking performance from Roma rather than a low scoring outcome.</p><p>6. <strong>Heatmap:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*n5XFS2ap84DsDH3ixCgc5Q.png" /><figcaption>Heatmap for Roma vs Fiorentina</figcaption></figure><p>The heatmap above gives us a better visual representation of the probability distribution for different possible scorelines between Roma and Fiorentina generated by the probabilistic forecasting system. Focusing on the lightened cells which shows high probabilities of fiorentina low scoring and roma high scoring</p><p>7. <strong>Over and Under Goals Probability: </strong>I consider the over and under goals probability to be one of the most reliable and trustworthy metrics within the probabilistic framework, as it helps validate the underlying assumptions and strengthens the credibility of the overall probability system.</p><p>The Code:</p><pre># 7. Checking for over and under goals<br><br># Group dataframe by total goals<br>group_df = conv_df.groupby(&quot;Total Goals&quot;)[&quot;Probability&quot;].sum().reset_index()<br># over 1.5 goals probability<br>over_15 = sum(group_df[group_df[&quot;Total Goals&quot;] &gt; 1.5][&quot;Probability&quot;].to_list())<br># over 2.5 goals probability<br>over_25 = sum(group_df[group_df[&quot;Total Goals&quot;] &gt; 2.5][&quot;Probability&quot;].to_list())<br># Under 3.5 goals probability<br>under_35 = sum(group_df[group_df[&quot;Total Goals&quot;] &lt; 3.5][&quot;Probability&quot;].to_list())<br><br>print(f&quot;Probability of having over 1.5 goals in this match is {int(over_15 * 100)}%&quot;)<br>print(f&quot;Probability of having over 2.5 goals in this match is {int(over_25 * 100)}%&quot;)<br>print(f&quot;Probability of having under 3.5 goals in this match is {int(under_35 * 100)}%&quot;)</pre><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcyQWGBpWA6eXGUDUIC-jQ.png" /><figcaption>Over and Under Probabilities</figcaption></figure><p>The result shows a very high chance for over 1.5 and 2.5 goals happening and an average chance of under 3.5 goals happening</p><h3><strong>CONCLUSION</strong></h3><p>The analysis demonstrates that leveraging historical model errors can significantly improve how we interpret and evaluate uncertain match outcomes. In this experiment, the probabilistic framework successfully generated high probability scenarios that aligned closely with the actual 4–0 victory of AS Roma over ACF Fiorentina, despite the original deep learning model predicting a 2–1 result.</p><p>Rather than relying solely on a single deterministic prediction, the system used each team’s historical error behavior to construct a broader probability landscape of possible outcomes. This made the analysis more informative, realistic, and uncertainty-aware.</p><p>The results suggest that model errors should not be viewed merely as evaluation leftovers, but as valuable statistical signals capable of improving probabilistic forecasting, scenario analysis, and risk aware decision making.</p><p>Although this experimentation focused on football analytics, the same framework can potentially be extended to other regression-based machine learning systems where uncertainty and volatility play a major role. This includes applications in financial forecasting, demand prediction, risk management, healthcare analytics, and other domains where understanding the range of possible outcomes is just as important as the prediction itself.</p><p>Building on this idea, a platform called AML Football was developed to apply AI, machine learning, mathematical modeling, and statistical techniques to football analytics and probabilistic match forecasting.</p><p><strong>LINK:</strong></p><p><a href="https://amlfootball.live/">AML Football — Applied Machine Learning Research | AI Match Intelligence</a></p><h3><strong>Evaluation Notebook:</strong></h3><p><a href="https://github.com/dlifeofjay/AMLFootball-Evaluation">dlifeofjay/AMLFootball-Evaluation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a789f14d10c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Neural Network Using Just Python and Numpy]]></title>
            <link>https://medium.com/@dlifeofjay/building-a-neural-network-using-just-python-and-numpy-c5df9cad85bc?source=rss-4f3c86d3fc5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5df9cad85bc</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jay]]></dc:creator>
            <pubDate>Sat, 02 May 2026 19:27:16 GMT</pubDate>
            <atom:updated>2026-05-02T19:27:16.072Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a neural network doesn’t have to be difficult, you just need to understand the concepts behind it and what makes up the entire system.</p><p>This article is designed to give you a full understanding and mental walkthrough of the core concepts behind neural networks. An understanding of vectors, linear algebra and matrices will make your understanding of this article much better</p><p>I will break these concepts into 3, which is core in understanding how the system predicts</p><ul><li>Forward Pass</li><li>Backward Pass</li><li>Update Parameters</li></ul><p>Before explaining the above concepts, we need to have a visual sense of what these systems looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1VzI0Lope3JoooYjQSudg.png" /><figcaption>A Visual Example of an Artificial Neural Network</figcaption></figure><p>The above image looks complicated but trust me it’s not! We will use the MNIST hand digit dataset to clearly explain how this network works, but to clearly understand the flow i will explain what each item in the diagram means</p><ol><li>X: This is simply the input dataset features the network expects to learn from.</li><li>Hidden Layer: The hidden layers are made up of neurons, each blue circle in the layers are called neurons and each of them have their own parameters (I will explain parameters later in the article). The goal of these neurons is to produce a value which will be used in making the next layer predictions.</li><li>ReLU: This is called an activation function commonly used within the hidden layers before the final layer and after the input layer, it goal is to make sure the values from the neurons from these hidden layers won&#39;t be negative. It does this by converting negative values to 0 and positives still remain and maintain their values</li><li>Output Layer: This layer consists of the neurons that makes the finally used predictions. In our case which is a classification model, having 10 neurons means we are trying to predict ten classes. We expect 10 values from each input samples and these values will be used to give the ultimate final prediction after it has gone through softmax activation function</li><li>Softmax: The Softmax activation function is applied to the final output layer to interpret the model’s results. Its role is to take the raw numerical scores (logits) from each output neuron and convert them into a probability distribution. For example, if the final outputs from the neurons for a specific sample are: [1.33, 2.4, 6.7, 3.6, 1.9, 0.6, 2.7, 1.23, 2.8, 4.4], The Softmax function calculates the probability for each class by taking the exponential of each value and dividing it by the sum of the exponentials of all values in the vector. This ensures that all resulting probabilities are between 0 and 1 and sum up to exactly 100%. The neuron with the highest probability is then selected as the “winning” class or the model’s final prediction.</li></ol><h4>EXPLAINING THE CONCEPTS AND TRAINING A MODEL</h4><ol><li><strong>FORWARD PASS:</strong> This is simply when the model tries to make a prediction using the formular <em>“Y = wx + b” </em>where Y is the predicted value, w is the weight, x is the data and b is the bias term. The parameters are simply w &amp; b.</li></ol><p>To start making the model predict (forward pass) we need to define our architecture and what it entails:</p><p><strong>A. Data Preprocessing for Matrix Operations:</strong> Before initiating the training process, the dataset must be converted from a standard dataframe into NumPy arrays and subsequently transposed. This transformation is essential for several technical reasons:</p><ul><li>Computational Efficiency: Converting to NumPy arrays allows the model to handle large-scale datasets as structured matrices. This format is optimized for the high-performance linear algebra operations required for deep learning models to converge faster and more reliably.</li><li>Mathematical Alignment: The transpose operation is necessary to align the dimensions of our data for matrix dot multiplication.</li><li>Vectorization: In neural network training, we multiply weights by inputs (W . X); by transposing the input matrix, we ensure that the rows of our weight matrix correctly align with the columns of our feature matrix.</li></ul><p>The code:</p><pre># 1. Converting dataframe to array, splitting into train and test set and transposing<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>data = np.array(data) # converting to numpy array<br>m, n = data.shape # Extracting number of samples (m) and number of features (n)<br>np.random.shuffle(data) # Re-organizing and rearranging data for randomness<br><br>test_data = data[0:1000].T # Extracting test data and transposing; picking first 1000 samples and making columns row and row columns for matrix dot multiplication (Transposing)<br>X_test = test_data[1:n] # Extracting Features (X) that will be used for (testing)<br>y_test = test_data[0] # Extracting the label transposed row<br><br>data_train = data[1000:m].T # Extracting train data and transposing; picking (49,000) samples and making columns row and row columns for matrix dot multiplication (Transposing)<br>X_train = data_train[1:n] # Extracting Features (X) that will be used for (training)<br>y_train = data_train[0] # Extracting the label transposed row</pre><p><strong>B. Initialization of Parameters: </strong>Initializing the weights and bias is very important because without it, the model misses the key variables that makes up it formular.</p><p>First of all, let me explain how the weights are different from the bias term</p><ul><li>The number of weights for a particular sample depends on the number of features we have for that sample if we have 2 features to predict a value, it means we are expected to have 2 weights. In our case we have a total number of 784 features meaning we have 784 number of weights, while the bias always remains 1 given that we have 2 layers (Hidden and Output layer) and each layer have 10 neurons each, that means we have 784 weights and 1 bias term per neuron, meaning each layer has 7,840 weights and 10 bias term. Note that each weight are expected to be of different values</li></ul><p>The Code to initialize parameters:</p><pre># 2. Initializing weights and bias<br><br>def init_params():<br>    # W1: 10 neurons, each receiving 784 input features<br>    w1 = np.random.randn(10, 784) * 0.01 <br>    # b1: 1 bias term for each of the 10 neurons in the hidden layer<br>    b1 = np.zeros((10, 1)) <br><br>    # W2: 10 output neurons, each receiving 10 inputs from the hidden layer<br>    w2 = np.random.randn(10, 10) * 0.01 <br>    # b2: 1 bias term for each of the 10 neurons in the output layer<br>    b2 = np.zeros((10, 1))<br>    <br>    # Returns all needed parameters for calculation of predictions<br>    return w1, b1, w2, b2 </pre><p><strong>C. ReLU: </strong>This is an activation function that takes in the outputs from each neurons, if any output is negative, it converts to 0, if not, the output remains the same.</p><p>The Code:</p><pre># 3. Setting up ReLU<br><br>def ReLU(z):<br>    # Defining Relu<br>    # The maximum between 0 and z values<br>    return np.maximum(0, z)</pre><p><strong>D. Softmax: </strong>This is also an activation function, but it is responsible for converting the values (logits) from the output layers into probabilities</p><p>The code:</p><pre># 4. Softmax activation function<br><br>def softmax(z):<br><br>    # Picks the exponential of the total 10 neurons<br>    exp_z = np.exp(z - np.max(z, axis=0, keepdims=True))<br><br>    # return the probability of each neurons<br>    return exp_z / np.sum(exp_z, axis=0, keepdims=True)</pre><p><strong>FULL FORWARD PASS CODE:</strong></p><pre># 5. Forward pass function<br><br>def forward_pass(w1, b1, w2, b2, x):<br>    # Execution of the formular &quot;Y = wx + b&quot;<br>    # First Layer output calculation<br>    z1 = w1.dot(x) + b1<br>    <br>    # Output passing through ReLU activation function<br>    a1 = ReLU(z1)<br>    <br>    # Output layer outputs (logits)<br>    z2 = w2.dot(a1) + b2<br>    <br>    # Softmax giving us the class with the highest probability<br>    a2 = softmax(z2)<br><br>    # Returns all outputs for effective calculation of Back Propagation<br>    return z1, a1, z2, a2</pre><p><strong>2. BACKWARD PASS: </strong>The idea here is to calculate the error (predicted minus actual outcome) and allocating these errors to the neurons (from output to hidden) that made that prediction. So we are basically working from the back to the front.</p><p>These are the steps taken for an effective backward pass:</p><p><strong>A. One Hot Encoding: </strong>Currently, our output predictions and ground truth are in label-encoded form (a simple integer like 3 or 7). However, remember that our 10 output neurons each represent one specific class, as seen in the Output Layer.</p><p>To calculate the error correctly during the Backward Pass, we must transform these single integers into a One-Hot Encoded vector. This means creating a list of 10 values where every position is a 0, except for the index corresponding to the actual class, which is marked as a 1.</p><p>For example, if the correct label for an image is 3, the one-hot encoded version becomes: [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]</p><p>The Code:</p><pre># 1. Convert labels to one hot encoded values<br><br>def one_hot(y):<br>    # creates a matrix of 0s with rows of the training data rows and columns of the highest value of the label<br>    one_hot_y = np.zeros((y.size, y.max()+1))<br><br>    # It looks at each row, then uses y as a column index, if y exists, it changes that particular column index to 1<br>    one_hot_y[np.arange(y.size), y] = 1 <br>    <br>    # Transpose it, then each row will be a column for effective error calculation<br>    one_hot_y = one_hot_y.T<br><br>    # if label is 3, output will be [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]<br>    return one_hot_y</pre><p><strong>B. Derivative of ReLU:</strong> The idea behind this stage is to catch the neurons that contributed to the prediction. remember where we defined ReLU, we mentioned that any neuron that gives negative output we change it to 0, this stage just helps us locate the exact neurons that were not 0</p><p>The Code:</p><pre># 2. Derivative of ReLU<br><br>def deriv_ReLU(z):<br><br>    # Catching the outputs that contributed to the error<br>    return z &gt; 0</pre><p><strong>THE BACKWARD PASS CODE:</strong></p><pre># 3. Backward Pass Function: Calculating how to adjust weights to reduce error<br><br>def backward_pass(z1, a1, z2, a2, w2, x, y):<br>    # Get total number of samples to average the error across the entire samples<br>    m = y.size<br>    <br>    # Transform integer labels into one hot probability matrix (e.g., [0,0,0,1...])<br>    one_hot_y = one_hot(y)<br><br>    # Calculate error (dz2): Find the difference between our Softmax predictions and the actual probability matrix<br>    dz2 = a2 - one_hot_y<br><br>    # Calculate Weight 2 Change (dw2): Determine how much each Output neuron&#39;s weight contributed to the error<br>    dw2 = 1/m * dz2.dot(a1.T)<br><br>    # Calculate Bias 2 Change (db2): Find the average error offset for the output layer<br>    db2 = 1/m * np.sum(dz2, axis=1, keepdims=True)<br><br>    # Calculate error for the Hidden Layer (dz1):<br>    <br>    # Use the Derivative of ReLU to locate only the neurons that were active (not 0) during the forward pass<br>    dz1 = w2.T.dot(dz2) * deriv_ReLU(z1)<br><br>    # Calculate Weight 1 Change (dw1): Determine how the input features influenced the hidden layer&#39;s error<br>    dw1 = 1/m * dz1.dot(x.T)<br>    <br>    # Calculate Bias 1 Change (db1): Find the average error offset for the hidden layer<br>    db1 = 1/m * np.sum(dz1, axis=1, keepdims=True)<br>    <br>    return dw1, db1, dw2, db2</pre><p><strong>3. UPDATE PARAMETERS: </strong>This is just a subset or continuation of the backward pass, the idea of this part is to take the rate of change (gradients) and use it to physically adjust our parameters. Here, the higher the rate of change, the larger the new parameters adjust, all depending on the learning rate.</p><p>So once the Backward Pass have gotten the rate of change of the error, the update parameters look at how extreme the rate is to give another weight the forward pass should try</p><p>The Code</p><pre># Update Parameters<br><br>def update_params(w1, b1, w2, b2, dw1, db1, dw2, db2, lr):<br><br>    # For the hidden layer<br>    w1 = w1 - lr * dw1<br>    b1 = b1 - lr * db1<br><br>    # For the output layer<br>    w2 = w2 - lr * dw2<br>    b2 = b2 - lr * db2<br><br>    return w1, b1, w2, b2</pre><p><strong>MEASURE ACCURACY: </strong>This helps us monitor the training accuracy</p><pre># Measure accuracy<br><br>def get_pred(a2):<br>    # Returns the index of the highest probability<br>    return np.argmax(a2, 0)<br><br><br>def get_accuracy(predictions, y):<br>    # Compares them<br>    print(predictions, y)<br>    # Return the correctly predicted / total dataset size percentage (Accuracy)<br>    return np.sum(predictions == y) / y.size</pre><p><strong>FULL MODEL TRAINING: </strong>This is the whole training loop that takes all the functions together. Returns the learnt weights and bias for both layers</p><pre># Model Training<br><br>def train(x, y, iterations, lr):<br>    # Initialize parameters<br>    w1, b1, w2, b2 = init_params()<br><br>    # Start loop<br>    for i in range(iterations):<br>        # Model Tries to predict<br>        z1, a1, z2, a2 = forward_pass(w1, b1, w2, b2, x)<br>        # Checks how wrong it is<br>        dw1, db1, dw2, db2 = backward_pass(z1, a1, z2, a2, w2, x, y)<br>        # Correct the prediction by giving another parameters to try<br>        w1, b1, w2, b2 = update_params(w1, b1, w2, b2, dw1, db1, dw2, db2, lr)<br>        # Print Accuracy Overtime<br>        print(f&quot;Epochs: {i+1}, Accuracy: {get_accuracy(get_pred(a2), y)}&quot;)<br>    return w1, b1, w2, b2</pre><p><strong>TRAINING RESULT: </strong>Got a final accuracy score of 83.75% which is quite good for a simple (MLP ANN)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zV8PrKZu_RERo7VRiUQ7qA.png" /></figure><p><strong>MAKING A PREDICTION:</strong></p><pre># Making a prediction<br><br>def make_pred(x, w1, b1, w2, b2):<br>    # Makes a prediction<br>    _, _, _, a2 = forward_pass(w1, b1, w2, b2, x)<br>    # Get the output index<br>    predictions = get_pred(a2)<br>    return predictions<br><br><br>def test_pred(index, w1, b1, w2, b2):<br>    # Grab the image we are trying to predict in the test set<br>    current_image = X_test[:, index, None]<br>    # Make predictions<br>    prediction = make_pred(X_test[:, index, None], w1, b1, w2, b2)<br>    <br>    # Extract true value<br>    label = y_test[index]<br>    print(&quot;Prediction: &quot;, prediction)<br>    print(&quot;Label: &quot;, label)<br><br>    # Convert Image to Gray Scale<br>    current_image = current_image.reshape((28, 28)) * 255<br>    plt.gray()<br>    plt.imshow(current_image, interpolation=&quot;nearest&quot;)<br>    plt.show()</pre><p><strong>PREDICTED RESULT TESTING ACTUAL VALUE (5)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZpyF_Eoqs9Qt2S0fP-kXg.png" /></figure><p><strong>CONCLUSION:</strong></p><p>This should help give you a mental visual understanding of how the math and code works, extending the layers and adding regularization techniques makes it deep learning or Deep Neural Networks (DNN).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5df9cad85bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>