<?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 Brian Muchai on Medium]]></title>
        <description><![CDATA[Stories by Brian Muchai on Medium]]></description>
        <link>https://medium.com/@muchaibriank?source=rss-fb32d74bdd20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2yG23qGx2rphUmhO5aQmhA.jpeg</url>
            <title>Stories by Brian Muchai on Medium</title>
            <link>https://medium.com/@muchaibriank?source=rss-fb32d74bdd20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:07:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muchaibriank/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[End To End Machine Learning Project (Loan Approval) — Part 3— Deployment and CI/CD Pipeline]]></title>
            <link>https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-3-deployment-and-ci-cd-pipeline-0db5e8d7d078?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/0db5e8d7d078</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 08:12:20 GMT</pubDate>
            <atom:updated>2024-11-25T08:18:14.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>End To End Machine Learning Project (Loan Approval) — Part 3— Deployment and CI/CD Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*rcIiP1Jfzy7HQOsylyzZKA.jpeg" /></figure><p>The objective of this article is to <strong>deploy and develop a CI/CD pipeline for our end-to-end machine learning model for loan prediction</strong>. If you are new to this series, kindly check out <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-prediction-part-1-introduction-5">Part 1</a> where I explained the overall aim of this project and <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-2-development-0e437b084ad5">Part 2</a> where I went through the Development phase of the project and shared all the resources I used for development, including the GitHub repository.</p><p>You’ve done so? Great! Let’s move on…</p><p>I had used the below tools and services for this phase of the project. I had created accounts in DigitalOcean and name.com using the <a href="https://education.github.com/pack">Github Student Developer Pack</a>. This in turn gave me 200 USD worth of credits for an year on Digital Ocean and a free Domain name on name.com.</p><p>However, you can opt to create a normal account on DigitalOcean instead. You will still be given 200 USD worth of credits but it will last for 60 days. For the domain name, there are plenty of other registrars who offer free domain names such as <a href="https://www.hostinger.com/free-domain">Hostinger</a> should you wish to go with that route. The rest of the tools and services used are either free or open source so no worries there :)</p><ol><li><strong>DigitalOcean</strong> — a cloud computing platform. Provides virtual servers (called droplets) and other cloud services like databases and storage. We shall obtain a Linux virtual server from it where we shall host our application.</li><li><strong>Nginx</strong> — a web server software. Serves websites and handles tasks like load balancing, acting as a reverse proxy, or caching. We shall use it as our web server and use it as a reverse proxy.</li><li><strong>Let’s Encrpt</strong> — a free Certificate Authority. Provides SSL/TLS certificates to secure websites, enabling HTTPS. This is where we shall obtain SSL certificates for our website and API through certbot.</li><li><strong>name.com</strong> — a domain registrar. Allows you to register and manage domain names. We shall obtain the <strong>loanpredictor.live</strong> domain name from here.</li><li><strong>GitHub</strong> — platform for hosting and collaborating on code. We shall be pushing our code here and pulling it from here to the virtual machine.</li><li><strong>GitHub Actions</strong> — tool within GitHub for automating tasks. Automates workflows, like testing code, deploying apps, or updating documentation when you push changes to your repository. We shall use it to automate deployment of the new changes to the application when we push new changes to GitHub.</li><li><strong>CloudFlare</strong> — DNS server. We shall use it to resolve DNS queries to our application. We shall also take advantage of its CDN capabilities so as to serve our application faster to the users.</li></ol><p><strong>Step 1: Obtaining a Virtual Machine and deploying the app</strong></p><p><strong>1.1 Create a Droplet</strong></p><p>Virtual machines in DigitalOcean are known as Droplets. You will have to create an account in DigitalOcean if you don’t already have. An account made through the GitHub Student Developer Pack usually has 200 USD worth of credit ready to use. This will be more than enough for our usecase.</p><p>Create a new project in DigitalOcean and assign it a Droplet. You will have to chose the Region and the specific Datacenter you want the Droplet to recede in. It is a good rule of thumb to always choose the Region closest to you and your users geographically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0RAGxlhoGPNtdTWHEBNoA.jpeg" /></figure><p>Next step will be to choose an operating system for your droplet. In my case I went with <strong>Ubuntu 24.10 x64</strong>. You will also have to choose the configuration for the Droplet in terms of RAM, storage and storage type.</p><p><strong>Note</strong>: most operating systems in DigitalOcean are Linux based so some knowledge in Linux will be of great benefit.</p><p>As a final step, you will have to chose the Authentication method you wish to use for the Droplet. For my case, I went with the Password option. With it, you can always SSH into the Virtual Machine as the “root” user.</p><p>Once the Droplet is setup, it will be vital to set up a <strong>reserved IP address</strong> for it. This is the IP address where the virtual machine will be located and anyone on the internet can access it through it.</p><p><strong>1.2 Install Docker</strong></p><p>To do so, we first need to access the Droplet we have just created. We can do so in two ways; either from the console in your Droplet dashboard or by SSH. To SSH, you will have to run this bash script, where <em>&lt;your_droplet_ip&gt; </em>is the IP address of the Droplet.</p><pre>ssh root@&lt;your_droplet_ip&gt;</pre><p>Next, we will have to update the system, install Docker and Docker Compose and then verify that Docker is running. We do so by running the following scripts:</p><pre>apt update &amp;&amp; apt upgrade -y<br>apt install docker.io docker-compose -y<br>systemctl status docker</pre><p><strong>1.3 Clone your code from GitHub</strong></p><p>To do so, we will first have to install git. After doing so, we can clone the repo and then cd into it.</p><pre>apt install git -y<br>git clone https://github.com/username/repo-name.git<br>cd repo-name</pre><p><strong>1.4 Build and run the containers</strong></p><p>To do so, we first have to make sure that we are in the root directory of the repository, where the <strong>docker-compose.yml</strong> file is located. We then build the container and then start it.</p><pre>docker-compose build<br>docker-compose up -d</pre><p>After doing so, we can test whether everything is working by accessing the Streamlit App and API through the droplet’s public IP.</p><ul><li>Streamlit app: <em>http://&lt;droplet_ip&gt;:8501</em></li><li>FastAPI: <em>http://&lt;droplet_ip&gt;:8000</em></li></ul><p><strong>Step 2: Set up a Domain name</strong></p><p><strong>2.1 Purchase a Domain</strong></p><p>You can do so by setting up an account on name.com using the Github Student Developer Pack. You will get a free <strong>.LIVE</strong> Domain name by default which will last for an year. For my case, I went with <strong>loanpredictor.live.</strong></p><p>If using name.com, I recommend turning on the WhoIs Privacy to on and the Auto renew to off if you’d not like to be charged automatically for a renewal when the year ends.</p><p><strong>2.2 Point the Domain to the Droplet</strong></p><p>To do so, we will have to set up Cloudflare as our DNS server. A free account on Cloudflare will be more than enough for this purpose. Cloudflare will resolve all DNS queries to our application and our application will enjoy all of Cloudflare’s protection and CDN.</p><p>Once you have created an account on Cloudflare, we will have to configure our Domain to use Cloudflare. We can do so by updating it’s nameservers to Cloudflare’s and deleting the defaults.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*yXPOsH9iOmtL2Lo23PykFw.jpeg" /></figure><p>We then have to set up A DNS records for loanpredictor.live and api.loanpredictor.live and point them to our Droplet’s IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQa3GnSKT9G-dZARHUjGVQ.jpeg" /></figure><p><strong>2.3 Configure Nginx to serve the application</strong></p><p>We first install Nginx using the following script:</p><pre>apt install nginx -y</pre><p>We now have to set up configuration files for <strong>loanpredictor.live</strong> and <strong>api.loanpredictor.live</strong> at <em>/etc/nginx/sites-available</em></p><p>Let us start with the Streamlit app page. We create a new configuration file named <em>app</em> at <em>/etc/nginx/sites-available </em>and then write the following configurations in it using<em> sudo nano app</em></p><pre>server {<br>    server_name loanpredictor.live;<br>    <br>    location / {<br>        proxy_pass http://localhost:8501;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p>The key parts of the configuration file is the <em>server_name loanpredictor.live; </em>and<em> proxy_pass </em><a href="http://localhost:8501;"><em>http://localhost:8501;</em></a> lines. Make sure that <em>server_name</em> points to your domain name and <em>proxy_pass</em> points to the port that the app is running in.</p><p>After saving the configuration file, we enable it by running the following script. Adjust <em>app</em> to the name of the configuration file</p><pre>sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/</pre><p>We then test the configuration file by running the following script:</p><pre>sudo nginx -t</pre><p>After doing so, we can reload Nginx by running the following script:</p><pre>sudo systemctl reload nginx</pre><p>We can then obtain an SSL certificate for the app using certbot by running the following script:</p><pre>sudo certbot --nginx -d loanpredictor.live</pre><p>Our app should now be available at <a href="https://loanpredictor.live./"><strong>https://loanpredictor.live</strong></a>. It may take some time, from a few minutes to a few hours until our site is available at the domain name<strong>.</strong></p><p>Once the app is available, we can do the same exact thing for the API endpoint. We first create a new configuration file at <em>/etc/nginx/sites-available</em>. Let as name it as api.</p><pre>server {<br>    server_name api.loanpredictor.live;<br>    <br>    location / {<br>        proxy_pass http://localhost:1338;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p>We then enable it, test it, reload Nginx and set up an SSL certificate for it by running the following scripts respectively.</p><pre>sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/<br>sudo nginx -t<br>sudo systemctl reload nginx<br>sudo certbot --nginx -d api.loanpredictor.live</pre><p>We should now be both the App and API at their respective domains, accessible to anyone on the internet.</p><p>So as to secure our domains, it is recommend that we set the SSL/TSL setting at Cloudflare to fullstrict. This ensures the most secure connection between our users and the Droplet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*nUZa78Jub1HppAPhUWJMBg.jpeg" /></figure><p><strong>Step 3: Create a CI/CD pipeline with GitHub Actions</strong></p><p><strong>3.1 Install the GitHub Actions runner in the Droplet</strong></p><p>Go to your repository on GitHub then navigate to Settings &gt; Actions &gt; Runners. Follow the instructions to install a <strong>self-hosted runner</strong> on the Droplet.</p><p><strong>Note</strong>: if you are setting up the runner in a Linux environment, you need to do so as a user with non-root privileges. If you are logged in as root, you can create another user and log in as the new user before setting up the runner. Also, you will need to set up passwordless SSH and store the private key to the repository’s Secrets.</p><p><strong>3.2 Add deployment Workflow</strong></p><p>Add a Github Actions workflow in<em> .github/workflows/deploy.yml</em>. This is at the root of our repository.</p><pre>name: Deploy to DigitalOcean<br><br>on:<br>  push:<br>    branches:<br>      - master<br><br>jobs:<br>  deploy:<br>    runs-on: self-hosted<br><br>    steps:<br>      - name: Set up SSH<br>        run: |<br>          echo &quot;${{ secrets.DO_SSH_KEY }}&quot; &gt; ~/.ssh/id_rsa<br>          chmod 600 ~/.ssh/id_rsa<br><br>      - name: Add SSH Key to Agent<br>        run: |<br>          eval &quot;$(ssh-agent -s)&quot;<br>          ssh-add ~/.ssh/id_rsa<br><br>      - name: Checkout Repository<br>        uses: actions/checkout@v3<br><br>      - name: Pull Latest Changes on Droplet<br>        run: |<br>          ssh root@188.166.207.252 &quot;cd /root/loan-prediction &amp;&amp; git pull&quot;<br><br>      - name: Build and Restart Docker Containers<br>        run: |<br>          ssh root@188.166.207.252 &quot;<br>          cd /root/loan-prediction &amp;&amp;<br>          docker-compose down &amp;&amp;<br>          docker-compose build &amp;&amp;<br>          docker-compose up -d&quot;</pre><p>This workflow is activated once we push changes to the master branch of our GitHub repository. The runner pulls the latest changes from the repository, stops all the current running containers, builds new containers with the latest changes from the GitHub repository and then builds them. This is done as long as the runner is active on the Droplet.</p><p><strong>Note</strong>: so as to ensure that the GitHub runner is always active, you can run it as a service.</p><p>If you have reached here, congratulations! You now know how to deploy an application to the cloud and set up a CI/CD pipeline!</p><p>It is my hope that you found this article helpful. If so, you can give it some claps. Feel free to share it with your friends. You can also support my work by buying me a cup of coffee ☕ <a href="https://buymeacoffee.com/muchai">here</a> so that I can continue to do what I do best. Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0db5e8d7d078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End To End Machine Learning Project (Loan Approval) — Part 2 — Development]]></title>
            <link>https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-2-development-0e437b084ad5?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e437b084ad5</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 08:08:31 GMT</pubDate>
            <atom:updated>2024-11-25T08:18:18.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>End To End Machine Learning Project (Loan Approval) — Part 2 — Development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GgGFnHiAztFLnFjqpNry0A.jpeg" /></figure><p>The objective of this article is to develop and end-to-end machine learning model for loan prediction. The model can be accessible by making API requests. This makes the model robust as it can be easily integrated, not only to the Streamlit dashboard but other solutions that are either being developed or already existing.</p><ol><li><strong>Aim of the project and Data set</strong></li></ol><p>The aim of this project is explained in detail in <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-prediction-part-1-introduction-541e639b7c5c">Part 1</a> of this article series. You can find it <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-prediction-part-1-introduction-541e639b7c5c">here</a>. I highly encourage you to read it if you haven’t already. It is only a 5 minutes read and will make you to understand why we are doing this project so as to fully appreciate it.</p><p>You’ve read it? Great! Let’s move on…</p><p>2. <strong>Project Resources</strong></p><p>The project is deployed on this <a href="https://loanpredictor.live/">link</a>. Feel free to play around with the Streamlit Dashboard. There is also a live API whose documentation can be found <a href="https://loanpredictor.gitbook.io/api-docs">here</a>. The project files can be found in <a href="https://github.com/muchai254/loan-prediction">GitHub</a>. Feel free to clone the repository, run the project locally with Docker or by setting up a Python environment. Instructions on how to do so can be found in the README file. If you want to make an improvement or fix a bug, feel free to contribute by making a pull request. I will be happy to accept your contributions after reviewing them. Instructions on how to do so can also be found in the README file.</p><ul><li><a href="https://github.com/muchai254/loan-prediction">GitHub Repository</a></li><li><a href="https://loanpredictor.gitbook.io/api-docs">API Documentation</a></li><li><a href="https://loanpredictor.live/">Live link to the Prediction Dashboard</a></li></ul><p><strong>3. Data preprocessing and Model Development</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*v3ky_a1aEsUcJwCTR8jn8A.jpeg" /></figure><p>The Jupyter notebook used for EDA, model training and evaluation can be found in the GitHub repository. It is well documented hence easy to follow. The training data can also be found there.</p><ul><li><a href="https://github.com/muchai254/loan-prediction/blob/master/server/notebooks/eda.ipynb">Jupyter Notebook</a></li><li><a href="https://github.com/muchai254/loan-prediction/tree/master/server/data">Data</a></li></ul><p><strong>3. Fast API</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*TpY9U2sIZviChfAhM9beVA.png" /></figure><p>FastAPI is a modern, high-performance web framework for building APIs with Python. It is designed to enable developers to create robust and production-ready APIs quickly and efficiently while maintaining code readability and simplicity.</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel, Field<br>from typing import Optional, Literal<br>import pandas as pd<br>import numpy as np<br>import shap<br>import matplotlib.pyplot as plt<br>from io import BytesIO<br>import base64<br>import joblib<br>import os<br><br>base_dir = os.path.dirname(os.path.abspath(__file__)) <br><br>model_path = os.path.join(base_dir, &quot;models&quot;, &quot;gb_model.joblib&quot;)<br>data_path = os.path.join(base_dir, &quot;data&quot;, &quot;X_train.csv&quot;)<br><br>model = joblib.load(model_path)  <br>X_train = pd.read_csv(data_path)  <br><br>app = FastAPI()<br><br>class LoanRequest(BaseModel):<br>    loan_term: int<br>    annual_income: int<br>    loan_amount: int<br>    credit_score: int<br>    currency: Literal[&#39;KES&#39;, &#39;INR&#39;] <br>    probability: Optional[bool] = Field(False, description=&quot;Return prediction probability&quot;)<br>    SHAP: Optional[bool] = Field(False, description=&quot;Return SHAP waterfall plot&quot;)<br><br>def log_transform(*dfs):<br>    transformed_dfs = []<br>    for df in dfs:<br>        df_copy = df.copy()<br>        numeric_columns = df_copy.select_dtypes(include=[np.number]).columns<br>        for column in numeric_columns:<br>            if (df_copy[column] &gt; 0).all():<br>                df_copy[column] = np.log(df_copy[column])<br>        transformed_dfs.append(df_copy)  <br>    return transformed_dfs<br><br>@app.post(&quot;/loan&quot;)<br>async def loan_prediction(request: LoanRequest):<br>    custom_input_data = pd.DataFrame([{<br>        &#39;loan_term&#39;: request.loan_term,<br>        &#39;annual_income&#39;: request.annual_income,<br>        &#39;loan_amount&#39;: request.loan_amount,<br>        &#39;credit_score&#39;: request.credit_score<br>    }])<br><br>    if request.currency == &quot;KES&quot;:<br>        custom_input_data[[&#39;annual_income&#39;, &#39;loan_amount&#39;]] /= 0.65<br><br>    # Preprocess the DataFrame<br>    processed_data = custom_input_data.copy()<br>    processed_data[&#39;income_loan_ratio&#39;] = custom_input_data[&#39;annual_income&#39;] / custom_input_data[&#39;loan_amount&#39;]<br>    processed_data[&#39;credit_score_income_ratio&#39;] = custom_input_data[&#39;credit_score&#39;] / custom_input_data[&#39;annual_income&#39;]<br>    processed_data.drop(columns=[&#39;loan_amount&#39;, &#39;annual_income&#39;], inplace=True)<br>    processed_input = log_transform(processed_data)[0]<br><br>    prediction = model.predict(processed_input)[0]<br>    <br>    response = {&quot;prediction&quot;: int(prediction)}<br><br>    if request.probability:<br>        prediction_probability = model.predict_proba(processed_input)<br>        response[&quot;prediction_probability&quot;] = prediction_probability[0].tolist()<br><br>    if request.SHAP:<br>        explainer = shap.Explainer(model, X_train)<br>        shap_values = explainer(processed_input)<br>        <br>        # Adjust SHAP values for the original data values<br>        for i, column in enumerate(processed_data.columns):<br>            shap_values[0].data[i] = processed_data.iloc[0, i]<br>        <br>        # Plot SHAP waterfall and convert to an image<br>        plt.figure()<br>        shap.plots.waterfall(shap_values[0], show=False)<br>        buf = BytesIO()<br>        plt.savefig(buf, format=&quot;png&quot;, bbox_inches=&quot;tight&quot;)<br>        buf.seek(0)<br>        <br>        img_base64 = base64.b64encode(buf.read()).decode(&quot;utf-8&quot;)<br>        response[&quot;SHAP_plot&quot;] = img_base64<br><br>        plt.close()<br><br>    return response</pre><p><strong>Step 1: Importing libraries</strong></p><p>We begin by importing the necessary libraries for various tasks:</p><ul><li><strong>FastAPI</strong>: To create and handle API endpoints.</li><li><strong>pydantic</strong>: For data validation and request modeling.</li><li><strong>pandas </strong>and<strong> </strong><strong>numpy</strong>: For data manipulation and mathematical operations.</li><li><strong>shap </strong>and<strong> </strong><strong>matplotlib.pyplot</strong>: For providing explanations to the predictions by plotting visualizations.</li><li><strong>BytesIO </strong>and<strong> </strong><strong>base64</strong>: To encode images as base64 for API responses. We do this so as to simplify the process of sending the SHAP waterfall diagram over the API.</li><li><strong>joblib</strong>: To load the machine learning model.</li><li><strong>os</strong>: To handle file path</li></ul><p><strong>Step 2: Setting up paths to the trained model and X_train data and loading them</strong></p><p>We set up the path to the model and <em>X_train</em> data using <em>os.path </em>so as to ensure consistency between operating systems. The two are then loaded. We are importing the<em> X_train</em> data we got from the model training procedure because it will be used by SHAP to provide explanations for the predictions.</p><p><strong>Step 3: Creating a model class for requests</strong></p><p>We create a class called <em>LoanRequest</em> which defines the structure of the incoming API requests. This is made to be of JSON format with some attributes being required while some are optional.</p><p><strong>Step 4: Defining a Log Transform function</strong></p><p>This is done to prevent model bias by performing log transformation on numerical values fed to the model by handling skewed data. We shall perform this transformation on any input fed to the model through the API.</p><p><strong>Step 5: Defining the loan prediction endpoint</strong></p><p>We make an API endpoint at <em>/loan</em> where one is required to make a <em>POST</em> request to the API with the data structured at step 3. This data is inturn converted to a pandas DataFrame for model input. If the currency entered was put as Kenyan Shilling, it is converted to Indian Rupee. This is because the model was trained on this currency. New features are created from the data. These are <em>income_loan_ratio</em> and <em>credit_score_income_ratio.</em> The redundant features are dropped and log transformation is applied for skew handling. This data is then passed to the model which in turn returns a prediction: <em>1</em> for a loan that is likely to be approved and <em>0</em> for a loan that is likely to be denied.</p><p>If <em>probability</em> was set to<em> true</em>, the predicted class probabilities are returned and if <em>SHAP</em> was set to <em>true</em>, the SHAP waterfall diagram is returned as an encoded base64 string.</p><p>These responses are then converted to JSON and sent to the user as an API response.</p><p><strong>4. Streamlit</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*yFjsQki8SpNc3AhIv-XFsQ.png" /></figure><p>Streamlit is an open-source Python library designed to simplify the creation of interactive web applications for data science and machine learning projects. It allows developers and data scientists to quickly turn Python scripts into user-friendly, shareable web apps without requiring extensive knowledge of web development or front-end technologies like HTML, CSS, or JavaScript.</p><pre>import streamlit as st<br>import pandas as pd<br>import numpy as np<br>import joblib<br>import os<br>from sklearn.ensemble import GradientBoostingClassifier<br>import matplotlib.pyplot as plt<br>import shap<br>import requests<br>import base64<br>from PIL import Image<br>from io import BytesIO<br><br>api_url = &quot;http://fastapi_server:8000&quot;<br><br>st.title(&#39;🤖 Loan Predictor&#39;)<br><br>st.markdown(&quot;This is a loan Predictor App that predicts whether a loan application will be approved or not. It does so by calculating how the following features affect the loan application approval:&quot;)<br>st.markdown(&quot;1. Loan term in years&quot;)<br>st.markdown(&quot;2. Annual income&quot;)<br>st.markdown(&quot;3. Loan amount&quot;)<br>st.markdown(&quot;4. Credit score&quot;)<br>st.markdown(&quot;These are entered on the side panel to the left and predictions are made once the **predict** button is pressed. &quot;)<br>st.markdown(&quot;This project offers the following advantages:&quot;)<br>st.markdown(&quot; -  Clear and Explainable Predictions by use of a SHAP waterfall diagram.&quot;)<br>st.markdown(&quot; -  Custom API Endpoint for Easy Integration.&quot;)<br>st.markdown(&quot; -  Seamless CI/CD Pipeline for Ongoing Improvement&quot;)<br>st.markdown(&quot; &gt; You can find the full project documentation and resources used [here]()&quot;)<br>st.markdown(&quot; &gt; The API documentation can be found here [here](https://loanpredictor.gitbook.io/api-docs)&quot;)<br>payload = {<br>&quot;loan_term&quot;: 0,<br>&quot;annual_income&quot;: 0,<br>&quot;loan_amount&quot;: 0,<br>&quot;credit_score&quot;: 0,<br>&quot;currency&quot;: &quot;KES&quot;,<br>&quot;probability&quot;: False,<br>&quot;SHAP&quot;: False<br>}<br><br>with st.sidebar:<br>    st.header(&quot;Input Features&quot;)<br>    loan_term = st.number_input(&quot;Loan term in years&quot;, 1, 10)<br>    income = st.number_input(&quot;Annual income&quot;, 200000, 10000000, 200000)<br>    loan_amount = st.number_input(&quot;Loan amount&quot;, 300000, 20000000, 300000)<br>    credit_score = st.number_input(&quot;Credit score&quot;, 300, 900, 400)<br>    st.caption(&quot;The credit score should be between 300 and 900, where higher scores indicate better creditworthiness.&quot;)<br>    currency = st.radio(&quot;Currency&quot;, [&quot;Kenyan shilling&quot;, &quot;Indian Rupee&quot;])<br><br>    currency_map = {<br>    &quot;Kenyan shilling&quot;: &quot;KES&quot;,<br>    &quot;Indian Rupee&quot;: &quot;INR&quot;<br>}<br>    currency_api_value = currency_map[currency]<br><br>    predict_button = st.button(&quot;Predict&quot;)<br><br>    response = requests.post(f&quot;{api_url}/loan&quot;, json=payload)<br><br>result_placeholder = st.empty()<br><br>with result_placeholder.container():<br>    st.markdown(<br>        &quot;&quot;&quot;<br>        &lt;div style=&quot;border: 2px solid #ddd; border-radius: 10px; padding: 20px; text-align: center; background-color: #0E1117;&quot;&gt;<br>            &lt;h4 style=&quot;color: #888;&quot;&gt;Predictions are displayed here. Enter features on the side panel to the left.&lt;/h4&gt;<br>        &lt;/div&gt;<br>        &quot;&quot;&quot;,<br>        unsafe_allow_html=True,<br>    )<br><br>if predict_button:<br>    with result_placeholder.container():<br>        with st.spinner(&quot;Making prediction ...&quot;):<br>            payload = {<br>                &quot;loan_term&quot;: loan_term,<br>                &quot;annual_income&quot;: income,<br>                &quot;loan_amount&quot;: loan_amount,<br>                &quot;credit_score&quot;: credit_score,<br>                &quot;currency&quot;: currency_api_value,<br>                &quot;probability&quot;: True,<br>                &quot;SHAP&quot;: True,<br>            }<br>            response = requests.post(f&quot;{api_url}/loan&quot;, json=payload)<br><br>    with result_placeholder.container():<br>        if response.status_code == 200:<br>            result = response.json()<br>            st.write(&quot;### Prediction Result&quot;)<br><br>            if result.get(&quot;prediction&quot;) == 1:<br>                st.success(&quot;The loan application is likely to be approved.&quot;)<br>            else:   <br>                st.error(&quot;The loan application is likely to be rejected.&quot;)<br>            <br>            if &quot;SHAP_plot&quot; in result:<br>                # Decode the base64 image<br>                shap_img = Image.open(BytesIO(base64.b64decode(result[&quot;SHAP_plot&quot;])))<br>                st.image(shap_img, caption=&quot;SHAP Waterfall Plot&quot;)<br><br>        else:<br>            st.write(&quot;Error:&quot;, response.status_code)<br>            st.write(&quot;Message:&quot;, response.text)<br><br>st.markdown(<br>    &quot;&quot;&quot;<br>    &lt;style&gt;<br>        .footer {<br>            position: fixed;<br>            bottom: 0;<br>            left: 0;<br>            width: 100%;<br>            text-align: center;<br>            padding: 10px 0;<br>            background-color: #0E1117;<br>            font-size: 16px;<br>            color: #F9F9F9;<br>        }<br>        .footer a {<br>            color: #007BFF;<br>            text-decoration: none;<br>        }<br>        .footer a:hover {<br>            text-decoration: underline;<br>        }<br>    &lt;/style&gt;<br>    &lt;div class=&quot;footer&quot;&gt;<br>        made with ❤️ by &lt;a href=&quot;https://www.linkedin.com/in/brian-muchai-7380231a7&quot; target=&quot;_blank&quot;&gt; Muchai&lt;/a&gt;<br>    &lt;/div&gt;<br>    &quot;&quot;&quot;,<br>    unsafe_allow_html=True,<br>)<br><br><br></pre><p><strong>Step 1: Importing libraries</strong></p><p>The necessary libraries for data processing, visualization, API interaction, and Streamlit UI are imported.</p><p><strong>Step 2: Defining the API URL</strong></p><p><em>api_url</em> specifies the backend FastAPI server endpoint. <a href="https://fastapi_server:8000/">https://fastapi_server:8000</a> is used when running the server in Docker but <a href="https://localhost:8000/">https://localhost:8000</a> is used when running it locally.</p><p><strong>Step 3: Sidebar Input Features</strong></p><p><em>st.sidebar</em> is used to add input to the sidebar. Input fields are set up so that a user can input <em>loan term</em>, <em>annual income</em>, <em>loan amount</em>, <em>credit score</em> and <em>currency</em>. A predict button is placed at the very bottom which triggers the prediction process when pressed.</p><p><strong>Step 4: Processing the prediction when Predict button is clicked</strong></p><p>The input fields are converted to a JSON payload and sent to the API endpoint <em>/loan</em> with the <em>POST</em> method. If the response is succesful, the app goes ahead to display the results but if an error occured, an error message is displayed instead.</p><p><strong>Step 5: Displaying results</strong></p><p>The prediction results are mapped to some Streamlit messages which show whether the loan was likely to be accepted or denied. The SHAP waterfall diagram is decoded and displayed on the app as an image.</p><p><strong>5. Docker</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*sWmr1Qzj8BJVzkinCU1fHQ.png" /></figure><p>Docker is an open-source platform designed to help developers build, ship, and run applications consistently across different environments. It does so by containerizing applications along with their dependencies into isolated units called <strong>containers</strong>. These containers are lightweight, portable, and run consistently regardless of the underlying operating system or infrastructure. We shall be using Docker to containerize our app so that we can deploy it to the cloud.</p><p>So as to do so, we shall make <em>Dockerfiles</em>, each at the directory where the streamlit app and FastAPI server exist. We shal then write a <em>Docker-compose.yml</em> at the root of the project.</p><p><strong>Streamlit Dockerfile</strong></p><pre>FROM python:3.9-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir --default-timeout=1000 -r requirements.txt<br>COPY . .<br>EXPOSE 8501<br>CMD [&quot;streamlit&quot;, &quot;run&quot;, &quot;streamlit-app.py&quot;, &quot;--server.port=8501&quot;, &quot;--server.enableCORS=false&quot;]</pre><p>We first define the Docker image to use. We use <em>python:3.9-slim</em> which is a lightweight version of Python 3.9. This provides the Python runtime environment needed to run the application. We set<em> /app</em> as the working directory. We then copy the <em>requirements.txt</em> file to the working directory and install the dependencies listed therein.</p><p>We then copy all the files from the local project directory into the <em>/app</em> directory in the container. This ensures that everything is available in the container. We then declare <em>port 8501</em> to be available for external connections as this is where the app will run. We then run the streamlit app by executing <em>streamlit run streamlit-app.py</em>.<em> — server.port=8501</em> ensures that the app runs on port 8501. — <em>server.enableCORS=false</em> disables Cross-Origin Resourse Sharing restrictions</p><p><strong>FastAPI Docker file</strong></p><pre>FROM python:3.9-slim<br>WORKDIR /server<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir --default-timeout=1000 -r requirements.txt<br>COPY . .<br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;server:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>We are pretty much doing the same thing we did on the Streamlit Dockerfile but exporting port 8000 instead.</p><p><strong>Docker-compose.yml file</strong></p><pre>version: &#39;3&#39;<br><br>services:<br>  server:<br>    build: ./server<br>    container_name: fastapi_server<br>    ports:<br>      - &quot;8000:8000&quot;  <br>    networks:<br>      - app_network<br><br>  app:<br>    build: ./app<br>    container_name: streamlit_app<br>    ports:<br>      - &quot;8501:8501&quot;  <br>    depends_on:<br>      - server<br>    networks:<br>      - app_network<br>    environment:<br>      - API_URL=http://fastapi_server:8000 <br><br>networks:<br>  app_network:<br>    driver: bridge</pre><p>The individual containers (services) that make up the application are defined. The fastAPI container is named as <em>fastapi_server</em> for easier reference. <em>Port 8000</em> of the container is mapped to <em>port 8000</em> of the host machine. The fastAPI container is then connected to the <em>app_network</em> so that it can communicate with the Streamlit container</p><p>The Streamlit container is named as streamlit_app. Port 8501 of the container is mapped to port 8501 of the host machine.</p><p>The <em>depends_on: — server </em>in the app service ensures that the server container is always built first before the app container. This is because the app makes background API calls to the server and cannot work as intended if the server is not already running.</p><p>Once we have done this, we can build the containers using the following script. make sure that you are at the root of the repository where the <em>Docker-compose.yml</em> file is before running it.</p><pre>docker-compose build</pre><p>It will take some time during the first build as all the requirements in the respective <em>requirements.txt</em> files are being downloaded. Upon a successful build, we can run the containers with the following script:</p><pre>docker-compose up -d</pre><p>This starts up the two containers and the Streamlit App and API are made available in the following URLs:</p><ul><li>Streamlit App — http://localhost:8501</li><li>FastAPI — http://localhost:8000</li></ul><p>Once both the App and API are available at these URLs, we are ready to deploy the application. This will be covered in <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-3-deployment-and-ci-cd-pipeline-0db5e8d7d078">Part 3</a> of this article series.</p><p><strong>MLOps pipeline</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*50Q9uTz1fuoHYyyl6X6l7w.jpeg" /></figure><p>Something to note about the overall folder structure is that our model will be saved in the <em>/models</em> folder after being trained and tested in the Jupyter notebook. This model will later be imported so that it works with FastAPI.</p><p>Therefore, should we train a better model, we can simply swap the old model with the new model in the <em>/models</em> folder. This new model will be utilized by the API and therefore by any other application dependent on the API.</p><p>It is my hope that you found this article helpful. If so, you can give it some claps. Feel free to share it with your friends. You can also support my work by buying me a cup of coffee ☕ <a href="https://buymeacoffee.com/muchai">here</a> so that I can continue to do what I do best. Cheers. See you guys in <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-3-deployment-and-ci-cd-pipeline-0db5e8d7d078">Part 3</a> of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e437b084ad5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End To End Machine Learning Project (Loan Approval Prediction) — Part 1 — Introduction]]></title>
            <link>https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-prediction-part-1-introduction-541e639b7c5c?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/541e639b7c5c</guid>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[loans]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 10:25:21 GMT</pubDate>
            <atom:updated>2024-12-02T07:54:15.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>End To End Machine Learning Project (Loan Approval) — Part 1 — Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*bvhx7SA6lDicodys8xmloQ.jpeg" /></figure><p>In the world of machine learning, it’s all too easy to get lost into creating complex and more accurate models. But at the core, machine learning should be about solving real world problems. Projects created as a technical showoff may demonstrate skill, but the true potential of machine learning is when it’s applied to create solutions that benefit people and industries. My goal with this project has been to move beyond theoretical knowledge — to build a solution that addresses a real need.</p><p>For us to proceed, I’d like us to put ourselves in the shoes of a Financial Institution which offers loans to its customers. These institutions are of great value to borrowers as they offer some financial support when we really need it. However, these institutions often face some risk; the biggest one being borrowers defaulting on their loans. This has some consequences to themselves as well as the borrowers. Some of these consequences include:</p><p>1. <strong>Financial Losses</strong>: The institution loses the principal amount of the loan, plus any expected interest income. <br>2. <strong>Increased Provisions for Bad Debt</strong>: Financial institutions must set aside funds as provisions to cover anticipated losses from defaults, which can reduce the capital available for new loans or investments. Over time, high provisions can erode profitability and affect the institutions balance sheet.<br>3. <strong>Impact on Credit Risk Rating</strong>: High default rates can negatively affect the institution’s credit rating, making it more difficult to raise funds that it will in turn lend out to the borrowers. <br>4. <strong>Higher Interest Rates for Other Borrowers</strong>: To offset losses, the institution may raise interest rates for other borrowers. This can make loans more expensive, potentially discouraging creditworthy customers.<br>5. <strong>Reputational Damage</strong>: Frequent defaults may hurt the institution’s reputation, particularly if it becomes known for high-risk lending. This can make it harder to attract depositors, investors, and quality customers.<br>6. <strong>Increased Collection and Legal Costs</strong>: The institution may incur additional costs in trying to recover the loan amount through debt collection efforts, legal proceedings, or repossessing assets. These efforts can be time-consuming and often yield only a portion of the loan’s value, adding to the institution’s costs.</p><p>So as to face these risks, it is important for them to know the probability of a customer defaulting on a loan and only issue a loan to those with the lowest likelihood to default. This can be done by building a machine learning model that is trained with previous customer information. It will be able to learn on the lending patterns and when presented with new customer information, be able to predict whether the institution would be likely to issue to the particular customer or not.</p><p>However, having a machine learning model that only tells you whether a customer is likely to be given a loan or not is not enough. For one, we do not know how it came to that decision. Take the case below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*mJit1OIU2hIk-RIPzX9zkw.jpeg" /></figure><p>We have a customer who is requesting for a loan of sh300,000 and is willing to repay it in an year. This person’s annual income is sh700,000 and a credit score of 540. Given this information, it is most likely that the loan will be approved. Let us see what the model thinks…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLE3QiOx704YYOlDJnSLCA.jpeg" /></figure><p>How is this possible? This guy is asking for a loan which is basically 43% of his annual income and is willing to pay back in an year. By intuition, he should be more than capable to pay back, right? If only there was a way to know how the model came to this conclusion. Wait, there actually is. Let us reveal the curtain and take a look at the model’s thought process…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwYecKbwZDR8eyUFeMlpDA.jpeg" /></figure><p>From this, it appears that the model paid a lot of emphasis to the credit score, which resulted in it thinking that this was a high risk customer. As a result, it predicted that the loan was most likely to be denied.</p><p>This makes some sense as credit score ranges from 300, which represents customers with the greatest risk to default to 900 where customers are least likely to default. A credit score of 540 makes this a high risk customer therefore the loan was likely to be rejected.</p><p>However, relying solely on credit score as the only parameter for provision of loan is an oversimplification of the whole loan lending procedure. Profitability is also considered in the decision-making process.</p><p>From the above diagram, it’s quite beneficial to know how the model is thinking, right? We get to fully understand why the model made that decision, making the predictions to be clear and explainable. This level of interpretability makes financial institutions to make informed data driven decisions. It also allows for better risk management as model bias can be easily caught and mitigated.</p><p>There are also some other benefits to why this project would be beneficial to a financial institution besides the predictions being interpretable:</p><ol><li>There is a <strong>custom API endpoint</strong> for easy integration. A user interface is good and all but it is not useful when somebody wants to plug in this solution to their already existing systems. The documentation for the API can he found <a href="https://loanpredictor.gitbook.io/api-docs">here</a>. The custom API is made with <strong>FastAPI</strong> and easily integrates into the <strong>Streamlit</strong> user interface and other systems.</li><li>There is a seamless CI/CD pipeline for ongoing improvement. In an industry where accuracy is critical, I’ve built a continuous integration/continuous deployment (CI/CD) pipeline that allows for smooth, automatic updates. When a new model or improvement is available, it’s seamlessly deployed without downtime. Plus, if a new model requires different inputs, a fresh API endpoint can be set up — allowing smooth transitions without affecting ongoing operations.</li></ol><p>The CI/CD pipeline is made possible using <strong>Github Actions</strong>. There is a <strong>self-hosted runner</strong> on the <strong>DigitalOcean server</strong> where the application is hosted. When new changes are pushed to the<strong> GitHub</strong> Repository where the code is hosted, the runner automatically pulls the new changes, stops the already running <strong>Docker containers</strong> for the application, rebuilds them with the new changes and then reruns them. This ensures that the application with the latest changes is the one deployed to the public.</p><p><a href="https://loanpredictor.live/">Here</a> is the link to the loan prediction dashboard. Feel free to test how the loan term, annual income, loan amount and credit score contribute to the probability of one getting a loan. It can also be assessed through <a href="https://loanpredictor.live/">https://loanpredictor.live/</a>. You can also play around with the prediction API I built. Its documentation can be found <a href="https://loanpredictor.gitbook.io/api-docs">here</a>.</p><p>In <strong>Part 2</strong> of this article series, I will take a dive into how I actually developed the prediction model, built an API endpoint and dashboard for it. In <strong>Part 3</strong>, I will explain how I deployed the application and how I built the CI/CD pipeline together with the tools used. I will also share all the resources that I used for this project in Parts 2 and 3.</p><ul><li><a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-2-development-0e437b084ad5">Part 2</a> — Development</li><li><a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-3-deployment-and-ci-cd-pipeline-0db5e8d7d078">Part 3</a> — Deployment and CI/CD Pipeline</li></ul><p>It is my hope that you found this article helpful. If so, you can give it some claps. Feel free to share it with your friends. You can also support my work by buying me a cup of coffee ☕ <a href="https://buymeacoffee.com/muchai">here</a> so that I can continue to do what I do best. Cheers. See you guys in Part <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-2-development-0e437b084ad5">2</a> and <a href="https://medium.com/@muchaibriank/end-to-end-machine-learning-project-loan-approval-part-3-deployment-and-ci-cd-pipeline-0db5e8d7d078">3</a> of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=541e639b7c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correlation vs. Causation: Your Data Might Be Lying To You]]></title>
            <link>https://medium.com/@muchaibriank/the-correlation-causation-conundrum-why-your-data-might-be-lying-to-you-b89ab89d8dd0?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89ab89d8dd0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 13:51:40 GMT</pubDate>
            <atom:updated>2024-10-06T14:06:54.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*dW8pYVJFon0grc7yAxjVFQ.jpeg" /></figure><p>We have <strong>always</strong> been natural pattern-seekers. It’s built into our brains. Long ago, before math was even discovered, our ancestors were already using pattern recognition in their daily lives. Picture this; a group of hunter-gatherers foraging in the wild. Among the many plants they encounter, mushrooms catch their eye. They develop a taste for them and they become one of their favorite foods. As days go by, they notice that there is an increased number of individuals who were falling sick and dying thereafter.</p><p>They begin to put one and one together— those who were dying were reported to have eaten mushrooms with some distinct black spots. From this, they begin to associate these black-spotted mushrooms with potential death. Through this grim discovery, they learnt to avoid these mushrooms, a crucial insight that saved countless of their lives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSVroOKrLryNKOem4gptdA.jpeg" /></figure><p>Fast forward to the modern era, and pattern recognition is no longer just about survival — it’s about thriving, being among the top one percent.</p><p>Before we go on, let us define some terms:<br><strong>Correlation </strong>— it is the measure of strength and direction of a relationship between two variables. When two variables are correlated, it means they tend to vary together in a consistent pattern. In the example above, the black-spotted mushrooms and illness were positively correlated. This is because when there was an increase in the consumption of those mushrooms, there was a corresponding increase in cases of ailment and eventual death.</p><p><strong>Causation</strong> — implies that a change in one variable directly produces a change in another. From the same example above, eating the black-spotted mushrooms was the cause of illness and eventual death.</p><p>With these terms fully defined, let as explore other examples where correlation and causation are at play.</p><p>A certain company notices a troubling trend in its quarterly sales reports. Sales have been steadily declining over the past three months. Digging upon this, they discover something troubling: there had been a significant drop in customer numbers. It turned out that many customers had been unsubscribing from their service, in turn, leading to a decrease in sales revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIpO_xVwut7KHt7laXowrw.jpeg" /></figure><p>Recognizing this pattern was the first step for them to address this problem. From it, they hypothesize that a declining customer base is driving the sales drop. To combat this, a strategy is devised: launching a loyalty program to reward repeat customers and incentivize referrals. By identifying and acting on this correlation, they aim to turn the tide and boost their revenue once again.</p><p>From foraging for mushrooms to analyzing sales data, the ability to spot patterns has always been a powerful tool. It is particularly useful in a scenario where we are trying to solve a problem. We already have the data at hand to do so, we just have to discover what the data is actually telling us. However, as we do so, we<strong> must be careful</strong>. The line between correlation and causation is thin, and mistaking one for the other can lead to misleading conclusions and costly decisions.</p><p>For example, the decline in sales in the case above wasn’t necessarily because people were leaving the company— not fully at least. People were leaving because of a decrease in income. It was the middle of the Covid-19 pandemic. Thousands of people were getting laid off while others had their salaries significantly reduced. I mean, when your earnings are cut by 50%, will you continue with your online movie subscription or focus more on how you will get a steady food supply?</p><p>Because of this oversight, they ended up implementing a strategy that would not help them gain customers back. Instead, they were literally just throwing money in the drain, leading to even more losses.</p><p>Here is another scenario: you are tasked to investigate why students at a particular school are getting low marks. After doing your research, you discover that most of these students smoke. It is known that smoking can lower somebody’s cognitive ability, therefore, you come up with the conclusion that those particular students are getting low marks because of smoking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoIJpUknlTBWo-b0BuDESw.jpeg" /></figure><p>However, somebody else could argue that these particular students smoke because of getting low grades. They may be getting a lot of pressure from their teachers and parents because of scoring poor marks in their exams, and therefore resort to smoking for some relief.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4sVg6T4I5jCQGuTwlxoJg.jpeg" /></figure><p>Which is which then? Students are getting low marks because they smoke, or they smoke because of getting the low marks. In effort to remaining in scope of the task at hand, you conclude that smoking is the reason that they get low marks. A conclusion that very few can object because you have the data to back it up.</p><p>However, just because you have the data to defend your case does not always mean that you are right. You might have missed out on something, therefore, instead of getting credible insights from the data, it is lying to you instead.</p><p>Let as look at this case in a different perspective. We have students who smoke and they happen to be getting low marks. Rather than these two characteristics causing each other, what if we have some external parameter causing them? This seems possible, right? Let’s further explore it.</p><p>It is known that negative life experiences such as loss of a loved one, stress and peer pressure can cause somebody to smoke and also score low marks in examinations. Upon interviewing a significant number of these students, they confessed the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qph0ZTLAJ8McTHc9vRHzYw.jpeg" /></figure><p>What could have happened if we did not dig deeper into the root cause of why the students were getting low marks? We could have given a recommendation to the school like sensitizing about the dangers of smoking to the students. This, however, would not have fully addressed the problem at hand. The students would have potentially quit smoking but their marks would not have improved.</p><p>The best solution in addressing was looking into why the students were actually failing, not addressing the smoking problem which by coincidence they all happen to have.</p><p>From the two examples, we have learnt that it is of utmost importance to dig deeper into our data. We should understand fully what our data is trying to tell us, not just spotting a correlation and assuming that it is leading to a causation. If we do this, we will fully understand the reasons behind the patterns in our data and give solutions that fully address the problem that we wish to solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89ab89d8dd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNDERSTANDING HOW THE KENYA POWER TOKEN SYSTEM WORKS]]></title>
            <link>https://medium.com/@muchaibriank/understanding-how-the-kenya-power-token-system-works-97fd4d3e1e7e?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/97fd4d3e1e7e</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[smart-devices]]></category>
            <category><![CDATA[smart-grid]]></category>
            <category><![CDATA[smart-grid-technologies]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 17:32:32 GMT</pubDate>
            <atom:updated>2023-08-23T17:32:32.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9SI-47ZVWyaYnFWCmESGg.jpeg" /><figcaption>a CIU (Customer Interface Unit)</figcaption></figure><p>Most of us have seen and interacted with this machine, but have you ever wondered how the Kenya Power Prepaid system works to meter your electric consumption and cut the power when you forget to reload the Tokens? In this reading, we shall learn more about the system, understand how it works, explore some of its vulnerabilities, compare it to other metering systems, and discover its advantages and disadvantages.</p><p>Let’s first look at some keywords we shall use throughout this reading:</p><ol><li><strong>Token</strong> — the 20 digit numeric code provided by Kenya Power. Each Token is unique and contains the amount of electricity units to be credited by the meter for use.</li><li><strong>CIU</strong> (Customer Interface Unit) — this is the official name of the device shown above on which one inputs the Token for loading.</li><li><strong>Daraja</strong> — a sort of bridge that connects M-Pesa to external businesses, e.g Kenya Power.</li></ol><p>Let’s begin by looking at some of the Frequently Asked Questions you may have about the system:</p><ol><li><strong>Why must I always plug the CIU into a wall socket?</strong></li></ol><p><em>I’m sure some of us may have wondered why the CIU must be connected to the wall socket even if it’s running on batteries. The answer is that it communicates by using the electric wires in the house with the meter, a technology known as PLC (Power Line Communication) This communication allows for the loading of Tockens and other functionalities.</em></p><p><strong>2. Why can’t my Token work at my friend’s house?</strong></p><p><em>The Tokens are generated specifically for your meter. Remember the account number you provided when purchasing Tokens? It is used to generate the Token hence making it meter specific.</em></p><p><strong>3. Why can’t Kenya Power load my Tokens remotely?</strong></p><p><em>We may have found ourselves in a situation where our CIU is not working and called customer care, hoping that they could help out. You will often be advised by the Kenya Power personnel to change the batteries in the CIU, plug it in, and try again. This brings up the wonder of why they can’t just load the Tokens onto your meter remotely.</em></p><p><em>The reason why there is no remote loading of Tokens is because the CIU and meter are completely isolated from Kenya Power.</em></p><p><strong>4. How does the system tell if the Tokens are valid?</strong></p><p><em>You may be wondering how the meter tells if the Token you input is valid if it is indeed completely isolated from Kenya Power. To answer this, let’s have a closer look at what the Token really is. The Token is your meter number and corresponding electricity units encrypted in a 20-digit numeric code. This code is then decrypted by the meter, making it possible to have Token validation even if it is completely isolated.</em></p><p><strong>5. How does the meter know that I have exhausted my units?</strong></p><p><em>The meter keeps track of the number of units consumed by a household. For example, when 10 units of power are purchased, the meter counts until 10 units are exhausted. When they are indeed exhausted, it cuts the power to the house until another Token is loaded.</em></p><p>By looking at these questions and their answers, we have gained some understanding of the Kenya Power Pre-paid System. We can even say that this technology is quite ingenious! Now that we have understood the Kenya Power implementation of a meter, let’s take a look at another meter system and do comparisons.</p><h3><strong>CASE STUDY OF ANOTHER METERING SYSTEM</strong></h3><p>There are other meter systems, often for water metering. These systems are a bit different from Kenya Power’s implementation in that they communicate directly with the company they belong to.</p><p>These meters are set up in such a way that they record the readings of the utility consumed, e.g. water, and transmit them to the company. The transmission of these readings is done at equal intervals. When the company discovers that the customer has exhausted their units from the readings transmitted, it sends a signal to the meter instructing it to close the valve/switch.</p><p>Another communication done between the meter and the company is when the customer is purchasing units. Upon successful purchase, the company sends a signal to the meter to instruct it to open the valve/switch. The valve/switch is kept open until the units purchased are exhausted.</p><p>However, this and other forms of communication are kept to a minimum. This is so as to increase the life span of the meters, as they are battery-powered. For this reason, you may find them sending readings once every two days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*f1wwVPr8x52_xl62F3hNWw.png" /></figure><p><strong>ADVANTAGES OF THE KENYA POWER METERING SYSTEM</strong></p><ol><li>Saves on communication costs: as there is no communication between the meter and the company.</li><li>Secure: the Tokens are very difficult to decrypt and reproduce.</li><li>Requires little maintenance.</li><li>Ensures simplicity: as the meters are isolated from the company, there is no need to build a complex infrastructure to allow communication between the meter and the company.</li></ol><p><strong>DISADVANTAGES OF THE SYSTEM</strong></p><ol><li>Tokens cannot be loaded remotely: this may cause inconveniences when the CIU has some technical issues</li><li>Tokens are not transferable: one is forced to sacrifice Tokens that they had already loaded at their previous home before moving to a new place.</li></ol><p>We have come a long way in exploring and understanding Kenya Power’s system. Now, let’s have a look at the payment infrastructure for Tokens. There are several ways of purchasing Tokens, some of them being through M-Pesa, Airtel Money, purchasing through banks, and directly purchasing Tokens from Kenya Power.</p><p>For the rest of this reading, we shall look at M-Pesa infrastructure, as M-Pesa is the most common way of buying Tokens. We will also explore a certain vulnerability in this payment infrastructure.</p><h3>THE WORKING OF THE M-PESA PAYMENT SYSTEM</h3><p>This is by far the easiest way to buy Tokens. Kenya Power integrates with M-Pesa through Daraja. When a customer buys Tokens through M-Pesa, Daraja notifies Kenya Power of the same. Kenya Power, in return, sends the purchased Token through SMS to the customer. A C2B workflow is used in this particular configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Xyu3VPlFFmZ-fXS4kpXpbg.png" /><figcaption>C2B workflow</figcaption></figure><p><strong>STAGES OF THE PAYMENT PROCESS</strong></p><ol><li><strong>Payment initiation</strong></li></ol><p>The customer goes ahead to initiate the payment by purchasing the amount of Tokens they would like through Kenya Power’s Pre-paid Till Number. They enter the account number as their meter number.</p><p>2. <strong>Authentication and authorization</strong></p><p>M-pesa confirms that the PIN entered by the customer is correct to ensure that it was really them who initiated the transaction. Upon successful confirmation, it authorizes the customer to move on to the next steps.</p><p>3. <strong>Payment validation request</strong></p><p>For M-pesa to carry out the transaction, it needs to validate that the account number entered is valid. Since M-pesa does not have a record of Kenya Power Meter numbers, it requests Daraja to validate the same with Kenya Power.</p><p>4. <strong>Validation request</strong></p><p>Daraja communicates with Kenya Power to validate the customer’s account number.</p><p>5. <strong>Validation response</strong></p><p>Kenya Power then responds to determine whether the account number is valid or not. If the account number is correct, the transaction is completed; if the meter number is incorrect, the payment process is aborted.</p><p>6. <strong>Payment validation response</strong></p><p>Daraja then carries forward the response to M-pesa which in turn proceeds with the process or terminates it, depending on the response.</p><p>7. <strong>Payment confirmation</strong></p><p>Upon successful validation of the meter number, M-pesa debits the customer’s M-pesa balance and credits it to Kenya Power’s Till. It then sends a confirmation to Daraja that the payment has been made.</p><p>8. <strong>Payment acknowledgement</strong></p><p>Daraja then acknowledges that the payment has been made prior to notifying Kenya Power of the same.</p><p>9. <strong>M-pesa notification</strong></p><p>M-pesa goes ahead and sends an SMS confirmation to the customer with its corresponding transaction ID and M-pesa balance after the transaction.</p><p>10.<strong> Payment acknowledgement</strong></p><p>Daraja then sends a notification to Kenya Power acknowledging that the payment of a certain amount has been made by the customer.</p><p>11. <strong>SMS with Token</strong></p><p>Kenya Power,, in turn, generates a Token by encrypting the meter number and the number of units equivalent to the amount paid in a 20-digit numeric code. It then sends the Token to the customer for him/her to input it using the CIU.</p><p>By the end of this reading, you will have understood how the whole payment process happens through M-pesa. It is quite fascinating that all of this happens in seconds. Technology is quite interesting!</p><p>Now, for those of you with a keen eye for vulnerabilities, you may have figured out a way of getting a Token message from Kenya Power without necessarily paying for it. If you haven’t, scroll up to the flow chat real quick and try to figure out how this is possible.</p><p>HINT: It’s among the last stages</p><p>You got it? Well done!! Now let’s have a closer look at this vulnerability.</p><p>The vulnerability is at step 10, Payment acknowledgment. For all the nerds out there, you may be thinking of spoofing Daraja’s notification to Kenya Power of Payment Confirmation. This is indeed possible. With enough research, one can send a fake Payment acknowledgment notification to Kenya Power and, in return, get a free ksh 5000+ Token!!</p><p>Before you think of leaving this page and researching how this is possible, stop!!! Safaricom already thought of this vulnerability and implemented a security patch, hoping that Kenya Power implemented it at the time of writing.</p><p>Safaricom encourages companies expecting payment notifications to whitelist only their IP addresses. This would stop any bad actors, such as ourselves, from sending a fake payment notification. A list of these IP addresses is available in Daraja’s documentation.</p><p>Congratulations for making it to the end of this reading. It is my hope that you have learnt how the Kenya Power Meter System and M-Pesa payment infrastructure works. If you have found it helpful, like this post and share it with your friends so that they can also benefit from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97fd4d3e1e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What exactly is Web3?]]></title>
            <link>https://medium.com/@muchaibriank/what-exactly-is-web3-baa2534185e6?source=rss-fb32d74bdd20------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa2534185e6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Brian Muchai]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 06:25:23 GMT</pubDate>
            <atom:updated>2022-10-29T06:25:23.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*jLBRKoRKu4Oa-H_AbDVnJw.jpeg" /></figure><p>For us to understand <strong>Web3</strong>, we must first understand <strong><em>Blockchain</em></strong>. What is Blockchain? It is a <em>distributed permanent database shared among multiple nodes of a computer network</em>. The data is recorded in a way that makes it impossible to modify or hack the system. The Blockchain, as its name suggests, records data in blocks, each block containing a group of transactions. Blockchain allows one to create and manage an array of Web3 functions, including but not limited to <strong>NFTs</strong>, <strong>initiation and execution of transactions</strong> and the <strong>creation of smart contracts</strong>. The concept of Blockchain became popular when <strong>Bitcoin</strong>, a cryptocurrency network, was released back in 2009. The network <em>primarily handles the transfer of the Bitcoin asset across the networks under no regulations while ensuring that the network itself cannot be hacked</em>. Bitcoin, however, inspired the rise of a more capable Blockchain network, <strong>Ethereum</strong>, which is at the core of Web3. Ethereum is a network that <em>supports NFTs, decentralized social networks, decentralized finance</em> and <em>crypto staking</em>. Other Blockchain platforms include: Avalanche, Ripple, Solana, Tron DAO, Polkadot and Hyperledger Fabric.</p><h3>So, why Web3?</h3><blockquote>1. Built on a decentralized platform, giving no central authority access to control the system.</blockquote><blockquote>2. Allows users to interact either publicly or privately without a third party.</blockquote><blockquote>3. Stable as it does not have a single point of failure because of decentralization.</blockquote><blockquote>4. Censorship proof.</blockquote><p>It is without a doubt that Web3 is the future of the Internet and it’s coming sooner than we know it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa2534185e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>