<?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 Michael Faraday Otieno on Medium]]></title>
        <description><![CDATA[Stories by Michael Faraday Otieno on Medium]]></description>
        <link>https://medium.com/@iamfaradayotieno?source=rss-6aa1f9fc9755------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1LjnxKWUhY9-5Y1n</url>
            <title>Stories by Michael Faraday Otieno on Medium</title>
            <link>https://medium.com/@iamfaradayotieno?source=rss-6aa1f9fc9755------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:07:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamfaradayotieno/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[Assessing Data Quality and Business Performance in a Manufacturing MSME Dataset: A Practical MEAL…]]></title>
            <link>https://medium.com/@iamfaradayotieno/assessing-data-quality-and-business-performance-in-a-manufacturing-msme-dataset-a-practical-meal-ee48bed1d012?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee48bed1d012</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[monitoring-and-evaluation]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 19:42:57 GMT</pubDate>
            <atom:updated>2026-10-15T19:42:57.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Assessing Data Quality and Business Performance in a Manufacturing MSME Dataset: A Practical MEAL Exercise</h3><h4>A practical R-based case study of missing data, duplicate records, inconsistent county labels, and revenue differences among Kenyan manufacturing MSMEs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*kH4Uu1-dQXi_H5jhEIg20Q.jpeg" /></figure><p><strong>Introduction</strong></p><p>Monitoring, Evaluation, Accountability and Learning (MEAL) relies on trustworthy data to measure, monitor and evaluate, identify gaps thus making decisions.</p><p>In addition to describing the data, this activity discusses the impact that data quality problems can have on indicator reporting, evaluation, and learning. Since the dataset is cross-sectional without validated programme baseline and follow-up data, differences observed are described as associations and are not necessarily directly attributable to the training.</p><ol><li><strong>Dataset and Methodology</strong></li></ol><p>This exercise uses the original Excel dataset from the <a href="https://github.com/Ocholar/mel-case-study-kenya">MEL Quantitative Case Study: Kenya MSME Manufacturing Analysis</a>, which contains 5,016 records and eight variables covering business identifiers, county, business size, owner’s gender, manufacturing classification, training status, revenue, and employment. The data were imported into R using readxl and analysed using packages including dplyr, stringr, and tibble.</p><p>The assessment independently assessed missing values, repeated identifiers, exact duplicate records, inconsistent county name entries, and anomalously high revenue and employment entries. Next descriptive comparisons were made based on training status, business size, and owner gender. This information was used to develop a draft data quality issue log and recommendations for monitoring, evaluation, accountability, and learning. No permanent data corrections were made during this exercise, and the cross-sectional data cannot be used to imply that training causes variations in business outcomes.</p><p>2. <strong>Data-quality assessment</strong></p><p><em>i. </em><strong><em>Missing Values</em></strong></p><p>The original dataset contained six missing revenue values and six missing employment values, representing a small proportion of the 5,016 original records, but they still matter when calculating indicators.</p><p>For instance, a median revenue calculation excludes records with missing revenue. Consequently, the number of businesses in a group is not necessarily the same as the number of valid revenue observations used to calculate its median.</p><p>Instead of providing an estimate to fill the missing values, I retained them as is and noted the discrepancy. A typical MEAL operations desk approach would be to determine whether the missing data were captured in data collection, not provided by the respondents, or entered wrongly.</p><p><strong><em>ii. Exact duplicates and repeated identifiers</em></strong></p><p>The evaluation discovered one absolute duplicate row within the unique eight variables. Deleting this row dropped the examine set from 5,016 to 5,015 records.</p><p>Another issue, which was more isolated and of greater scale, was about repeated IDs. In the analytical copy there were 519 sets of repeated IDs and 1,037 records from analytical copy belonged to an ID with more than one occurrence.</p><p>Repeated IDs should not automatically be treated as duplicate businesses. In the inspected records, the same ID sometimes appeared alongside different counties or other business records. This raises questions about the intended meaning of the identifier and whether it is supposed to uniquely identify each business.</p><p>I therefore retained these records pending verification. Before using the dataset for official reporting, the data owner should clarify the ID structure and determine whether the repeated values reflect data-entry errors, a record-linkage problem, or a legitimate feature of the original data.</p><p><strong><em>iii. Inconsistent county labels</em></strong></p><p>The original data had 45 different labels for counties, of which there were some apparent spelling variants, such as “Nairobii,” “Nairobi,” and “Narobi.” After eliminating the apparent variants listed during inspection, only 27 distinct labels remained, thus, improving consistency for grouping and summarising the data. However, it does not mean that all county names have been verified against an authoritative list. The standardised labels should still be checked against Kenya’s official county names before county-level findings are used for decision-making.</p><p>This illustrates why data cleaning requires documented rules rather than arbitrary replacement. Every correction should be traceable to an identified issue and, where necessary, verified against the source</p><p><strong><em>iv. Unusual high values</em></strong></p><p>The variables, Revenue and employment, had some very high values. Revenue distribution reported a value of KES 12 billion while the employment distribution reported values of 1,000 and 4,500 employees.</p><p>51 revenue observations and 45 employment observations, which exceeded the 99th percentile threshold, were flagged for further investigation. These flags highlight observations that require further review, and more importantly, do not demonstrate that these values are wrong. High net worth organizations may have justifiable reasons to report values well in excess of those reported by typical micro enterprises.</p><p>I therefore retained these observations rather than applying an arbitrary cutoff. However, they have a substantial influence on mean revenue, making the median a more useful primary statistic for comparing typical reported business outcomes in this dataset.</p><p><strong><em>v. Data quality summary</em></strong></p><p>The initial assessment identified several issues requiring attention before the dataset could be used confidently for reporting and evaluation.</p><ul><li><strong>Original records:</strong> 5,016</li><li><strong>Records in the analytical copy:</strong> 5,015</li><li><strong>Exact duplicate rows excluded:</strong> 1</li><li><strong>Repeated-ID groups requiring review:</strong> 519</li><li><strong>Missing revenue values:</strong> 6</li><li><strong>Missing employment values:</strong> 6</li><li><strong>Distinct county labels before standardisation:</strong> 45</li><li><strong>Distinct county labels after standardisation:</strong> 27</li><li><strong>Revenue observations flagged above the 99th percentile:</strong> 51</li><li><strong>Employment observations flagged above the 99th percentile:</strong> 45</li></ul><p>The flagged values were retained for investigation rather than automatically deleted. Repeated identifiers also remain unresolved pending verification against the source data.</p><p><strong>3. Monitoring findings: training coverages and business outcomes</strong></p><p>Of the <strong>5,015 </strong>records in the analytical copy, <strong>1,490 </strong>were recorded as having received training, while <strong>3,525 </strong>were recorded as having received no training, meaning that <strong>29.7%</strong> of the records were classified as trained.</p><p>For the revenue comparison, <strong>3,521</strong> observations were available in the no-training group and <strong>1,488 </strong>in the trained group. The median reported revenue was KES 22,000 among businesses recorded as untrained and KES 32,750 among those recorded as trained hence the difference between the two medians was KES 10,750.</p><h3>Business outcomes by training status</h3><p><strong>Businesses recorded as having received no training</strong></p><ul><li><em>Records</em>: 3,525</li><li><em>Valid revenue observations</em>: 3,521</li><li><em>Median revenue</em>: KES 22,000</li><li><em>Median employees</em>: 1</li></ul><p><strong>Businesses recorded as having received training</strong></p><ul><li><em>Records</em>: 1,490</li><li><em>Valid revenue observations</em>: 1,488</li><li><em>Median revenue</em>: KES 32,750</li><li><em>Median employees</em>: 2</li></ul><p>The employment figures show a similar descriptive pattern: the median was one employee in the no-training group and two employees in the trained group.</p><p>This is a relevant outcome pattern to investigate further, however, this classification only distinguishes between groups. These variations may be due to size, sector, location, time in business, availability of finance or other characteristics that are not analyzed in this purely descriptive exercise. The results should therefore be treated as an initial comparison, not evidence that training caused higher revenue or employment</p><p><strong>4. Does the pattern differ by business size ?</strong></p><p>Comparing businesses within size categories provides additional context. The median revenue was higher in the trained group across all three recorded business sizes.</p><h3>Business outcomes by size</h3><p><strong>Medium businesses</strong></p><ul><li><em>No training</em>: 5 businesses; median revenue KES 60,000; median employment 67.</li><li><em>Received training</em>: 3 businesses; median revenue KES 300,000; median employment 55.</li></ul><p><strong>Micro businesses</strong></p><ul><li><em>No training</em>: 3,325 businesses; median revenue KES 20,000; median employment 1.</li><li><em>Received training</em>: 1,287 businesses; median revenue KES 30,000; median employment 2.</li></ul><p><strong>Small businesses</strong></p><ul><li><em>No training</em>: 195 businesses; median revenue KES 45,000; median employment 6.</li><li><em>Received training</em>: 200 businesses; median revenue KES 90,750; median employment 6.</li></ul><p>The majority of records are in the microenterprises class. Median revenue in microenterprises was KES 20,000 for untrained businesses and KES 30,000 for trained businesses. Median employment was one and two employees respectively.</p><p>Small enterprise median revenue was KES 45,000 for the no-training group and KES 90,750 for the trained group. The median number of employees per business was six for both groups.</p><p>The medium-business comparison has to be treated with extra care as there are only five untrained and three trained medium business so only a few observations can easily sway the outcome. These comparisons suggest questions for further evaluation, rather than definitive conclusions about the effectiveness of training.</p><p><strong>5. Implications of MEAL practice</strong></p><p>The exercise highlights several practical actions that can strengthen programme monitoring and evaluation.</p><p><strong>Monitoring</strong>: Clearly specify the indicator (how it will be calculated: numerator, denominator, period of reporting and target population). Coverage of training has to be looked into in comparison to the population the target of the training, not the number of labelled records.</p><p><strong>Data quality assurance:</strong> Set validation rules for business IDs, county names, revenues, employment. Keep correction log, analyze anomalies in comparison with source records prior to overwriting or dropping observations.</p><p><strong>Evaluation</strong>: Collect baseline and follow-up data where possible. Document when the training was undertaken and when outcomes were measured. As far as possible, implement a credible comparison design and take account of business differences.</p><p><strong>Accountability</strong>: This dataset does not include details on complaints or feedback, satisfaction, and resolution of the concern. A programme seeking to strengthen accountability would need accessible feedback channels and a documented process for responding to issues raised by participants.</p><p><strong>Learning</strong>: Discuss findings with programme teams, programme investors and the relevant stakeholders. Explore possible reasons for different results, other contextual factors and record whether actions are being taken as agreed. Use learning to drive decisions to change practice rather than produce a dashboard or report.</p><p><strong>6. Limitations</strong></p><p>This exercise has several limitations.</p><p>First, the analysis reflects only the variables available in the dataset. It is unable to date the training in relation to the measurement of revenue and employment, nor the outcomes are validated before and after.</p><p>Second, repeated identifiers remain unresolved. The results assume the retained rows are records in the source dataset, but they should not be interpreted as 5,015 verified unique businesses until the identifier structure has been clarified.</p><p>Third, extreme revenue and employment values were held for further review. They impact the totals and could be valid large businesses, business recording errors or other data anomalies.</p><p>Fourth, county labels were standardised on the basis of the identified spelling variants, but the final set of labels requires validation with an agreed-upon list of counties.</p><p>Finally, the analysis is simply descriptive. The differences observed between the trained and untrained businesses might be due to selection effects, or other feature, not the training. The programme impact cannot be causally identified.</p><p><strong>Conclusion</strong></p><p>A useful MEAL analysis begins by asking whether the data can support the decisions we want to make. In this manufacturing MSME case study, basic data-quality checks identified missing values, an exact duplicate, repeated identifiers, inconsistent county labels, and unusually high observations.</p><p>fter creating an independently cleaned analytical copy, the descriptive analysis found higher median revenue and employment in the group recorded as having received training. These findings provide a starting point for further investigation, not proof of training effectiveness.</p><p>The most important lesson is that data cleaning, indicator interpretation, evaluation design, accountability, and learning are connected. Reliable decisions require transparent methods, documented limitations, and a commitment to verifying the evidence before drawing conclusions.</p><p><em>This article documents a practical MEAL learning exercise using an existing dataset. The analysis and cleaning decisions described here are independent of the original repository’s own analysis</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee48bed1d012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weather + Machine Learning Prediction API]]></title>
            <link>https://python.plainenglish.io/weather-ml-prediction-api-7f704484f1b9?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f704484f1b9</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 17:39:11 GMT</pubDate>
            <atom:updated>2026-01-18T20:02:29.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*L2Mh3VgNemfuO0_gUCR7oA.jpeg" /></figure><h3>Introduction</h3><p>This project demonstrates a <strong>FastAPI API</strong> that combines <strong>real-time weather data</strong> with a <strong>local machine learning model</strong> to make predictions. For example, it can recommend clothing based on the temperature or classify weather-related risk levels.</p><p>All the project files, including the FastAPI app, the lightweight MLP model, test scripts, and requirements, are available on <strong>GitHub</strong>: <a href="https://github.com/FaradayOtieno/ml_weather_api">https://github.com/FaradayOtieno/ml_weather_api</a> you can clone or download the repo and run it locally.</p><p>This project shows:</p><ul><li>Integration of <strong>local ML models</strong> with <strong>external APIs</strong></li><li><strong>Token-based authentication</strong> for secure API access</li><li><strong>Logging, environment variables, and error handling</strong> often skipped by beginners</li><li>Clear <strong>JSON response structure</strong>, suitable for frontend integration</li></ul><h3>Use Cases</h3><ul><li><strong>Personal assistants</strong>: suggest clothing or outdoor activities</li><li><strong>IoT projects</strong>: feed weather data to smart devices and make ML predictions</li><li><strong>Portfolio / learning</strong>: demonstrates API + ML integration, security, and clean design</li></ul><h4>1: Environment Setup</h4><p>We use Python virtual environments, FastAPI, PyTorch for ML, and requests to access online APIs.</p><pre># requirements.txt<br>fastapi<br>uvicorn<br>torch<br>scikit-learn<br>pydantic<br>requests<br>python-dotenv</pre><p><strong>Explanation:</strong></p><p>Specifying dependencies ensures reproducibility. Beginners often skip this step, which leads to “works on my machine” issues. python-dotenv lets you keep API keys and tokens out of your code for security.</p><h4>2: Environment Variables</h4><p>Create a .env file in your project folder:</p><pre>ML_API_TOKEN=secret-token-123<br>OPENWEATHER_API_KEY=YOUR_OPENWEATHER_API_KEY <br><br># i&#39;ll use 4618a0c7f50054e3366003edd475519a</pre><blockquote><em>Replace </em><em>YOUR_OPENWEATHER_API_KEY with your real OpenWeatherMap API key.</em></blockquote><p><strong>Why:</strong></p><ul><li>Prevents hardcoding sensitive information in your code</li><li>Ensures your project is safe to push to GitHub</li></ul><p>Load these variables in your project:</p><pre>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()  # loads .env from current directory<br>ML_API_TOKEN = os.getenv(&quot;ML_API_TOKEN&quot;)<br>OPENWEATHER_API_KEY = os.getenv(&quot;OPENWEATHER_API_KEY&quot;)<br><br>if not ML_API_TOKEN or not OPENWEATHER_API_KEY:<br>    raise ValueError(&quot;API tokens not found in .env file&quot;)</pre><p><strong>Explanation:</strong><br>Using environment variables keeps your secrets safe. Beginners often hardcode API keys, which is insecure.</p><h4>3. Local ML Model</h4><p>We use a <strong>lightweight MLP</strong> that predicts a categorical value based on temperature:</p><pre>import torch<br>import torch.nn as nn<br>import os<br><br># Ensure models folder exists<br>os.makedirs(&quot;models&quot;, exist_ok=True)<br><br>class MLP(nn.Module):<br>    def __init__(self, input_dim=1, hidden_dim=8, output_dim=3):<br>        super().__init__()<br>        self.fc1 = nn.Linear(input_dim, hidden_dim)<br>        self.fc2 = nn.Linear(hidden_dim, output_dim)<br>    <br>    def forward(self, x):<br>        x = torch.relu(self.fc1(x))<br>        x = self.fc2(x)<br>        return x<br><br># Save a dummy model if it doesn&#39;t exist<br>model_path = &quot;models/mlp_model.pth&quot;<br>if not os.path.exists(model_path):<br>    model = MLP()<br>    torch.save(model.state_dict(), model_path)<br>    print(f&quot;✅ Dummy model saved at {model_path}&quot;)</pre><p><strong>Explanation:</strong></p><ul><li>The MLP is intentionally small to run on any machine</li><li>map_location=&quot;cpu&quot; ensures compatibility without GPU</li></ul><h4>4. FastAPI App with Token Authentication</h4><pre>from fastapi import FastAPI, HTTPException, Header, Depends<br>import logging<br>import requests<br>import torch<br>from ml_model import MLP<br><br># Logging setup<br>logging.basicConfig(level=logging.INFO)<br><br># FastAPI app<br>app = FastAPI(title=&quot;ML + Weather Demo API&quot;)<br><br># Token authentication<br>def token_auth(x_api_key: str = Header(...)):<br>    if x_api_key != ML_API_TOKEN:<br>        logging.warning(f&quot;Unauthorized token attempt: {x_api_key}&quot;)<br>        raise HTTPException(status_code=401, detail=&quot;Unauthorized&quot;)<br>    return True<br><br># Load ML model<br>model = MLP()<br>model.load_state_dict(torch.load(model_path, map_location=&quot;cpu&quot;))<br>model.eval()</pre><p><strong>Explanation:</strong></p><ul><li>Protects endpoints with header-based token authentication</li><li>Logging unauthorized attempts helps track potential misuse</li></ul><h4>5. Weather + ML Endpoint</h4><pre>@app.get(&quot;/weather_predict/{city}&quot;)<br>def weather_predict(city: str, auth: bool = Depends(token_auth)):<br>    url = f&quot;http://api.openweathermap.org/data/2.5/weather?q={city}&amp;appid={OPENWEATHER_API_KEY}&amp;units=metric&quot;<br>    res = requests.get(url)<br>    if res.status_code != 200:<br>        raise HTTPException(status_code=404, detail=&quot;City not found or API error&quot;)<br>    <br>    data = res.json()<br>    temp = data[&#39;main&#39;][&#39;temp&#39;]<br>    weather_desc = data[&#39;weather&#39;][0][&#39;description&#39;]<br><br>    # ML prediction<br>    x_tensor = torch.tensor([[temp]], dtype=torch.float32)<br>    with torch.no_grad():<br>        out = model(x_tensor)<br>        pred = torch.argmax(out, dim=1).item()<br>    <br>    logging.info(f&quot;{city}: Temp={temp}°C, ML Prediction={pred}&quot;)<br>    <br>    return {<br>        &quot;city&quot;: city,<br>        &quot;temperature&quot;: temp,<br>        &quot;weather&quot;: weather_desc,<br>        &quot;ml_prediction&quot;: pred<br>    }<br><br>@app.get(&quot;/&quot;)<br>def root():<br>    return {&quot;message&quot;: &quot;ML + Weather Demo API running. Use /weather_predict/{city} with x-api-key header.&quot;}</pre><p><strong>Explanation:</strong></p><ul><li>Requests real-time weather data from OpenWeatherMap</li><li>Converts temperature to a tensor for ML prediction</li><li>torch.no_grad() avoids computing gradients, making it more efficient</li><li>Returns a clean JSON response</li></ul><h4>6. Running the API Locally</h4><pre># Run on Command Prompt<br># For my case, databotenvironment is my virtual environment.<br><br>databotenvironment\Scripts\activate<br>cd C:\Users\user\Desktop\ml_dataset<br>uvicorn ml_weather_demo:app --reload</pre><p><strong>Explanation:</strong></p><ul><li>Visit in browser: <a href="http://127.0.0.1:8000/weather_predict/Nairobi">http://127.0.0.1:8000/weather_predict/Nairobi</a></li><li>Add header: x-api-key: secret-token-123</li></ul><p>✅ You get a JSON response with <strong>real weather + ML prediction</strong>.</p><h4>7. API Test</h4><pre>import requests<br><br># API URL<br>base_url = &quot;http://127.0.0.1:8000/weather_predict/&quot;<br><br># API token<br>headers = {<br>    &quot;x-api-key&quot;: &quot;secret-token-123&quot;<br>}<br><br># Cities for demo<br>cities = [&quot;Mombasa&quot;, &quot;Nairobi&quot;, &quot;Kisumu&quot;, &quot;Garissa&quot;]<br><br># Loop through cities and get predictions<br>for city in cities:<br>    response = requests.get(f&quot;{base_url}{city}&quot;, headers=headers)<br>    if response.status_code == 200:<br>        data = response.json()<br>        print(f&quot;{city} → Temp: {data[&#39;temperature&#39;]}°C, Weather: {data[&#39;weather&#39;]}, ML Prediction: {data[&#39;ml_prediction&#39;]}&quot;)<br>    else:<br>        print(f&quot;{city} → Error: {response.status_code}, {response.json()[&#39;detail&#39;]}&quot;)</pre><h4>Explanation</h4><ol><li><strong>base_url</strong> points to your local FastAPI endpoint.</li><li><strong>headers</strong> include your token for authentication.</li><li>We loop through <strong>Mombasa, Nairobi, Kisumu, and Garissa</strong> and make GET requests.</li><li>If the request succeeds (status_code == 200), we print the <strong>temperature, weather description, and ML prediction</strong>.</li><li>If there’s an error (city not found, API error), we print the error message.</li></ol><p><strong><em>Result;</em></strong></p><pre>Mombasa → Temp: 25.8°C, Weather: scattered clouds, ML Prediction: 1<br>Nairobi → Temp: 18.14°C, Weather: scattered clouds, ML Prediction: 1<br>Kisumu → Temp: 22.22°C, Weather: scattered clouds, ML Prediction: 1<br>Garissa → Temp: 30.69°C, Weather: clear sky, ML Prediction: 1</pre><h4>8. Recommendations</h4><ul><li><strong>Keep secrets safe</strong>: Use .env files, never hardcode tokens</li><li><strong>Log everything</strong>: Track API usage and ML predictions</li><li><strong>Batch predictions</strong>: Extend the API for multiple cities</li><li><strong>Error handling</strong>: Always check external API responses</li><li><strong>Documentation</strong>: FastAPI auto-docs (/docs) are portfolio-friendly</li><li><strong>Deployment</strong>: Host on Render, Heroku, or AWS for public access</li></ul><h4>9. Conclusion</h4><p>This project demonstrates <strong>real-world integration of ML with APIs</strong>:</p><ul><li>FastAPI development</li><li>Token authentication for secure endpoints</li><li>Handling online API data</li><li>Local ML predictions integrated into production-ready endpoints</li></ul><p>It’s a <strong>complete portfolio-ready project</strong> showing <strong>security, logging, and clean design</strong>, not just ML or API separately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f704484f1b9" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/weather-ml-prediction-api-7f704484f1b9">Weather + Machine Learning Prediction API</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Staple Food Price Trends in Kenya: Inflation, Volatility, Seasonality and Predictive Forecasts]]></title>
            <link>https://python.plainenglish.io/staple-food-price-trends-in-kenya-inflation-volatility-seasonality-and-predictive-forecasts-2d3da02ecf58?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3da02ecf58</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[food-security]]></category>
            <category><![CDATA[inflation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 14:35:37 GMT</pubDate>
            <atom:updated>2025-10-02T04:10:21.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*rww969w3iFllU9p-F_TJ5A.jpeg" /></figure><h4>Introduction</h4><p>Food price volatility directly affects household food security in Kenya. Staples like <strong>maize, beans, milk, wheat, and rice</strong> dominate household consumption and act as inflation indicators.</p><p>📌 In this project, I explore staple food price trends using <strong>Python</strong> (for cleaning, analysis, and forecasting) and <strong>Power BI</strong> (for dashboards and interactive visuals). The goal is to uncover <strong>inflation pressure, volatility, seasonality, and future risks</strong> in Kenya’s staple food market.</p><p>🔗 All materials, including datasets, Python scripts, and Power BI files, are available in the GitHub repository:</p><p><a href="https://github.com/FaradayOtieno/wfp_food_price_ke">GitHub - FaradayOtieno/wfp_food_price_ke: Empirical analysis of staple food price trends in Kenya using Python &amp; Power BI. Explores inflation, volatility, seasonality, and forecasting to provide data-driven insights into food security &amp; market stability.</a></p><h4>Project Outline</h4><ol><li>Trends &amp; Inflation Pressure</li></ol><p>🔎 <strong>Questions</strong></p><ul><li>Which commodities have the <strong>fastest rising prices</strong>?</li><li>What’s the <strong>year-on-year (YoY) price increase</strong>?</li></ul><p>2. Volatility &amp; Stability</p><p>🔎 <strong>Questions</strong></p><ul><li>Which commodities are the <strong>most volatile</strong> (riskier for consumers)?</li><li>Which are <strong>stable</strong> (good for food security)?</li></ul><p>3. Seasonality</p><p>🔎 <strong>Questions</strong></p><ul><li>Do prices spike in <strong>certain months</strong> (pre-harvest, drought season)?</li></ul><p>4. Forecasts</p><p>🔎 <strong>Questions</strong></p><ul><li>What are prices likely to be in <strong>January 2026</strong>?</li><li>Are prices expected to <strong>stabilize or keep rising</strong>?</li></ul><h4>🛠️ Deliverables</h4><ul><li><strong>Python Notebook</strong> (cleaning → trend → inflation → volatility → seasonality → forecast → scenarios).</li><li><strong>CSV outputs</strong> (clean dataset, YoY inflation, volatility index, forecast).</li><li><strong>Power BI dashboard</strong> with 4 pages:</li></ul><ol><li>📊 Overview (inflation summary)</li><li>📈 Trends &amp; volatility</li><li>📅 Seasonality heatmap</li><li>🔮 Forecast</li></ol><h4>1. Python Libraries</h4><p>The relevant python libraries for this project:</p><pre>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import statsmodels.api as sm<br>from statsmodels.tsa.seasonal import STL, seasonal_decompose<br>from sklearn.metrics import mean_absolute_error, mean_squared_error<br>from datetime import datetime</pre><h4>2. Load and Understanding the Dataset</h4><pre>df = pd.read_csv(r&#39;C:\Users\user\Desktop\datasets\wfp_food_prices_ken.csv&#39;, low_memory=False)</pre><p>Normalize and check the shape of the data:</p><pre>df.columns = df.columns.str.lower() # normalize<br>print(&quot;rows, cols:&quot;, df.shape)<br>display(df.head(6))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1Wl1WnWeWLjN0CH5ZVxaQ.png" /></figure><p>We have 12189 rows and 16 columns.</p><p>Check column names too;</p><pre># show candidate columns to confirm field names<br><br>[c for c in df.columns if any(k in c for k in<br>                              [&#39;date&#39;, &#39;price&#39;, &#39;commodity&#39;, &#39;market&#39;, &#39;unit&#39;, &#39;usd&#39;])]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*pY3DMYmiOTFOn-7D5HX5hw.png" /></figure><h4>3. Data Cleaning</h4><pre>## Light cleaning<br><br># keep relevant columns<br>cols = [c for c in [&#39;date&#39;, &#39;price&#39;, &#39;commodity&#39;, &#39;market&#39;] if c in df.columns]<br>df = df[cols].copy()<br><br># parse types<br>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;], errors=&#39;coerce&#39;)<br>df[&#39;price&#39;] = pd.to_numeric(df[&#39;price&#39;], errors=&#39;coerce&#39;)<br><br># Drop rows missing date or commodity (essentials)<br>df = df.dropna(subset=[&#39;date&#39;, &#39;commodity&#39;])<br><br># create month for monthly aggregation (first day of month)<br>df[&#39;month&#39;] = df[&#39;date&#39;].dt.to_period(&#39;M&#39;).dt.to_timestamp()<br><br># Trim commodity/market strings<br><br>df[&#39;commodity&#39;] = df[&#39;commodity&#39;].astype(str).str.strip().str.title()<br>if &#39;market&#39; in df.columns:<br>    df[&#39;market&#39;] = df[&#39;market&#39;].astype(str).str.strip().str.title()<br><br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*tAZdAEENYhtEL1_UCSSNkA.png" /></figure><p>From the above code;</p><ol><li>We settle for date, price, column, commodity and market as our relevant columns for the project.</li><li>Incase any row is missing ‘date’ and ‘commodity’, it will be dropped.</li><li>We also, create month which will be useful later in our DAX measure operations and also in visualizations.</li></ol><h4>4. Conservative price imputation &amp; National monthly aggregation</h4><pre>## Conservative price imputation &amp; national monthly aggregation<br><br># impute missing prices conservatively and aggregate to national monthly averages<br><br>#global median fallback<br><br>global_med = df[&#39;price&#39;].median()<br><br># compute median at multiple granulation for conservative imputation<br># (commodity, market, month) -&gt; (commodity, month) -&gt; commodity -&gt; global<br><br>med_exact = df.groupby([&#39;commodity&#39;, &#39;market&#39;, &#39;month&#39;])[&#39;price&#39;].median().rename(&#39;med_exact&#39;) if &#39;market&#39; in df.columns else pd.Series()<br>med_cm = df.groupby([&#39;commodity&#39;, &#39;month&#39;])[&#39;price&#39;].median().rename(&#39;med_cm&#39;)<br>med_c = df.groupby(&#39;commodity&#39;)[&#39;price&#39;].median().rename(&#39;med_c&#39;)p<br><br># merge median back<br><br>df = df.merge(med_cm.reset_index(), on=[&#39;commodity&#39;, &#39;month&#39;], how=&#39;left&#39;)<br>df = df.merge(med_c.reset_index(), on= [&#39;commodity&#39;], how=&#39;left&#39;)<br>if &#39;market&#39; in df.columns:<br>    df = df.merge(med_exact.reset_index(), on=[&#39;commodity&#39;, &#39;market&#39;, &#39;month&#39;], how=&#39;left&#39;)<br><br># impute function<br><br>def fill_price(row):<br>    if pd.notnull(row[&#39;price&#39;]):<br>        return row[&#39;price&#39;]<br>    if &#39;market&#39; in df.columns and pd.notnull(row.get(&#39;med_exact&#39;)):<br>        return row[&#39;med_exact&#39;]<br>    if pd.notnull(row.get(&#39;med_cm&#39;)):<br>        return row[&#39;med_cm&#39;]<br>    if pd.notnull(row.get(&#39;med_c&#39;)):<br>        return row[&#39;med_c&#39;]<br>        <br>df[&#39;price_filled&#39;] = df.apply(fill_price, axis=1)</pre><p><strong>Explanation:</strong> We impute missing prices using progressively broader medians to avoid throwing away many rows.</p><p>Then we compute the national monthly average per commodity (avg_price).</p><pre># aggregate to national monthly average per commodity<br><br>national = df.groupby([&#39;commodity&#39;, &#39;month&#39;], as_index=False)[&#39;price_filled&#39;].mean().rename(columns={&#39;price_filled&#39;:&#39;avg_price&#39;})<br>national = national.sort_values([&#39;commodity&#39;, &#39;month&#39;]).reset_index(drop=True)<br><br># save cleaned history for Power BI<br>national.to_csv(&quot;national_monthly_clean_csv&quot;, index=False)<br><br>display(national.head(8))</pre><p>This national.csv table answers trend/inflation and is Power BI–ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*ZAW6JvKQ8_LFWwNJoD0WSA.png" /></figure><h4>5. Trends &amp; Inflation Pressure (who is rising fastest; YoY)</h4><pre>## Trends &amp; Inflation Pressure (who is rising fastest; YoY)<br><br># Cell E — Trend &amp; YoY<br># compute YoY and average annual growth rate per commodity<br>national[&#39;yoy_pct&#39;] = national.groupby(&#39;commodity&#39;)[&#39;avg_price&#39;].pct_change(12) * 100<br><br># compute mean YoY over last 12 months per commodity (robust indicator)<br>latest_month = national[&#39;month&#39;].max()<br>recent_12 = national[national[&#39;month&#39;] &gt; (latest_month - pd.DateOffset(months=24))]  # last 2 yrs<br><br>mean_annual_growth = recent_12.groupby(&#39;commodity&#39;)[&#39;yoy_pct&#39;].mean().reset_index().rename(columns={&#39;yoy_pct&#39;:&#39;mean_yoy_pct&#39;})<br>mean_annual_growth = mean_annual_growth.sort_values(&#39;mean_yoy_pct&#39;, ascending=False)<br><br># Top 10 fastest rising commodities<br>top_risers = mean_annual_growth.head(10)<br>display(top_risers)<br><br># Plot top 4 risers&#39; historical series<br>top4 = top_risers[&#39;commodity&#39;].head(4).tolist()<br>plt.figure(figsize=(12,5))<br>for c in top4:<br>    s = national[national[&#39;commodity&#39;]==c].set_index(&#39;month&#39;)[&#39;avg_price&#39;]<br>    plt.plot(s.index, s.values, label=c)<br>plt.title(&quot;Price trends — top 4 YoY risers (avg YoY over recent period)&quot;)<br>plt.xlabel(&quot;Month&quot;); plt.ylabel(&quot;Avg price&quot;)<br>plt.legend(); plt.show()<br><br># Save YoY table<br>mean_annual_growth.to_csv(&quot;commodity_mean_annual_yoy.csv&quot;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*dXPRB5xpRvnD-TyVVfyhiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZoz96ziI6V7envajfErbA.png" /></figure><p><strong>Explanation :</strong></p><ol><li>‘top_risers’ gives the commodities with fastest rising prices</li><li>‘yoy_pct’ is the YoY percent change; you can quote values for specific commodities, e.g., “Maize YoY = X% in latest month</li><li>From the graph, we can beans (Rosecoco) is highly ustable whilst Milk (Camel, Fresh) is relatively stable.</li></ol><h4>6. Volatility &amp; Stability ranking</h4><pre># Use monthly returns (pct_change) to capture month-to-month volatility<br>returns = national.copy()<br>returns[&#39;month_ret&#39;] = returns.groupby(&#39;commodity&#39;)[&#39;avg_price&#39;].pct_change()<br><br>vol = returns.groupby(&#39;commodity&#39;)[&#39;month_ret&#39;].agg([&#39;std&#39;,&#39;mean&#39;]).reset_index()<br>vol[&#39;volatility_index&#39;] = (vol[&#39;std&#39;] / vol[&#39;mean&#39;].abs()).replace([np.inf, -np.inf], np.nan).fillna(0)<br>vol = vol.sort_values(&#39;volatility_index&#39;, ascending=False)<br><br># stable commodities are those with low volatility_index<br>stable = vol.tail(10)<br>volatile = vol.head(10)<br><br>display(volatile[[&#39;commodity&#39;,&#39;volatility_index&#39;]].head(10))<br>display(stable[[&#39;commodity&#39;,&#39;volatility_index&#39;]].head(10))<br><br># Save<br>vol.to_csv(&quot;commodity_volatility_index.csv&quot;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CuepafxlTIZypUAPCdAYFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*LscUT1rHLN_81z1xQ3SfJQ.png" /></figure><p><strong>Explanation: </strong>The volatility table highlights commodities most at risk of sudden price shocks (notably fuel and staple grains), where stabilization measures would have the greatest impact. Conversely, the stable table suggests commodities with predictable trends, making them reliable for social programs and long-term planning. Policymakers can use this dual lens to both mitigate risk and ensure resilience in food and market systems.</p><ol><li><strong>Interpretation of Volatility Table</strong></li></ol><ul><li>Commodities like fuel (petrol, diesel, kerosene) dominate the high-volatility list, suggesting strong exposure to global oil markets and external shocks. This volatility often has spillover effects on transport and food costs, amplifying inflationary pressures.</li><li>Sorghum (red) and maize flour appearing here indicates staple food vulnerability, directly impacting household food security.</li></ul><p>2. <strong>Interpretation of Stable Table</strong></p><ul><li>The stable group (milk, beans, onions, rice imports) shows items with relatively predictable prices, making them suitable for nutritional programs and longer-term social safety nets.</li><li>Zero volatility in red onions suggests either controlled pricing, steady supply, or possible data gaps — worth flagging as an anomaly for validation.</li></ul><h4>7. Seasonality checks (monthly patterns, STL decomposition)</h4><pre># 1) Monthly seasonal pattern across years (heatmap-ready)<br>seasonal = national.copy()<br>seasonal[&#39;month_num&#39;] = seasonal[&#39;month&#39;].dt.month<br>monthly_pattern = seasonal.groupby([&#39;commodity&#39;,&#39;month_num&#39;])[&#39;avg_price&#39;].mean().reset_index()<br>monthly_pattern.to_csv(&quot;monthly_pattern_by_commodity.csv&quot;, index=False)<br><br># 2) STL decomposition example for a commodity with enough history<br>example = top4[0]  # from earlier<br>ts = national[national[&#39;commodity&#39;]==example].set_index(&#39;month&#39;)[&#39;avg_price&#39;].asfreq(&#39;MS&#39;)<br>if ts.dropna().shape[0] &gt;= 36:<br>    stl = STL(ts.interpolate().ffill().bfill(), period=12, robust=True)<br>    res = stl.fit()<br>    fig = res.plot()<br>    fig.set_size_inches(12,6)<br>    plt.suptitle(f&quot;STL decomposition — {example}&quot;)<br>    plt.show()<br>else:<br>    print(f&quot;Not enough monthly history for STL on {example} (need ~36 months).&quot;)</pre><p>The output: Not enough monthly history for STL on Milk (Camel, Fresh) (need ~36 months).</p><p><strong>Explanation:</strong> <em>Our codes works as intended. This arises because STL decomposition requires at least ~3 years of monthly data to reliably separate trend, seasonality, and residuals. For commodities with shorter histories (e.g., Camel Milk), seasonal analysis is instead summarized via monthly aggregation (heatmap), while STL is reserved for those with longer time series.</em></p><h4>8. Forecasting (SARIMAX baseline) and Jan 2026 estimate</h4><pre># SARIMAX forecast for a maize, and Jan 2026 prediction<br><br>from statsmodels.tsa.statespace.sarimax import SARIMAX<br><br>def sarimax_forecast(commodity_name, horizon_months=12, order=(1,1,1), seasonal_order=(0,1,1,12)):<br>    s = national[national[&#39;commodity&#39;]==commodity_name].set_index(&#39;month&#39;)[&#39;avg_price&#39;].asfreq(&#39;MS&#39;)<br>    s = s.interpolate().ffill().bfill()<br>    <br>    # fit model on full history<br>    model = SARIMAX(s, order=order, seasonal_order=seasonal_order, enforce_stationarity=False, enforce_invertibility=False)<br>    res = model.fit(disp=False)<br>    fc = res.get_forecast(steps=horizon_months)<br>    fc_mean = fc.predicted_mean<br>    fc_ci = fc.conf_int()<br>    return s, res, fc_mean, fc_ci<br><br>commodity_to_forecast = &quot;Maize&quot;  # change as needed<br>s, res, fc_mean, fc_ci = sarimax_forecast(commodity_to_forecast, horizon_months=18)  # 18 to include Jan 2026 if needed<br><br># determine the predicted value for January 2026<br>target_date = pd.Timestamp(&quot;2026-01-01&quot;)<br>if target_date in fc_mean.index:<br>    jan2026_pred = float(fc_mean.loc[target_date])<br>    jan2026_ci_lower = float(fc_ci.loc[target_date].iloc[0])<br>    jan2026_ci_upper = float(fc_ci.loc[target_date].iloc[1])<br>    print(f&quot;{commodity_to_forecast} prediction for Jan 2026: {jan2026_pred:.2f} (CI: {jan2026_ci_lower:.2f} - {jan2026_ci_upper:.2f})&quot;)<br>else:<br>    print(&quot;Model horizon does not reach Jan 2026 — increase `horizon_months` or forecast date.&quot;)<br><br># Save forecast table (next 12 months from last historical month)<br>fc_out = pd.DataFrame({&#39;month&#39;: fc_mean.index, &#39;forecast_price&#39;: fc_mean.values})<br>fc_out = pd.concat([fc_out, fc_ci.reset_index(drop=True)], axis=1)<br>fc_out[&#39;commodity&#39;] = commodity_to_forecast<br>fc_out.to_csv(f&quot;forecast_sarimax_{commodity_to_forecast.replace(&#39; &#39;,&#39;_&#39;)}.csv&quot;, index=False)</pre><p><strong>Explanation:</strong> Using a SARIMAX model with seasonal adjustment, maize prices are projected to reach <strong>67.7</strong> in January 2026, with a 95% confidence range of <strong>44.2–91.2</strong>. This suggests moderate price growth but with significant uncertainty, underscoring the need for continued monitoring and risk preparedness.</p><h4>9. Power BI Dashboard</h4><p>With the cleaned national monthly dataset prepared in Python (national_monthly_csv) and supporting outputs (YoY growth, volatility index, forecasts), the next step was building an <strong>interactive Power BI dashboard</strong>.</p><p>Power BI complements the Python analysis by:</p><ul><li>Presenting results in a <strong>clear, visual format</strong> for decision-makers.</li><li>Allowing <strong>drill-down exploration</strong> of staples across time.</li><li>Summarizing insights across <strong>inflation, volatility, seasonality, and forecasts</strong> in four dashboard pages.</li></ul><h4>9.1 Executive Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LZb7He8PeN1FfrCOVyXFg.png" /></figure><p>The dashboard opens with a <strong>high-level snapshot</strong> of staple food prices in Kenya:</p><ul><li><strong>Latest Average Food Price:</strong> KSh 1.58K</li><li><strong>Overall Average Food Price:</strong> KSh 1.90K</li><li><strong>Most Expensive Staple:</strong> Cowpeas at <strong>KSh 9.00K</strong></li></ul><p>The trend line (year vs. average price) shows that <strong>food prices surged sharply after 2020</strong>, reflecting post-pandemic supply shocks and inflationary pressure. Interestingly, the data also suggests a <strong>downward correction towards the end of that year</strong>, hinting at short-term stabilization despite long-term upward pressure.</p><p>The following DAX Measures were used to achieve the visual above:</p><pre>AvgFoodPrice = AVERAGE(national_monthly_clean[avg_price])</pre><pre>LatestMonthAvgPrice = <br>CALCULATE(<br>    AVERAGE(national_monthly_clean[avg_price]),<br>    FILTER(<br>        national_monthly_clean,<br>        national_monthly_clean[month] = MAX(national_monthly_clean[month])<br>    )<br>)</pre><pre>MostExpensiveStaple = <br>VAR CurrentMonth = MAX(national_monthly_clean[month])<br>VAR TableThisMonth =<br>    FILTER(national_monthly_clean, national_monthly_clean[month] = CurrentMonth)<br>RETURN<br>    MAXX(TableThisMonth, national_monthly_clean[avg_price])</pre><pre>MostExpensiveStapleName =<br>VAR CurrentMonth = MAX(national_monthly_clean[month])<br>VAR TableThisMonth =<br>    FILTER(national_monthly_clean, national_monthly_clean[month] = CurrentMonth)<br>RETURN<br>    TOPN(1, TableThisMonth, national_monthly_clean[avg_price], DESC)</pre><h4>9.2 Inflation and Volatility</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mLa-ZSHwPGrDf4fkMea1Q.png" /></figure><h4>9.2.1 Inflation</h4><p>Based on our results, the following was observed:</p><ul><li>Maize consistently stayed <strong>-50% to -60% YoY</strong>, rarely positive.</li></ul><p>→ <strong><em>This indicates sustained deflationary pressure, suggesting oversupply or structural market weakness.</em></strong></p><ul><li>Wheat flour and rice showed <strong>moderate declines</strong> (less severe).</li></ul><p><strong><em>→ These commodities remain sensitive to market shifts but with less drastic swings.</em></strong></p><ul><li>Milk showed <strong>stable but slightly negative inflation trends</strong>.</li></ul><p><strong><em>→ Stability here implies resilience, making milk a relatively reliable staple.</em></strong></p><h4>9.2.2 Volatility</h4><ul><li>Vegetable Oil → <strong>most volatile</strong> (high price risk).</li></ul><p><strong><em>→ High exposure to global market shocks makes it a key risk factor for household food budgets.</em></strong></p><ul><li>Rice → moderately volatile.</li></ul><p><strong><em>→ While less risky than oil, rice still demands close monitoring for potential price surges.</em></strong></p><ul><li>Maize &amp; Milk → <strong>more stable</strong>, lower consumer risk.</li></ul><p><strong><em>→ This stability reduces consumer risk and offers predictability for long-term planning.</em></strong></p><p><strong><em>Key DAX Measures:</em></strong></p><pre>YoY Safe % = <br>VAR CurrPrice = AVERAGE ( national_monthly_clean_csv[avg_price] )<br>VAR PrevPrice = [PrevYearPriceMeasure]<br>VAR YoY = DIVIDE ( CurrPrice - PrevPrice, PrevPrice )<br>RETURN<br>IF (<br>    ISBLANK ( YoY )<br>        || YoY &gt; 2    // &gt; 200% inflation<br>        || YoY &lt; -2,  // &lt; -200% deflation<br>    BLANK (),<br>    YoY<br>)</pre><pre>Price Volatility = <br>STDEVX.P (<br>    VALUES ( national_monthly_clean_csv[month] ),<br>    CALCULATE ( AVERAGE ( national_monthly_clean_csv[avg_price] ) )<br>)</pre><h4>9.3 Seasonality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNAB5tRSCXGMOgCM7Nidng.png" /></figure><p>The immediate observation is:</p><ul><li><strong>Maize</strong><br> <em>→ Prices typically </em><strong><em>dip during harvest seasons</em></strong><em> when supply is abundant, then </em><strong><em>rise during off-season</em></strong><em> months as stocks tighten.</em></li></ul><p>Additionally, after clicking the other commodity from the slicer (which you can check on the .pbix file at</p><p><a href="https://github.com/FaradayOtieno/wfp_food_price_ke/tree/main">https://github.com/FaradayOtieno/wfp_food_price_ke</a>):</p><ul><li><strong>Rice &amp; Wheat</strong><br> <em>→ Both show </em><strong><em>import-driven spikes</em></strong><em>, often aligning with </em><strong><em>high-demand periods</em></strong><em> or disruptions in international trade.</em></li><li><strong>Milk</strong><br><em> → Exhibits </em><strong><em>mild seasonality</em></strong><em>, with prices </em><strong><em>firming in dry seasons</em></strong><em> (lower production) and </em><strong><em>easing during rainy seasons</em></strong><em> when supply increases.</em></li></ul><h4>9.4 <strong>Forecast (Maize Example)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOmCw_A48siixs5P8kHsjg.png" /></figure><p>Based on our findings:</p><ul><li><strong>Mid-2025:</strong><em> Model projects a </em><strong><em>slight price rise around mid-year</em></strong><em>, reflecting seasonal tightening.</em></li><li><strong>Late-2025:</strong> <em>Prices are expected to </em><strong><em>decline toward year-end</em></strong><em>, reaching about </em><strong><em>67.5 Ksh/kg by December</em></strong><em>.</em></li><li><strong>2026 Outlook:</strong> <em>Forecast indicates </em><strong><em>potential stabilization</em></strong><em>, with prices settling into a more predictable range.</em></li></ul><h4>9.5 Policy Implications</h4><ul><li><strong>Vegetable Oil Volatility</strong><br> → Given its sharp and unpredictable price swings, vegetable oil should be a <strong>priority for monitoring and stabilization measures</strong>.</li><li><strong>Early-Warning Systems</strong><br> → Strengthening <strong>food security early-warning systems</strong> can help anticipate shocks and guide timely interventions.</li><li><strong>Import Diversification</strong><br> → Expanding and diversifying <strong>import sources</strong> for key staples will reduce exposure to external market disruptions and price spikes.</li></ul><h4>10. 📌 Conclusion</h4><p>This project reveals how staple food prices in Kenya are shaped by <strong>inflationary pressures, volatility across commodities, and seasonal cycles</strong>. Insights from the analysis include:</p><ul><li>📈 <strong>Rising price levels</strong> after 2020, with sharp peaks followed by partial corrections.</li><li>🌾 <strong>Cowpeas</strong> emerged as the most expensive staple, while <strong>maize</strong> showed recurring seasonal dips post-harvest.</li><li>📊 <strong>Volatility patterns</strong> highlight beans as the most unstable, while milk prices remain comparatively stable.</li><li>🔮 Forecasting suggests that staple prices will likely remain elevated, posing continued challenges for household food security.</li></ul><h4>11. ✅ Recommendations</h4><ul><li><strong>Policy Makers &amp; Regulators</strong> →<em> Strengthen food price monitoring systems to anticipate inflation shocks and protect vulnerable households.</em></li><li><strong>Farmers &amp; Traders</strong> →<em> Leverage seasonal patterns for planting/harvesting and align storage/distribution strategies to reduce volatility.</em></li><li><strong>Researchers &amp; Analysts</strong> → <em>Combine statistical modeling (Python) with accessible dashboards (Power BI) for more holistic, actionable insights.</em></li></ul><h4>12. 🚀 Closing &amp; Call to Action</h4><p>This project demonstrates the value of <strong>integrating Python for empirical analysis with Power BI for interactive dashboards</strong> to better understand and communicate food security risks.</p><p>All datasets, scripts, and dashboards are openly available in my GitHub repository:<br> 🔗 <a href="https://github.com/FaradayOtieno/wfp_food_price_ke">https://github.com/FaradayOtieno/wfp_food_price_ke</a></p><p>I plan to continue expanding this work with more predictive models, additional datasets, and regional comparisons.</p><p>💡 <strong>Your feedback is invaluable</strong> — if you’re a researcher, policymaker, or data enthusiast, feel free to explore the repo, suggest improvements, or collaborate. Together, we can turn data into actionable solutions for food security in Kenya and beyond.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3da02ecf58" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/staple-food-price-trends-in-kenya-inflation-volatility-seasonality-and-predictive-forecasts-2d3da02ecf58">Staple Food Price Trends in Kenya: Inflation, Volatility, Seasonality and Predictive Forecasts</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Geospatial Clustering of Health Facilities in Kenya Based on Location and Ownership Type]]></title>
            <link>https://python.plainenglish.io/geospatial-clustering-of-health-facilities-in-kenya-based-on-location-and-ownership-type-bc248a129262?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc248a129262</guid>
            <category><![CDATA[geospatial-analytics]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 09:13:22 GMT</pubDate>
            <atom:updated>2025-09-02T00:12:04.959Z</atom:updated>
            <content:encoded><![CDATA[<p>This project explores the spatial distribution of healthcare facilities in Kenya using clustering techniques. It investigates how facilities ownership (e.g., MOH, private clinics etc.) relates to geographical distribution patterns.</p><p>Using KMeans and DBSAN, we identify:</p><p>· Regional clusters of healthcare facilities</p><p>· Outliers and remote facilities</p><p>· Ownership influence on facility location</p><h4>Dataset</h4><p>· Source: Cleaned CSV file from official Kenyan health facility data (<a href="https://energydata.info/dataset/kenya-healthcare-facilities">https://energydata.info/dataset/kenya-healthcare-facilities</a>)</p><p>· Fields Used:</p><p>i) Facility Name</p><p>ii) Latitude and Longitude</p><p>iii) Owner</p><h4>1. Load and Preview the Dataset</h4><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import DBSCAN<br>from sklearn.preprocessing import StandardScaler<br><br># Load the dataset<br>df = pd.read_csv(r&#39;C:\Users\user\Desktop\datasets\healthcare_facilities.csv&#39;, encoding=&#39;latin1&#39;)</pre><ul><li>Check the shape of the Data:</li></ul><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myoMPbEv3A-n_aU1F1Gw-w.png" /></figure><ul><li>Information about our dataset:</li></ul><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*AWYamrhRAfHp1QC5j8IShQ.png" /></figure><p>We see that only ‘Facility_N’, ‘Latitude’ and ‘Longitude’ are numerical but all the rest are categorical.</p><ul><li>Check for null values:</li></ul><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*rOLWfYy7GpVWlZgH5uR0YA.png" /></figure><p>Good News! No null values in our data.</p><h4>2. DBSCAN for Density-Based Clustering</h4><p>The goal is to identify patterns in the healthcare facility distribution in Kenya, even the remote ones!</p><p>We will use longitude and latitude as coordinates for DBSCAN</p><pre># Use only coordinates for DBSCAN<br>coords = df[[&#39;Latitude&#39;, &#39;Longitude&#39;]]</pre><p>Then, scale the features for DBSCAN</p><pre># Scale the features (DBSCAN is distance-based)<br>scaler = StandardScaler()<br>coords_scaled = scaler.fit_transform(coords)<br><br># Apply DBSCAN<br>db = DBSCAN(eps=0.3, min_samples=5)  # tune eps &amp; min_samples<br>db.fit(coords_scaled)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*OnSsl52nQfPE3r6X-IVN9Q.png" /></figure><p>Next, we will add cluster labels to our dataframe</p><pre># Add cluster labels to dataframe<br>df[&#39;DBSCAN_cluster&#39;] = db.labels_<br><br># -1 indicates noise (i.e., outliers)<br>outliers = df[df[&#39;DBSCAN_cluster&#39;] == -1]<br>inliers = df[df[&#39;DBSCAN_cluster&#39;] != -1]</pre><p>N/B: <strong>Outliers refer to remote healthcare facilities but the meaning is not what you think! This will be explained just after we visualize our clusters of the healthcare facilities</strong></p><pre># Plotting<br>plt.figure(figsize=(10, 6))<br>plt.scatter(inliers[&#39;Longitude&#39;], inliers[&#39;Latitude&#39;], c=df[df[&#39;DBSCAN_cluster&#39;] != -1][&#39;DBSCAN_cluster&#39;], cmap=&#39;tab10&#39;, label=&#39;Clustered&#39;)<br>plt.scatter(outliers[&#39;Longitude&#39;], outliers[&#39;Latitude&#39;], c=&#39;red&#39;, label=&#39;Outliers (Remote Facilities)&#39;, marker=&#39;x&#39;)<br>plt.xlabel(&#39;Longitude&#39;)<br>plt.ylabel(&#39;Latitude&#39;)<br>plt.title(&#39;DBSCAN Clustering of Health Facilities in Kenya&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bvrzn7aG5Hnblpm7B5ChZw.png" /></figure><p>We now get a very beautiful clusters of the healthcare facilities using location coordinates (latitude and longitude).</p><p>· <strong>Interpretation</strong></p><p>i) DBSCAN performed density-based clustering, meaning it clusters closely packed points. It only identified core regions with many health facilities (e.g., urban areas) but also successfully marked outliers, which correspond to remote or rural clinics. This made the clustering naturally follow the shape of Kenya, visually aligning with known health access patterns.</p><p>ii) The algorithm detected one major outlier — a health facility located significantly far from the rest. This suggests that most regions represented in the dataset have at least one known health facility nearby, meaning they are not geographically isolated based on the density threshold defined in the model.</p><p>iii) In simple terms, even though some facilities are located in far-off regions, if they’re close to at least one other facility, DBSCAN does not classify them as remote(outliers). WHY? Because DBSCAN thinks in terms of neighbors — not how far a point looks on the map visually, but whether it’s isolated based on a set distance threshold (eps).</p><p><strong>3.</strong> <strong>KMeans for Ownership Identification</strong></p><pre>## Identify the ownership of the health facilities<br><br>import seaborn as sns<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br><br># Step 2: Check relevant columns<br>df = df[[&#39;Facility_N&#39;, &#39;Owner&#39;, &#39;County&#39;, &#39;Latitude&#39;, &#39;Longitude&#39;]]<br><br># Step 3: Drop missing values<br>df = df.dropna()</pre><p><strong><em>! Remember ‘Owner’ was categorical? Now, we introduce LabelEncoder()</em></strong></p><pre># Step 4: Encode &#39;Owner&#39; (categorical) to numeric<br>le = LabelEncoder()<br>df[&#39;Owner_encoded&#39;] = le.fit_transform(df[&#39;Owner&#39;])</pre><p>Our interest will be on ‘Latitude’, ‘Longitude’ and ‘Owner_encoded’</p><pre># Step 5: Prepare data for clustering<br>X = df[[&#39;Latitude&#39;, &#39;Longitude&#39;, &#39;Owner_encoded&#39;]]</pre><p>We therefore use the Elbow Method to help identify the number of clusters we can use to group the health facilities based on where they are and who owns them.</p><pre># Step 6: Determine the optimal number of clusters (Elbow method)<br>inertia = []<br>for k in range(1, 10):<br>    kmeans = KMeans(n_clusters=k, random_state=42)<br>    kmeans.fit(X)<br>    inertia.append(kmeans.inertia_)<br><br># Plot the Elbow<br>plt.figure(figsize=(8, 4))<br>plt.plot(range(1, 10), inertia, marker=&#39;o&#39;)<br>plt.xlabel(&#39;Number of Clusters (k)&#39;)<br>plt.ylabel(&#39;Inertia&#39;)<br>plt.title(&#39;Elbow Method For Optimal k&#39;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42OB2drVeLv0ax_azs_3BA.png" /></figure><p>We settle for k=4 and apply it to kmeans:</p><pre># Step 7: Apply KMeans with k=4 (or your chosen k)<br>kmeans = KMeans(n_clusters=4, random_state=42)<br>df[&#39;Cluster&#39;] = kmeans.fit_predict(X)</pre><p>Then, Introduce PCA for 2D visualization:</p><pre># Step 8: Use PCA for 2D visualization<br>pca = PCA(n_components=2)<br>principal_components = pca.fit_transform(X)<br>df[&#39;PCA1&#39;] = principal_components[:, 0]<br>df[&#39;PCA2&#39;] = principal_components[:, 1]<br><br># Step 9: Visualize clusters<br>plt.figure(figsize=(10, 6))<br>sns.scatterplot(data=df, x=&#39;PCA1&#39;, y=&#39;PCA2&#39;, hue=&#39;Cluster&#39;, palette=&#39;Set1&#39;, s=60)<br>plt.title(&#39;Healthcare Facilities Clustering (PCA 2D View)&#39;)<br>plt.legend(title=&#39;Cluster&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znafDh2n87hyBnUbKQ8FwA.png" /></figure><p>· <strong>Interpretation</strong></p><p>i) Clustering was done based on latitude and longitude, thus, clusters look like long vertical bands, because latitude dominates the distance calculation in KMeans.</p><p>ii) The goal was to identify regional patterns in healthcare facility distribution.</p><p>iii) The algorithm revealed 4 main spatial clusters, vertically-aligned due to:</p><ul><li>Kenya’s tall geographical shape</li><li>Uneven scaling of geographical features (latitude spans more than longitude)</li><li>KMeans using Euclidean distance, which treats each coordinate equally without considering actual physical geography.</li></ul><pre>print(df.groupby(&#39;Cluster&#39;).size())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*neKOjEhdWQb7l4OEUOHu0Q.png" /></figure><p>Cluster 0 had the most facilities while 2 was the least.</p><p>Now, a breakdown of who owns the most facilities per cluster:</p><pre>from sklearn.preprocessing import LabelEncoder<br><br>encoder = LabelEncoder()<br>df[&#39;Owner_encoded&#39;] = encoder.fit_transform(df[&#39;Owner&#39;])<br><br># Group by Cluster and Ownership for Insight<br><br>cluster_summary = df.groupby([&#39;Cluster&#39;, &#39;Owner&#39;]).size().unstack(fill_value=0)<br>print(cluster_summary)</pre><p>A snippet of our result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*B_4E4VnJydZ0E7ZYyl6iWQ.png" /></figure><ul><li>Visually:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwH_CksD9sCYk-wq6B3mgg.png" /></figure><pre># Gradient-style view in notebook<br>cluster_summary.style.background_gradient(cmap=&#39;Oranges&#39;, axis=1).set_caption(&quot;Facility Ownership by Cluster&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhv7q6NXdD9PVuWAUwU8Sg.png" /></figure><h4>4. Conclusion</h4><p>Ownership plays a role in spatial distribution. Such a project is useful for Ministry of Health, NGOs, or data journalists exploring access equity in healthcare.</p><p>It can also help in identifying areas that seem neglected to aligning with the Universal Health Coverage for better access to quality healthcare countrywide.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc248a129262" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/geospatial-clustering-of-health-facilities-in-kenya-based-on-location-and-ownership-type-bc248a129262">Geospatial Clustering of Health Facilities in Kenya Based on Location and Ownership Type</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering Crop Suitability with Machine Learning: A Clustering Approach]]></title>
            <link>https://python.plainenglish.io/uncovering-crop-suitability-with-machine-learning-a-clustering-approach-0bf54a6acf84?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bf54a6acf84</guid>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[agriculture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 08:52:51 GMT</pubDate>
            <atom:updated>2025-09-02T00:11:59.931Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Overview</li></ol><p>This project applies unsupervised machine learning techniques: KMeans and PCA Visualization to recommend the most suitable crop to grow based on environmental conditions and soil nutrients levels. Using publicly available dataset from Kaggle, we predict the ideal crop for a given combination of:</p><p>· Nitrogen (N)</p><p>· Phosphorus (P)</p><p>· Potassium (K)</p><p>· Temperature (Celsius)</p><p>· Humidity (%)</p><p>· pH Level(pH)</p><p>· Rainfall (mm)</p><h4><strong>2. Objective</strong></h4><p>To discover data-driven crop suitability zones based on environmental and soil conditions.</p><h4><strong>3. Tech Stack</strong></h4><p>· Python (Scikit-Learn, Pandas, Matplotlib, Seaborn)</p><p>· Jupyter Notebook</p><p>4. <strong>Understanding the Data</strong></p><p>The dataset used in the project is obtained from Kaggle and it is publicly accessible from (<a href="https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset">https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset</a>).</p><pre>import pandas as pd<br><br>df = pd.read_csv(r&#39;C:\Users\user\Desktop\datasets\Crop_recommendation.csv&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBpLo0ePzqXQ21D9Jn9XMQ.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVAA8BiZPRVqil8KbR5Rjw.png" /></figure><p>We see that we have ‘label’ as our only categorical data.</p><p>Another important step is to check null values and shape of our data.</p><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WF4OMu90RB5WuwA_0pXTNQ.png" /></figure><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBMiS77pwijdiY0Rz6DoTA.png" /></figure><p>Good news, our data has no null values.</p><h4>5. <strong>Data Preprocessing and Model Building</strong></h4><p>Next is to identify our features and Target for our study. Early we found that ‘label’ was categorical so it will be our target(y), dependent variable, for the study while the rest (crop conditions) will be our features(X), Independent variable.</p><pre># Features and Target<br><br>X = df.drop(&#39;label&#39;, axis=1)<br>y = df[&#39;label&#39;]</pre><p>Let’s now train our data model by importing the necessary libraries and go further to check the precision score for our classification report:</p><pre>## Train Crop Recommendation Model<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, accuracy_score<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)<br>clf = RandomForestClassifier()<br>clf.fit(X_train, y_train)<br><br>y_pred = clf.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFPxw4nhvXAcHijmJqZNfA.png" /></figure><p>The results show:</p><p>i) An accuracy of around 99.3% meaning the model is performing well</p><p>ii) High precision and recall for almost all crops meaning:</p><p>· Very few false positives (precision)</p><p>· Very few false negatives (recall)</p><p>iii) The F1-Score, which balances both, is also near-perfect.</p><p>iv) Rice has a slightly lower recall (0.89), meaning it missed a couple of true rice samples.</p><p>v) Jute and Lentil had precision at 0.92, meaning a few samples were misclassified as jute or lentil incorrectly.</p><p><strong>N/B:</strong> <strong>It’s worth noting that Random Forest Classifier is learning the pattern in the data very well.</strong></p><p>? <strong>Which crops are getting confused are confused with others</strong></p><pre># Confusion Matrix: To visualize which crops are getting confused<br><br>from sklearn.metrics import ConfusionMatrixDisplay<br>ConfusionMatrixDisplay.from_estimator(clf, X_test, y_test, xticks_rotation=90)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2be4MEZo3rhWSiqg-H736A.png" /></figure><p>For instance, it is found that:</p><p>i) Rice is at a time predicted as jute</p><p>ii) Mouth bean at one time as Lentil</p><p><strong>? Which crop condition is most important in our study</strong></p><pre># Feature Importance<br><br>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>feature_importance = pd.Series(clf.feature_importances_, index=X.columns)<br>feature_importance.sort_values().plot(kind=&#39;barh&#39;, figsize=(8,6))<br>plt.title(&quot;Feature Importance&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYt9pCclOUW1hZ9bmgX6FQ.png" /></figure><ul><li><strong>Cross-validation for more robust evaluation</strong></li></ul><pre># Cross-validation for more robust evaluation<br><br>from sklearn.model_selection import cross_val_score<br>scores = cross_val_score(clf, X, y, cv=5)<br>print(&quot;Cross-validation scores:&quot;, scores)<br>print(&quot;Mean CV accuracy:&quot;, scores.mean())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V-8LtEyPXvQc-bhv_erQw.png" /></figure><p>Instead of one train/test split, it:</p><p>i) Split the data into 5 (or more) parts</p><p>ii) Trains on 4, test on 1, rotates</p><p>And this provides a more reliable performance estimate and we get a beautiful set of cross-validation scores with a mean accuracy of around 99.41%. This also confirms our model is not over-fitting and performance is stable.</p><p><strong>6.</strong> <strong>Unsupervised Machine Learning</strong></p><h4>i) KMeans Clustering</h4><p>Main aim of using K-Means is to help explore which crops do well in each cluster which is useful in regional crop planning.</p><pre>from sklearn.cluster import KMeans<br><br>kmeans = KMeans(n_clusters=4, random_state=42)<br>clusters = kmeans.fit_predict(X)<br><br># Add cluster column to the original DataFrame<br>df[&#39;Cluster&#39;] = clusters</pre><p>I grouped similar soil and weather conditions into 4 distinct clusters, using all features in X.</p><pre># Quick Cluster Counts<br><br>print(df.groupby(&#39;Cluster&#39;).size())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*LIOoxLoUX9vKikzr0Ovx3A.png" /></figure><p>We have cluster 0 as the most frequented and 3 as least.</p><p>Let’s analyze each cluster’s characteristics:</p><pre>cluster_summary = df.groupby(&#39;Cluster&#39;)[X.columns].mean()<br>print(cluster_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*d9J3DX4n_EjNRt-BodL7jg.png" /></figure><p>Compared to our overall means for ease of interpretation:</p><pre>overall_mean = df[X.columns].mean()<br>overall_mean</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*u9ACMskYjYmrVxYcvjCd-Q.png" /></figure><p>What the table tells us is:</p><p><strong>0 — </strong>Low NPK, Neutral pH, moderate humidity &amp; Rainfall — Possibly less fertile land</p><p><strong>1 — </strong>Very high nitrogen(N), low K, humid — Fertile, wet — good for leafy crops</p><p><strong>2 — </strong>Moderate NPK, highest rainfall — Rain-fed fertile regions</p><p><strong>3 — </strong>Extremely high P &amp; K, lowest pH (acidic) — Rare/extreme — likely needs lime treatment.</p><p>Visual interpretation:</p><pre>overall_mean = df[X.columns].mean()<br>cluster_mean = df.groupby(&#39;Cluster&#39;)[X.columns].mean()<br>deviation = cluster_mean.subtract(overall_mean)<br><br>deviation.style.background_gradient(cmap=&#39;coolwarm&#39;, axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*wyCRIpaFnKg4gLQ4jgjk7w.png" /></figure><h4><strong>? which crops dominate each cluster?</strong></h4><pre># which crops dominate each cluster?<br><br>df.groupby(&#39;Cluster&#39;)[&#39;label&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*4NQNAx4yRTPdiO36FYcOzg.png" /></figure><p>Visual:</p><pre>df.groupby(&#39;Cluster&#39;)[&#39;label&#39;].value_counts().unstack().fillna(0).style.background_gradient(cmap=&#39;YlGn&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqJyqsemd1BrDR7Ari2hfg.png" /></figure><p>We see for example that in Cluster 0, crops like Mango, Chicken Pea etc. do well, Maize is not suitable and the conditions here are not suitable for crops like bananas, apples etc.</p><h4>ii) <strong>PCA (Principal Component Analysis)</strong></h4><p>PCA reduces the high-dimensional input data (X) into 2 principal components, which are linear combinations of the original features, chosen to capture the most variance in the data.</p><pre>## Visualize Clusters with PCA (2D)<br><br>from sklearn.decomposition import PCA<br><br>pca = PCA(n_components = 2)<br>components = pca.fit_transform(X)<br>df[&#39;PC1&#39;] = components[:, 0]<br>df[&#39;PC2&#39;] = components[:, 1]<br><br>plt.figure(figsize =(10,6))<br>scatter = plt.scatter(df[&#39;PC1&#39;], df[&#39;PC2&#39;], c=df[&#39;Cluster&#39;], cmap=&#39;tab10&#39;, alpha=0.6)<br>plt.xlabel(&#39;PCA Component 1&#39;)<br>plt.ylabel(&#39;PCA Component 2&#39;)<br>plt.title(&#39;Clustering of Crop Condition&#39;)<br>plt.legend(*scatter.legend_elements(), title=&quot;Cluster&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*8ftNJPuxC3L4Ba5ztPpwhg.png" /></figure><p>So, in the scatter plot:</p><p>i) Each point = One record (i.e. one data row: crop conditions)</p><p>ii) Color = cluster</p><p>iii) Location = relative condition based on NPK, Temp etc. compressed into PC1/PC2</p><ul><li>How to Interpret the Plot:</li></ul><p>i) Tight groups of the same plot — strong, well-defined clusters.</p><p>ii) Overlap between colors — similarity between those clusters.</p><p>iii) Spread of each cluster — Diversity of conditions inside a cluster.</p><p>Hence for cluster 3 which is well separated it forms distinct crop-growing environments.</p><h4>7. Conclusion</h4><p>From this project, it can be easily applied in real-world to help identify crop suitability zones from environmental and soil data. This is a milestone as data science can be used in bridging the gap in food security in a nation, and improve agricultural practices which in turn will be useful for the government and profitable to the farmers too.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bf54a6acf84" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/uncovering-crop-suitability-with-machine-learning-a-clustering-approach-0bf54a6acf84">Uncovering Crop Suitability with Machine Learning: A Clustering Approach</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sales and Profit Performance Dashboard with SQL Integration — Financial Sample Case Study]]></title>
            <link>https://medium.com/@iamfaradayotieno/sales-and-profit-performance-dashboard-with-sql-integration-financial-sample-case-study-7285a7860b9a?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/7285a7860b9a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 12:31:40 GMT</pubDate>
            <atom:updated>2025-06-03T12:31:40.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sales and Profit Performance Dashboard with SQL Integration — Financial Sample Case Study</h3><ol><li><strong>Introduction</strong></li></ol><p>This project explores a financial dataset containing product sales, profits, discounts, and regional performance across various markets. Using SQL, I performed comprehensive data cleaning, exploration, and analysis to uncover insights such as top-performing products, profit margins, discount impacts, and sales trends over time. The results were then visualized in Power BI through dynamic dashboards highlighting key metrics and comparisons by segment, region, and time. This end-to-end workflow demonstrates my ability to derive actionable insights from raw data using both SQL and Power BI</p><p><strong>2. Study Objective</strong></p><p>Analyze sales and profit performance across different market segments and countries to identify growth opportunities and profitability trends.</p><p>3. <strong>Understanding the Dataset</strong></p><p>The <em>Financial Sample.xlsx</em> file contains sales and profit data for a fictional company across various segments, products, regions, and months. The dataset is available at <a href="https://www.kaggle.com/datasets/konstantinognev/financial-samplexlsx">https://www.kaggle.com/datasets/konstantinognev/financial-samplexlsx</a> and the respective files for the study are available at <a href="https://github.com/FaradayOtieno/sales-profit-dashboard">https://github.com/FaradayOtieno/sales-profit-dashboard</a></p><p>N/B: The data is clean.</p><p>4. <strong>SQL Component</strong></p><p>Microsoft SQL is the first step for our end to end project. We simulate the backend using a SQL database. Here’s what we can do:</p><p>The respective table design for our data is:</p><pre>--- &quot;portfolio_projects&quot; is the name to the database i created.<br><br>use portfolio_projects;<br><br>--- Now lets create the table;<br><br>CREATE TABLE Finances (<br>Segment VARCHAR(50) NOT NULL,<br>Country VARCHAR(50) NOT NULL,<br>Product VARCHAR(50) NOT NULL,<br>Discount_Band VARCHAR(50) NOT NULL,<br>Units_Sold INT NOT NULL,<br>Manufacturing_Price MONEY NOT NULL,<br>Sale_Price MONEY NOT NULL,<br>Gross_Sales MONEY NOT NULL,<br>Discounts MONEY NULL,<br>Sales MONEY NOT NULL,<br>COGS MONEY NOT NULL,<br>Profit MONEY NULL,<br>Date DATE NOT NULL,<br>Month_Number INT NOT NULL,<br>Month_Name VARCHAR(20) NOT NULL,<br>Year INT NOT NULL<br>);</pre><p>We can check for nulls;</p><pre>--- Check for Nulls<br><br>SELECT <br> COUNT(*) - COUNT(Segment) AS Null_Segment,<br> COUNT(*) - COUNT(Country) AS Null_Country,<br> COUNT(*) - COUNT(Units_Sold) AS Null_UnitsSold<br>FROM Finances</pre><blockquote>Sample SQL Queries for Data Analysis</blockquote><p>Total Sales and Profit</p><pre>SELECT<br> SUM(Sales) as Total_Sales,<br> SUM(Profit) AS Total_Profit<br>FROM Finances;</pre><p>Top 5 Products by Sales</p><pre>SELECT<br> Product,<br> SUM(Sales) AS Total_Sales<br>FROM Finances<br>GROUP BY Product<br>ORDER BY Total_Sales DESC;</pre><p>Sales and Profit by Country and Segment</p><pre>SELECT<br> Country,<br> Segment,<br> SUM(Sales) AS Total_Sales,<br> SUM(Profit) AS Total_Profit<br>FROM Finances<br>GROUP BY Country, Segment</pre><p>Discount Effect on Profit Margin</p><pre>SELECT<br> Discount_Band,<br> AVG(Discounts) AS Avg_Discount,<br> AVG(Sales) AS Avg_Sales,<br> AVG(Profit) AS Avg_Profit,<br> AVG(Profit) / AVG(Sales) AS Profit_Margin<br>FROM Finances<br>GROUP BY Discount_Band</pre><p>Sales and Profit by Segment</p><pre>SELECT<br> Segment,<br> SUM(Sales) AS Sales,<br> SUM(Profit) AS Profit<br>FROM Finances<br>GROUP BY Segment<br>ORDER BY Sales DESC;</pre><p>Total Profit and Sales by Country</p><pre>SELECT<br> Country,<br> SUM(Profit) AS Total_Profit,<br> SUM(Sales) AS Total_Sales<br>FROM Finances<br>GROUP BY Country<br>ORDER BY Total_Profit</pre><p>Profit Margin by Segment</p><pre>SELECT <br> Segment,<br> ROUND(SUM(Profit) / NULLIF(SUM(Sales), 0), 2) AS Profit_Margin<br>FROM Finances<br>GROUP BY Segment<br>ORDER BY Profit_Margin DESC;</pre><p>Above is just a sample of SQL Queries. The rest of the queries are at <a href="https://github.com/FaradayOtieno/sales-profit-dashboard">https://github.com/FaradayOtieno/sales-profit-dashboard</a>.</p><p>5. <strong>Power BI Dashboard</strong></p><p>The goal of the dashboard is to help monitor regional and segment-level performance using interactive KPIs and visuals.</p><h3>Business Questions</h3><p>We’ll design the project around <strong>answering critical business questions</strong> like:</p><h4>Sales &amp; Revenue Focus</h4><ul><li>What are the <strong>total sales</strong>, <strong>units sold</strong>, and <strong>profit</strong> this year?</li><li>Which <strong>countries and regions</strong> perform best in terms of <strong>sales</strong> and <strong>profit</strong>?</li><li>How does <strong>sales performance change over time</strong> (monthly/quarterly)?</li><li>What are the <strong>top 5 products</strong> by revenue?</li></ul><h4>Profitability &amp; Margins</h4><ul><li>Which <strong>segments or products</strong> yield the <strong>highest profit margins</strong></li><li>Are there <strong>unprofitable regions</strong> or products to review?</li></ul><h4>Discount &amp; Pricing Impact</h4><ul><li>Does applying <strong>discounts improve or hurt</strong> overall profitability?</li><li>How does the <strong>discount band</strong> affect <strong>profit margins</strong>?</li></ul><p><strong>6. Data Cleaning and Modeling (Power BI)</strong></p><p>Done in <strong>Power Query Editor</strong> and <strong>Power BI DAX</strong>.</p><h4>Transformations:</h4><ul><li>Split Date into Year, Month, and Quarter.</li><li>Remove unnecessary columns (like Month Number if redundant).</li><li>Ensure numeric types are correct (e.g., Sales, Profit as decimals).</li></ul><h4>New Columns:</h4><ul><li>Gross Margin % = DIVIDE([Profit], [Sales])</li><li>Profit per Unit = DIVIDE([Profit], [Units Sold]</li><li>Discount Rate = DIVIDE([Discounts], [Gross Sales])</li></ul><p>Below are the DAX Queries;</p><pre>Top Product = CALCULATE(MAX(financials[Product]), TOPN(1, financials, financials[ Sales]))<br>Profit Margin % = DIVIDE([Total Proft], [Total Sales])<br>Total Proft = SUM(financials[Profit])<br>Total Sales = SUM(financials[ Sales])<br>Total Units = SUM(financials[Units Sold])<br></pre><p><strong>7. Dashboard Design (Main Pages)</strong></p><h4>Executive Summary</h4><p><strong>Visuals</strong>:</p><ul><li>KPIs: Total Sales, Total Profit, Gross Margin %, Top Product</li><li>Cards &amp; DAX measures</li><li>Slicer: Year, Country, Segment</li></ul><h4>Sales and Time Analysis</h4><p><strong>Visuals</strong>:</p><ul><li>Line chart: Sales over time</li><li>Bar chart: Sales by Segment or Product</li><li>Area Chart: Sales by Segment over Time</li></ul><h4>Profitability Insights</h4><p><strong>Visuals</strong>:</p><ul><li><em>Bar chart:</em> Profit by Product or Segment</li><li><em>Scatter plot:</em> Sales vs. Discount by Profit</li><li><em>Conditional formatting table:</em> Profit Margin by Country/Product</li></ul><h4>Discount Impact</h4><p><strong>Visuals</strong>:</p><ul><li>Column chart: Discounts by Month</li><li>Matrix table: Discount Band vs Discount</li><li>KPI Card: Average Discount Rate</li></ul><p>The results are as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXcq4kXVO7MgDq1rrwf65Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHSQtRmkFQzl00wuCS1x5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfIpFWwEBvuRbCb_wPcSYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vb86AZxqT57DL-OuBkkTQ.png" /></figure><p><strong>8. Conclusion</strong></p><p>This project not only sharpened my SQL and Power BI skills but also deepened my understanding of financial analytics and data storytelling. By transforming raw transactional data into meaningful insights, I was able to present a clear narrative of business performance. It reaffirmed my passion for turning complex data into clarity — and reinforced why I pursue data science with purpose and conviction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7285a7860b9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantifying Cognitive Load from writing using NLP and Complexity Metrics — A Case Study of Dante’s…]]></title>
            <link>https://medium.com/@iamfaradayotieno/quantifying-cognitive-load-from-writing-using-nlp-and-complexity-metrics-a-case-study-of-dantes-c2e05dfa2f9c?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e05dfa2f9c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[literature]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Wed, 14 May 2025 22:03:26 GMT</pubDate>
            <atom:updated>2025-05-14T22:03:26.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quantifying Cognitive Load from writing using NLP and Complexity Metrics — A Case Study of Dante’s Inferno</h3><h4>Introduction</h4><p>Cognitive load theory explains the mental effort required to process information. In textual content, factors such as syntactic structure, vocabulary, semantics, and discourse cohesion contribute to this load. This project aims to quantify cognitive load from literary using a combination of natural language processing (NLP) techniques and linguistic complexity metrics. Dante’s Inferno, a dense and symbolic literary work, provides an ideal corpus for testing such models due to its layered meaning, archaic structure, and intricate descriptions.</p><h4>Problem Statement</h4><p>While readability metrics like Flesch-Kincaid estimate ease of reading, they fail to fully capture the cognitive demand placed on readers, especially I literature. The project seeks to fill this gap by developing a more nuanced, multi-dimensional approach to modeling cognitive load in text using NLP.</p><h4>1. Import Libraries</h4><p>Let’s import the required python libraries.</p><pre>## Import Libraries<br><br>import pandas as pd<br>from textblob import TextBlob<br>import textstat<br>from wordcloud import WordCloud<br>import matplotlib.pyplot as plt<br>import re<br>from collections import Counter</pre><p>N/B: It should be noted that I use jupyter notebook therefore in order to install a given library then include the exclamation mark before pip, i.e.</p><pre>!pip install pandas </pre><h4>2. Load Data</h4><p>Provided in my GitHub folder</p><p><a href="https://github.com/FaradayOtieno/cognitive_load_inferno">https://github.com/FaradayOtieno/cognitive_load_inferno</a></p><p>is a copy of both the English translated version of Dante’s inferno and a text document, which I complied:</p><p>· Canto I — symbol of spiritual of confusion</p><p>· Canto III — “Abandon all hope…” Inscription at the gate of hell.</p><p>· Canto V — Tragic Love (Paolo and Francesca)</p><p>· Canto VI — The gluttonous</p><p>· Canto XIII — Suicides: Harrowing images of souls turned into trees.</p><p>· Canto XXXIV — Satan frozen in ice, the climax of Hell.</p><p>The above will be ideal for our focused analysis.</p><p>Hence,</p><pre># Load Dante text<br>with open(r&quot;C:\Users\user\Desktop\datasets\dante_inferno.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>    inferno = file.read()</pre><h4>3. Data Preprocessing</h4><p>We proceed to split the cantos and process them each separately. Textblob library is essential in the processing our text.</p><pre># Split into sections (e.g., Cantos)<br><br>sections = [s.strip() for s in inferno.split(&quot;Canto&quot;) if s.strip()]<br>cantos = [f&quot;Canto {s}&quot; for s in sections]<br><br>metrics = []<br>all_words =[]<br><br># Process each Canto<br><br>for i, text in enumerate(cantos, 1):<br>    blob = TextBlob(text)<br>    words = re.findall(r&#39;\b\w+\b&#39;, text.lower())</pre><h4>4. NLP + Cognitive Load Metrics</h4><p>Complexity Metrics will include:</p><p>· FleschEase — Higher is easier to read (scale: 0–100)</p><p>· FKGrade — U.S. school grade level required to understand</p><p>· SMOG — Estimation of years of education needed</p><p>· DifficultWords — Count of complex words</p><p>· LexicalDiversity — Ratio of unique words to total words</p><p>· AvgSentenceLength — Average number of words per sentence</p><p>· Dale-Chall Score — assess how easy or difficult a text is to read</p><p>· Automated Readability Index — estimate the <strong>U.S. grade level</strong> required to understand a piece of text</p><pre># NLP+ Cognitive Load Metrics<br><br>metrics.append({<br>        &quot;FleschEase&quot;: textstat.flesch_reading_ease(text),<br>        &quot;FKGrade&quot;: textstat.flesch_kincaid_grade(text),<br>        &quot;SMOG&quot;: textstat.smog_index(text),<br>        &quot;DifficultWords&quot;: textstat.difficult_words(text),<br>        &quot;LexicalDiversity&quot;: round(len(set(words)) / len(words), 3),<br>        &quot;AvgSentenceLength&quot;: textstat.avg_sentence_length(text),<br>        &quot;Polarity&quot;: blob.sentiment.polarity,<br>        &quot;Subjectivity&quot;: blob.sentiment.subjectivity<br>})<br>all_words.extend(words)<br><br>text = &quot;Your full text or canto here.&quot;<br><br>print(&quot;Flesch Reading Ease:&quot;, textstat.flesch_reading_ease(text))<br>print(&quot;Flesch-Kincaid Grade:&quot;, textstat.flesch_kincaid_grade(text))<br>print(&quot;SMOG Index:&quot;, textstat.smog_index(text))<br>print(&quot;Automated Readability Index:&quot;, textstat.automated_readability_index(text))<br>print(&quot;Dale-Chall Score:&quot;, textstat.dale_chall_readability_score(text))<br>print(&quot;Difficult Words:&quot;, textstat.difficult_words(text))<br>print(&quot;Lexicon Count:&quot;, textstat.lexicon_count(text))<br>print(&quot;Average Sentence Length:&quot;, textstat.avg_sentence_length(text))<br><br># save the metrics into csv <br><br>df = pd.DataFrame(metrics)<br>df.to_csv(&quot;dante_metrics.csv&quot;, index=False)</pre><p>The results from the saved csv file “dante_metrics.csv” are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrzl42BOheS3NBifhnLn_Q.png" /></figure><p>For the first Canto;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCnmu3QoGHwuxNzHrB6Kzg.png" /></figure><h4>5. WordCloud</h4><p>A key focus was placed on understanding the emotional depth and thematic patterns within the textual data. To achieve this, a WordCloud was first employed to provide a visual summary of the most frequently used terms.</p><pre>### Generate WordCloud<br><br>text_combined = &quot; &quot;.join(all_words)<br>wordcloud = WordCloud(width=1000, height=500, background_color=&quot;white&quot;).generate(text_combined)<br><br>plt.figure(figsize=(12, 6))<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&quot;Word Cloud of Dante&#39;s Inferno&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep8c1T2Bop_l4hhmOhe49w.png" /></figure><h4>6. NRC Emotion Lexicon</h4><p>Building on this foundation, the NRC Emotion Lexicon was integrated to map individual words to specific emotional categories such as anger, fear, joy, sadness, and trust. This lexicon-based approach allowed for a more nuanced interpretation of the emotional undercurrents present in the text. By associating words with emotions, we could move beyond surface-level frequency counts and delve into the psychological tone embedded within the content.</p><p>Also provided below,</p><p><a href="https://saifmohammad.com/WebDocs/NRC-Emotion-Lexicon.zip">https://saifmohammad.com/WebDocs/NRC-Emotion-Lexicon.zip</a></p><p>is the link to the package used for emotional frequency analysis(to be discussed next). Extract the zip file and obtain the relevant csv which can be stored in the folder of your liking for ease of extraction, as I demonstrate below</p><pre># use import pandas as pd<br><br># Correctly formatted file path<br>filepath = r&quot;C:\Users\user\NRC-Emotion-Lexicon-Wordlevel-v0.92.txt&quot;<br><br># Load NRC Emotion Lexicon<br>nrc = pd.read_csv(filepath, sep=&#39;\t&#39;, names=[&quot;word&quot;, &quot;emotion&quot;, &quot;association&quot;])<br><br># Filter for words with a positive association (1 = associated with emotion)<br>nrc = nrc[nrc[&#39;association&#39;] == 1]<br><br># Create a dictionary: word → list of associated emotions<br>emotion_dict = nrc.groupby(&#39;word&#39;)[&#39;emotion&#39;].apply(list).to_dict()<br><br># Preview<br>print(&quot;Sample emotion associations:&quot;)<br>for word in list(emotion_dict.keys())[:5]:<br>    print(f&quot;{word} → {emotion_dict[word]}&quot;)</pre><h4>7. Emotional Frequency Analysis</h4><p>To quantify this emotional layer, Emotional Frequency Analysis was conducted. This involved tallying the number of times each emotion occurred throughout the text, based on matches from the NRC lexicon.</p><pre># emotional frequency analysis<br><br>import matplotlib.pyplot as plt<br>from collections import Counter<br>import re<br><br># Load Dante text<br>with open(r&quot;C:\Users\user\Desktop\datasets\dante_inferno.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>    inferno = file.read()<br><br># Step 2: Clean and tokenize<br>words = re.findall(r&#39;\b[a-z]{2,}\b&#39;, inferno)<br><br># Step 3: Match words to emotion dictionary<br>emotion_words = []<br>for word in words:<br>    if word in emotion_dict:<br>        emotion_words.extend(emotion_dict[word])<br><br># Step 4: Count emotions<br>emotion_freq = Counter(emotion_words)<br><br># Step 5: Plot emotion frequencies<br>plt.figure(figsize=(12, 6))<br>plt.bar(emotion_freq.keys(), emotion_freq.values(), color=&#39;skyblue&#39;)<br>plt.title(&quot;Emotion Frequency in Dante&#39;s Inferno&quot;)<br>plt.xlabel(&quot;Emotion&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.xticks(rotation=45)<br>plt.tight_layout()<br>plt.grid(axis=&#39;y&#39;, linestyle=&#39;--&#39;, alpha=0.7)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYT60PRWmQiIW5Q6JDII0g.png" /></figure><h4>8. Significance of the Study</h4><p>This project bridges literary analysis, cognitive psychology, and a bit of machine learning. It provides a novel way to quantify the mental demand of reading, which could have applications in:</p><p>· Education: Tailoring text to students’ comprehension levels.</p><p>· Digital Humanities: Enhancing literary analysis with data.</p><p>· UX Writing: optimizing clarity in user-facing content.</p><p>· Mental health: detecting emotionally or cognitively heavy passages in content.</p><p>Full link to the my github for access of project files, please visit</p><p><a href="https://github.com/FaradayOtieno/cognitive_load_inferno">GitHub - FaradayOtieno/cognitive_load_inferno</a></p><h4>Thank You.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e05dfa2f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Donald Trump 47th President Oath video translation to speech using Python]]></title>
            <link>https://medium.com/@iamfaradayotieno/donald-trump-47th-president-oath-video-translation-to-speech-using-python-65ef5a57a4ce?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ef5a57a4ce</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[transcription]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[transcribe-video-to-text]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 07:27:50 GMT</pubDate>
            <atom:updated>2025-02-24T07:28:32.655Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction</strong></li></ol><p>This Python project extracts speech text from a video file using the <strong>MoviePy</strong> library for video processing and <strong>SpeechRecognition</strong> for speech-to-text conversion. The script loads a video, extracts the audio, and processes it to generate a transcript of the spoken content. This can be useful for subtitle generation, content indexing, or accessibility improvements.</p><p>The video to be used is from Donald J. Trump’s inauguration to office as the 47th President of the United States of America on 20th January 2025.</p><p>The link to the youtube video is</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiqyYqY95QZY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiqyYqY95QZY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiqyYqY95QZY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbfbb75e1ea4cdc8acc848ae8c25b9dc/href">https://medium.com/media/cbfbb75e1ea4cdc8acc848ae8c25b9dc/href</a></iframe><p>To extract speech text from video in Python, we require the following modules to install, Here we are using <a href="https://www.geeksforgeeks.org/python-pip/">Python PIP</a> to install different modules.</p><ol><li><strong>Moviepy Module</strong></li></ol><p><strong>MoviePy</strong> is a Python library used for video editing, processing, and manipulation. It allows users to perform tasks like cutting, joining, adding effects, extracting audio, and generating video clips from images. MoviePy supports various formats and integrates well with other multimedia libraries.</p><h4>Key Features</h4><ul><li>Extracting and replacing audio from videos</li><li>Cutting, trimming, and merging video clips</li><li>Applying effects like resizing, speed changes, and text overlays</li><li>Generating videos from images and text animations</li><li>Works with formats like MP4, AVI, GIF, and more</li></ul><p>It is widely used for automating video editing tasks, creating GIFs, and processing media content efficiently.</p><p>2. <strong>SpeechRecognition</strong></p><p><strong>SpeechRecognition</strong> is a Python library used for converting speech into text. It provides an easy-to-use interface for various speech recognition engines, including <strong>Google Web Speech API, CMU Sphinx, IBM Speech to Text, Wit.ai, and more</strong>.</p><h4>Key Features</h4><ul><li>Supports multiple speech recognition engines</li><li>Works with audio files (WAV, AIFF, FLAC) and live microphone input</li><li>Can recognize speech in different languages</li><li>Provides noise reduction and energy threshold adjustments for better accuracy</li></ul><p>This library is useful for applications like voice assistants, transcription services, and automated voice</p><p><strong>2. Install Libraries</strong></p><p>The first step is to import the required modules, i.e., moviepy and speech_recognition.</p><pre>import speech_recognition as sr<br>import moviepy as mp</pre><p><strong>3. Load Video</strong></p><p>The next step is to load the video who’s the speech we want to extract. For this, we already downloaded the video</p><pre># Load the video <br>video = mp.VideoFileClip(r&#39;C:\Users\admin\Desktop\portfolio data\Donald Trump 47th US President Oath of Office.mp4&#39;)</pre><p><strong>4. Extract audio from the video</strong></p><p>Then extract the audio from the video using the audio attribute and then write the ‘.mp4’ file to the ‘.wav’ file using the write_audiofile() function</p><pre># Extract the audio from the video <br>audio_file = video.audio<br>audio_file.write_audiofile(&quot;Donald Trump 47th US President Oath of Office.wav&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzxvUtih_XFkMAMwG0gWRQ.png" /></figure><p><strong>5. Load audio</strong></p><p>Load the newly converted audio file using the AudioFile() function of the speech recognition module.</p><pre># Initialize recognizer <br>r = sr.Recognizer()<br># Load the audio file <br>with sr.AudioFile(&quot;Donald Trump 47th US President Oath of Office.wav&quot;) as source: <br>    data = r.record(source)</pre><p><strong>6. Convert audio to text</strong></p><p>The final step is to convert the data extracted from the audio to text format. This can be done using the recognize_google() function and passing the extracted data as the parameter.</p><p><strong>NOTE : You need internet connectivity for the recognize_google() function to work.</strong></p><pre># Convert speech to text <br>text = r.recognize_google(data)</pre><p><strong>7. Print the text output</strong></p><pre># Print the text <br>print(&quot;\nThe resultant text from video is: \n&quot;) <br>print(text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pxAiYTWxORBBn9Go4gqMg.png" /></figure><p><strong>8. Conclusion</strong></p><p>By combining <strong>MoviePy</strong> for video processing and <strong>SpeechRecognition</strong> for speech-to-text conversion, this project efficiently extracts spoken content from videos. This approach is useful for generating subtitles, transcriptions, and enhancing accessibility. With Python’s powerful libraries, automating speech extraction from videos becomes simple and effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ef5a57a4ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Market Volatility Between Cooperative Bank Kenya and KCB Bank Kenya]]></title>
            <link>https://medium.com/@iamfaradayotieno/stock-market-volatility-between-cooperative-bank-kenya-and-kcb-bank-kenya-827b412ec0fa?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/827b412ec0fa</guid>
            <category><![CDATA[volatility]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[kenya]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 04:14:01 GMT</pubDate>
            <atom:updated>2024-12-18T04:14:01.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Stock market volatility refers to the degree of variation in the price of stocks or the overall market over a specific period. It measures how much and how quickly prices fluctuate, typically expressed using statistical metrics like standard deviation or variance. High volatility indicates large price swings, while low volatility signifies more stable price movements.</p><h4>1. Import the Libraries and Load Dataset</h4><pre>import pandas as pd<br>kcb_data = pd.read_csv(r&#39;C:\Users\admin\Desktop\data\kcb.csv&#39;, index_col = &#39;Date&#39;, parse_dates = True)<br>coop_data = pd.read_csv(r&#39;C:\Users\admin\Desktop\data\coop.csv&#39;, index_col = &#39;Date&#39;, parse_dates = True)</pre><p>Both datasets are obtained from WSJ website and has information from 2 Jan 2019 to 11 Dec 2024. There are five columns. The Open column tells the price at which a stock started trading when the market opened on a particular day. The Close column refers to the price of an individual stock when the stock exchange closed the market for the day. The High column depicts the highest price at which a stock traded during a period. The Low column tells the lowest price of the period. Volume is the total amount of trading activity during a period of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*luHj6EJwzrXAbGXfPZT86w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*PJz9BpOrx_UN5iTwPhEqjg.png" /></figure><pre>import plotly.io as pio<br>import plotly.graph_objects as go<br>pio.templates.default = &quot;plotly_white&quot;</pre><pre># Create a figure to visualize volumes of cooperative and kcb banks<br>fig = go.Figure()<br><br>fig.add_trace(go.Scatter(x=kcb_data.index, y=kcb_data[&#39; Volume&#39;],<br>                         mode=&#39;lines&#39;, name=&#39;KCB Bank&#39;, line=dict(color=&#39;blue&#39;)))<br>fig.add_trace(go.Scatter(x=coop_data.index, y=coop_data[&#39; Volume&#39;],<br>                         mode=&#39;lines&#39;, name=&#39;Cooperative Bank&#39;, line=dict(color=&#39;green&#39;)))<br><br>fig.update_layout(title=&#39;Stock Volume for KCB Bank and Cooperative Bank&#39;,<br>                  xaxis_title=&#39;Date&#39;, yaxis_title=&#39; Volume&#39;,<br>                  legend=dict(x=0.02, y=0.95))<br><br>fig.show()</pre><p>We can therefore, visualize and compare ‘volume’ of both Coop Bank and KCB Bank</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo3jBNo-UFHbhvHEuQDJug.png" /></figure><p>and for the year 2024 to get a clear picture of how both performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hkd3Ymy9_fxfESS9g-kKg.png" /></figure><h4><strong>2. Market Capitalisation</strong></h4><p>Market capitalisation (market cap) is the total value of a company’s outstanding shares of stock. It is calculated by multiplying the company’s current share price by the total number of outstanding shares. Market cap is often used to assess a company’s size and categorize it into small-cap, mid-cap, or large-cap. It provides a quick snapshot of a company’s market value but does not account for factors like debt or assets.</p><p>Here, we’ll multiply the ‘open’ column by the ‘volume’ column for both datasets;</p><pre>import matplotlib.pyplot as plt<br><br>kcb_data[&#39;MarktCap&#39;] = kcb_data[&#39; Open&#39;] * kcb_data[&#39; Volume&#39;]<br>coop_data[&#39;MarktCap&#39;] = coop_data[&#39; Open&#39;] * coop_data[&#39; Volume&#39;]<br>kcb_data[&#39;MarktCap&#39;].plot(label = &#39;KCB Bank&#39;, figsize = (15,7))<br>coop_data[&#39;MarktCap&#39;].plot(label = &#39;Cooperative Bank&#39;)<br>plt.title(&#39;Market Cap&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbO9t4qThHfQE3usLLL29A.png" /></figure><p>Next, we calculate the 50-day moving average for both Coop Bank and KCB Bank to observe the trends;</p><pre>from pandas.plotting import scatter_matrix<br>import numpy as np</pre><p>For KCB Bank;</p><pre># 50-Day Moving Average for KCB Bank<br><br>kcb_data[&#39;MA50&#39;] = kcb_data[&#39; Open&#39;].rolling(50).mean()<br>kcb_data[&#39;MA200&#39;] = kcb_data[&#39; Open&#39;].rolling(200).mean()<br>kcb_data[&#39; Open&#39;].plot(figsize = (15,7))<br>kcb_data[&#39;MA50&#39;].plot()<br>kcb_data[&#39;MA200&#39;].plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIUww2t7WLz4svAz4X0_Dg.png" /></figure><p>For Coop Bank;</p><pre># 50-Day Moving Average for Cooperative Bank<br><br>coop_data[&#39;MA50&#39;] = coop_data[&#39; Open&#39;].rolling(50).mean()<br>coop_data[&#39;MA200&#39;] = coop_data[&#39; Open&#39;].rolling(200).mean()<br>coop_data[&#39; Open&#39;].plot(figsize = (15,7))<br>coop_data[&#39;MA50&#39;].plot()<br>coop_data[&#39;MA200&#39;].plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjCaKZCIorYYtlTwNWSqyA.png" /></figure><h4><strong>3. Scatter Matrix Plot</strong></h4><p>A <strong>scatter matrix plot</strong> is useful for comparing two datasets because it allows you to visualize relationships and patterns between multiple variables simultaneously. Here’s why it’s beneficial:</p><ol><li><strong>Pairwise Relationships</strong>: It displays scatter plots for every pair of variables in the datasets, helping identify linear or non-linear relationships, correlations, or clusters.</li></ol><p><strong>2. Data Distribution</strong>: The diagonal typically shows histograms or kernel density plots, giving insight into the distribution of individual variables in each dataset.</p><p><strong>3. Comparison Across Datasets</strong>: By overlaying or juxtaposing scatter matrices for two datasets, you can spot differences in distributions, relationships, and variances across the datasets.</p><p><strong>4. Outlier Detection</strong>: It helps identify anomalies or outliers in the data that might skew analysis.</p><p>This makes scatter matrix plots a powerful exploratory tool for assessing similarities and differences between two datasets before conducting more formal statistical analyses.</p><pre># Scattered Plot Matrix<br><br>data = pd.concat([kcb_data[&#39; Open&#39;],coop_data[&#39; Open&#39;]],axis = 1)<br>data.columns = [&#39;KCB_Open&#39;,&#39;COOP_Open&#39;]<br>scatter_matrix(data, figsize = (8,8), hist_kwds= {&#39;bins&#39;:250})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*EEQ725sSj8Wf60xMJYRiGA.png" /></figure><p>We see clearly that KCB Bank stocks are loosely showing a linear correlation with Cooperative Bank.</p><h4><strong>4. Percentage Increase in Stock Value</strong></h4><p>A percentage increase in stock value is the change in stock comparing that to the previous day. The bigger the value either positive or negative the volatile the stock is.</p><pre>#Volatility<br>kcb_data[&#39;returns&#39;] = (kcb_data[&#39; Close&#39;]/kcb_data[&#39; Close&#39;].shift(1)) -1<br>coop_data[&#39;returns&#39;] = (coop_data[&#39; Close&#39;]/coop_data[&#39; Close&#39;].shift(1))-1<br>kcb_data[&#39;returns&#39;].hist(bins = 100, label = &#39;KCB Bank&#39;, alpha = 0.5, figsize = (15,7))<br>coop_data[&#39;returns&#39;].hist(bins = 100, label = &#39;Cooperative Bank Kenya&#39;, alpha = 0.5)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0w5R9OSLvbb4pbXGBGEdVw.png" /></figure><p>It is clear from the graph that the percentage increase in stock price histogram for Cooperative Bank is the widest which indicates the stock of Cooperative Bank is the most volatile among the two companies compared.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=827b412ec0fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitcoin Price Prediction(2024) using Machine Learning in Python]]></title>
            <link>https://medium.com/@iamfaradayotieno/bitcoin-price-prediction-2024-using-machine-learning-in-python-ec17f495923f?source=rss-6aa1f9fc9755------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec17f495923f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Michael Faraday Otieno]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 11:09:09 GMT</pubDate>
            <atom:updated>2024-12-10T11:09:09.680Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Machine Learning (ML)</strong> is a field of artificial intelligence where computers learn patterns from data and make predictions or decisions without explicit programming.</p><p>In <strong>Bitcoin price prediction</strong>, ML models analyze historical data, market trends, and external factors like news sentiment to identify patterns and make forecasts. Techniques like time-series analysis, regression, and neural networks are commonly used to handle Bitcoin’s volatility and dynamic behavior.</p><h4><strong>1. Import Libraries</strong></h4><p>Numpy — Provides support for multi-dimensional arrays and matrices, along with mathematical functions for fast operations on these arrays.</p><p>Matplotlib — Ideal for line charts, bar graphs, scatter plots, and more.</p><p>Pandas — Provides data structures like DataFrame and Series for handling tabular and time-series data.</p><p>Scikit-Learn — Includes tools for classification, regression, clustering, dimensionality reduction, and preprocessing.</p><p>Seaborn — Provides high-level functions for creating visually appealing and informative graphics.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.svm import SVC<br>from xgboost import XGBClassifier<br>from sklearn import metrics<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p>The dataset we will use here to perform the analysis and build a predictive model is Bitcoin Price data. We will use OHLC(‘Open’, ‘High’, ‘Low’, ‘Close’) data from 18th July 2010 to 23th August 2022 which is for 12 years for the Bitcoin price.</p><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*4bVldgaeAYB2iO4Qk1KJrQ.png" /></figure><p>we have are 4420 rows of data available and for each row, we have 7 different features or columns.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*keySp0dYQYEQy58NyIsS_Q.png" /></figure><p>2. <strong>Exploratory Data Analysis</strong></p><p><strong>Exploratory Data Analysis (EDA)</strong> is the process of analyzing and visualizing data to uncover patterns, trends, relationships, and anomalies before applying machine learning models.</p><pre>plt.figure(figsize=(15, 5))<br>plt.plot(df[&#39;Close&#39;])<br>plt.title(&#39;Bitcoin Close price.&#39;, fontsize=15)<br>plt.ylabel(&#39;Price in dollars.&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpYqVqNYyWzSSPR3ovTCrA.png" /></figure><p>The prices of the Bitcoin stocks are showing an upward trend as depicted by the plot of the closing price of the stocks.</p><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*V2kdLdCMjZrnZ1obFlg28g.png" /></figure><p>No null values in our dataset, so we proceed.</p><pre>features = [&#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;]<br><br>plt.subplots(figsize=(20,10))<br>for i, col in enumerate(features):<br>  plt.subplot(2,2,i+1)<br>  sb.distplot(df[col])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uHIEtspq8bytotL3WBctg.png" /></figure><pre>plt.subplots(figsize=(20,10))<br>for i, col in enumerate(features):<br>  plt.subplot(2,2,i+1)<br>  sb.boxplot(df[col])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcUp9PgIiMeaWzWtxGtiKg.png" /></figure><p>From the boxplots, prices of the stock have varied hugely in a very short period of time.</p><p>3.<strong> Feature Engineering</strong></p><p><strong>Feature engineering</strong> is crucial in machine learning as it involves transforming raw data into meaningful inputs that improve model performance. Here’s why it’s important:</p><ol><li><strong>Improves Model Accuracy</strong>: Good features capture the underlying patterns in data, enabling models to make more accurate predictions.</li><li><strong>Simplifies Models</strong>: Well-designed features can reduce the complexity of a model by eliminating noise and emphasizing relevant patterns.</li><li><strong>Enhances Interpretability</strong>: Intuitive features make models easier to understand and explain, which is critical in applications where transparency is key.</li><li><strong>Compensates for Data Limitations</strong>: By creating informative features, you can extract maximum value from limited or sparse datasets.</li><li><strong>Domain Insights</strong>: Feature engineering incorporates domain knowledge, which often uncovers critical relationships not easily detected by algorithms alone.</li></ol><pre>splitted = df[&#39;Date&#39;].str.split(&#39;-&#39;, expand=True)<br><br>df[&#39;year&#39;] = splitted[0].astype(&#39;int&#39;)<br>df[&#39;month&#39;] = splitted[1].astype(&#39;int&#39;)<br>df[&#39;day&#39;] = splitted[2].astype(&#39;int&#39;)<br><br># Convert the &#39;Date&#39; column to datetime objects<br>df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;]) <br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*faF5SFcBuPft1SarticX6Q.png" /></figure><p>We now have split our date to year, month and day. All these three have been derived from the ‘Date’ column which was initially provided in the data.</p><pre>df[&#39;is_quarter_end&#39;] = np.where(df[&#39;month&#39;]%3==0,1,0)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*JsU6-QaGp-s80IzLGGxFQw.png" /></figure><pre>df[&#39;open-close&#39;]  = df[&#39;Open&#39;] - df[&#39;Close&#39;]<br>df[&#39;low-high&#39;]  = df[&#39;Low&#39;] - df[&#39;High&#39;]<br>df[&#39;target&#39;] = np.where(df[&#39;Close&#39;].shift(-1) &gt; df[&#39;Close&#39;], 1, 0)</pre><p>We have introduced additional columns to enhance the training process of our model, including the target feature, which indicates whether a “buy” signal is present. The model will be trained specifically to predict this target. Before moving forward, let’s evaluate if the target is balanced by visualizing it using a pie chart.</p><pre># plot pie chart<br><br>plt.pie(df[&#39;target&#39;].value_counts().values, <br>        labels=[0, 1], autopct=&#39;%1.1f%%&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*XCl34Kym_GXkEQyCciBrLA.png" /></figure><p>Let’s drop ‘currency’ and ‘date’ for its not necessary going forward.</p><pre>df=df.drop(labels=&#39;Currency&#39;, axis=1)<br>df=df.drop(labels=&#39;Date&#39;, axis = 1)</pre><p>As our concern is with the highly correlated features only so, we will visualize our heatmap as per that criteria only.</p><pre>plt.figure(figsize=(10, 10))<br>sb.heatmap(df.corr() &gt; 0.9, annot=True, cbar=False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*cCMH9RraJ4_coc7ailZnTQ.png" /></figure><p>From the above heatmap, we can say that there is a high correlation between ‘Open’, ‘High’, ‘Low’, ‘Close’ which is pretty obvious, and the added features are not highly correlated with each other feature hence we are good to go and build our model.</p><pre>features = df[[&#39;open-close&#39;, &#39;low-high&#39;, &#39;is_quarter_end&#39;]]<br>target = df[&#39;target&#39;]<br><br>scaler = StandardScaler()<br>features = scaler.fit_transform(features)<br><br>X_train, X_valid, Y_train, Y_valid = train_test_split(<br>    features, target, test_size=0.1, random_state=2022)<br>print(X_train.shape, X_valid.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*i9fN0sQq3dDwME2tBn_DjQ.png" /></figure><p>After selecting the features to train the model on we should normalize the data because normalized data leads to stable and fast training of the model.</p><p><strong>4. Model Development and Evaluation</strong></p><p>Now lets’s train some state-of-the-art machine learning models(Logistic Regression, Support Vector Machine, XGBClassifier), and then based on their performance on the training and validation data we will choose the best ML model.</p><pre>models = [LogisticRegression(), SVC(kernel=&#39;poly&#39;, probability=True), XGBClassifier()]<br><br>for i in range(3):<br>  models[i].fit(X_train, Y_train)<br><br>  print(f&#39;{models[i]} : &#39;)<br>  print(&#39;Training Accuracy : &#39;, metrics.roc_auc_score(Y_train, models[i].predict_proba(X_train)[:,1]))<br>  print(&#39;Validation Accuracy : &#39;, metrics.roc_auc_score(Y_valid, models[i].predict_proba(X_valid)[:,1]))<br>  print()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*n_ZzICHJPksVBaEkADGAbQ.png" /></figure><p>Among the three models, we have trained XGBClassifier has the highest performance but it is pruned to overfitting as the difference between the training and the validation accuracy is too high.</p><p>Now, Let’s plot the confusion matrix;</p><pre>from sklearn.metrics import ConfusionMatrixDisplay<br><br>ConfusionMatrixDisplay.from_estimator(models[0], X_valid, Y_valid)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*JE5s6QeZhFuRjyqZ0m_dlg.png" /></figure><p>We can see that many of the actual positive cases were correctly predicted as positive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec17f495923f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>