<?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 Ronphreylucky on Medium]]></title>
        <description><![CDATA[Stories by Ronphreylucky on Medium]]></description>
        <link>https://medium.com/@ronphreylucky?source=rss-926787b5dd8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*O-pW0NFQeWXxJYao</url>
            <title>Stories by Ronphreylucky on Medium</title>
            <link>https://medium.com/@ronphreylucky?source=rss-926787b5dd8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:36:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ronphreylucky/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[Analysing the UK’s Milk and Cream Trade: What the Data Reveals About Imports, Exports and Trading…]]></title>
            <link>https://medium.com/@ronphreylucky/analysing-the-uks-milk-and-cream-trade-what-the-data-reveals-about-imports-exports-and-trading-2d3223aed911?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3223aed911</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 16:20:07 GMT</pubDate>
            <atom:updated>2026-11-01T16:20:07.062Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analysing the UK’s Milk and Cream Trade: What the Data Reveals About Imports, Exports and Trading Partners.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*OJpXB6bZDdBUci5OjhfFVw.png" /></figure><p>International trade is more than the movement of goods between countries. It reveals economic relationships, market dependencies, trading patterns and the extent to which countries rely on one another.</p><p>I wanted to explore these relationships using a practical data analysis project focused on the United Kingdom’s international trade in milk and cream.</p><p>Rather than simply calculating total imports and exports, I wanted to investigate some deeper questions:</p><ol><li>Does the UK export more milk and cream than it imports?</li><li>Which countries are its biggest trading partners?</li><li>Which countries consistently purchase milk and cream from the UK?</li><li>Which countries trade in both directions with the UK?</li><li>Are there noticeable patterns in trade values across months and commodity types?</li></ol><p>The project provided an opportunity to apply Python, Pandas, SQL concepts, statistical analysis and data visualisation to a real world dataset.</p><p>Using data from the United Nations Comtrade database, I investigated how much the UK imported and exported, which countries were its biggest trading partners, how consistent its export relationships were, and whether countries that bought from the UK also supplied it.</p><p>The extended 2014 analysis revealed an interesting picture: the UK exported approximately US$898.65 million worth of the selected products and imported approximately US$563.88 million, resulting in a trade surplus of about US$334.77 million.</p><p>Ireland was particularly significant, ranking as the UK’s largest trading partner in both directions.</p><p>Beyond these headline figures, I wanted to understand the patterns behind them.</p><h3>Understanding the dataset</h3><p>The data came from the <a href="https://comtradeplus.un.org/?utm_source=chatgpt.com">United Nations Comtrade database</a>, a source of international merchandise trade statistics.</p><p>The analysis focused on two Harmonized System commodity codes:</p><ul><li>0401: Milk and cream, neither concentrated nor sweetened.</li><li>0402: Milk and cream, concentrated or sweetened.</li></ul><p>The dataset contained monthly trade records for the United Kingdom, covering imports and exports with its trading partners.</p><p>The notebook used two datasets for different stages of the investigation:</p><ul><li>January to May 2015: the initial exercise using the cohort database.</li><li>January to December 2014: the extended analysis using a separately downloaded Comtrade CSV file.</li></ul><p>Some of the important variables included:</p><ul><li>period: The reporting month, represented as YYYYMM.</li><li>partnerDesc: The trading partner country.</li><li>flowDesc: Whether the record represents an import or export.</li><li>cmdCode: The commodity classification.</li><li>primaryValue: The reported trade value in US dollars.</li></ul><p>Other fields in the original Comtrade download included reporter information, quantities, weights, and other trade value measures. However, the analysis concentrated on the fields directly relevant to the research questions.</p><p>An important distinction is that the dataset contains reported trade values, not necessarily the physical quantity of milk and cream traded. A higher trade value does not automatically mean a higher volume.</p><h3>Data preparation and cleaning</h3><p>Before analysing the data, I needed to understand its structure and identify fields that could affect the accuracy of the results.</p><p>I loaded the CSV file using Pandas:</p><pre>df = pd.read_csv(<br>    RAW,<br>    dtype={&#39;cmdCode&#39;: str},<br>    encoding=&#39;utf-8-sig&#39;,<br>    index_col=False<br>)</pre><p>One small but important decision was specifying the commodity code as a string.</p><p>Why?</p><p>Because 0401 and 0402 are classification codes, not numerical values. Reading them as integers would remove the leading zero and change how the codes are represented.</p><p>Next, I selected only the columns needed for the analysis and removed the aggregate records labelled World.</p><pre>cols = [<br>    &#39;period&#39;,<br>    &#39;partnerDesc&#39;,<br>    &#39;flowDesc&#39;,<br>    &#39;cmdCode&#39;,<br>    &#39;primaryValue&#39;<br>]<br><br>df_noworld = df.loc[<br>    df[&#39;partnerDesc&#39;] != &#39;World&#39;,<br>    cols<br>].copy()</pre><p>This was one of the most important cleaning decisions.</p><p>The World records represent aggregate trade totals. Keeping them alongside individual country records would double count trade when calculating totals across partners.</p><p>After removing these records, the 2014 dataset changed from 1,477 rows to 1,429 rows, leaving five relevant columns.</p><p>I also renamed the columns to make the DataFrame easier to understand:</p><pre>df_noworld = df_noworld.rename(columns={<br>    &#39;period&#39;: &#39;Period&#39;,<br>    &#39;partnerDesc&#39;: &#39;Partner&#39;,<br>    &#39;flowDesc&#39;: &#39;Trade Flow&#39;,<br>    &#39;cmdCode&#39;: &#39;Commodity Code&#39;,<br>    &#39;primaryValue&#39;: &#39;Trade Value (US$)&#39;<br>})</pre><p>The result was a smaller, more focused dataset that was easier to work with.</p><h3>Exploratory analysis: Understanding the trade structure</h3><p>With the data prepared, I began by investigating the overall distribution of imports and exports.</p><p>The first technique I applied was grouping and aggregation using Pandas.</p><h3>Comparing total imports and exports</h3><p>The idea was to group the records according to their trade flow and calculate the total value within each group.</p><pre>grouped = df_noworld.groupby(&#39;Trade Flow&#39;)<br><br>grouped[&#39;Trade Value (US$)&#39;].sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpvqFNGHoNvuisymp4vxOg.png" /></figure><p>The UK recorded a substantial trade surplus in the selected milk and cream categories.</p><p>Exports were approximately 1.6 times the value of imports.</p><p>This answered the first research question, but it raised another: which countries contributed most to this surplus?</p><h3>Identifying the major trading partners</h3><p>To investigate this, I separated imports from exports, grouped the records by partner country and sorted the aggregated values.</p><p>For imports:</p><pre>imports = df_noworld[<br>    df_noworld[&#39;Trade Flow&#39;] == &#39;Import&#39;<br>]<br><br>top_imports = (<br>    imports.groupby(&#39;Partner&#39;)[&#39;Trade Value (US$)&#39;]<br>    .sum()<br>    .sort_values(ascending=False)<br>)<br><br>top_imports.head(10)</pre><p>I applied the same approach to exports.</p><p>The results revealed a strong relationship with Ireland.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0F1C1RYFFZEu8pyqnkD-w.png" /></figure><p>Ireland was the UK’s largest trading partner in both directions.</p><p>It accounted for approximately 46.9% of the UK’s total exports and 30.9% of its imports.</p><p>Another interesting finding was the difference in the number of trading partners. The UK exported to 120 countries but imported from only 25 countries in the 2014 dataset.</p><p>This suggested that the UK’s export market was geographically broader, while its imports were concentrated among fewer suppliers.</p><p>The top five import sources accounted for approximately 86% of total imports.</p><p>This was an important discovery because total trade figures alone would not have revealed the extent of this concentration.</p><h3>Investigating the effect of commodity type</h3><p>I did not want to treat all milk and cream products as one category.</p><p>Unprocessed milk and cream are different from concentrated or sweetened products, and the distinction could influence the countries involved in trade.</p><p>I therefore developed a reusable function to identify the largest trading partners within different groups.</p><pre>def top_partner(keys, n=1):<br><br>    totals = (<br>        df_noworld<br>        .groupby(keys + [&#39;Partner&#39;])[<br>            &#39;Trade Value (US$)&#39;<br>        ]<br>        .sum()<br>        .reset_index()<br>    )<br><br>    totals[&#39;Share (%)&#39;] = (<br>        100 * totals[&#39;Trade Value (US$)&#39;] /<br>        totals.groupby(keys)[<br>            &#39;Trade Value (US$)&#39;<br>        ].transform(&#39;sum&#39;)<br>    ).round(1)<br><br>    return (<br>        totals<br>        .sort_values(<br>            keys + [&#39;Trade Value (US$)&#39;],<br>            ascending=[True] * len(keys) + [False]<br>        )<br>        .groupby(keys)<br>        .head(n)<br>        .reset_index(drop=True)<br>    )</pre><p>This function allowed me to change the grouping dimensions without rewriting the entire analysis.</p><p>For example, I could identify the leading partner by commodity code, trade flow, or a combination of both.</p><p>The findings were particularly interesting:</p><ul><li>Ireland accounted for 75.2% of UK exports of unprocessed milk and cream.</li><li>Ireland also accounted for 50.1% of UK imports in that category.</li><li>For processed milk and cream exports, Ireland and Algeria were almost tied, with shares of 20.4% and 20.2%, respectively.</li><li>France was the largest import source for processed milk and cream, accounting for 25.1%.</li></ul><p>This showed that the leading trading partner depended on the commodity being analysed.</p><p>It also demonstrated why grouping data by multiple variables can produce more meaningful insights than looking at country totals alone.</p><h3>Analysing monthly trade patterns</h3><p>Annual totals provide a useful overview, but they can hide important variations throughout the year.</p><p>I therefore investigated the monthly movement of imports and exports.</p><p>Using groupby() on the reporting period, I calculated the total trade value for each month and plotted both trade flows on the same line chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7HK3CEWtQvRDahXveovnA.png" /></figure><p><em>Figure 1: Monthly UK milk and cream imports and exports in 2014. The notebook’s actual chart should be used here.</em></p><p>The results showed that exports were strongest during spring and early summer.</p><p>June recorded the highest export value at approximately US$99.32 million, followed by May at US$96.20 million and April at US$95.20 million.</p><p>Imports followed a different pattern.</p><p>Their highest monthly value occurred in November, at approximately US$57.08 million.</p><p>The monthly trade balance was positive in eleven of the twelve months. November was the exception, when imports exceeded exports by approximately US$7.79 million.</p><p>This was an interesting result because it showed that although the UK recorded an annual trade surplus, the balance was not positive in every month.</p><p>I also examined commodity 0402 separately.</p><p>For exports, June recorded the highest monthly mean, maximum and total trade value across partner records.</p><p>For imports, these measures pointed to different months. This highlighted an important analytical point: the average value of individual partner records and the total monthly trade value answer different questions.</p><p>A higher monthly average does not necessarily mean a higher overall trade value.</p><h3>Visualising the distribution of trade values</h3><p>After exploring totals and monthly trends, I wanted to understand how trade values were distributed across individual partner and month records.</p><p>The values varied considerably. Some records represented relatively small transactions, while others were worth millions of dollars.</p><p>A standard histogram would have been difficult to interpret because of this wide range.</p><p>I therefore applied a base 10 logarithmic transformation:</p><pre>pm[&#39;log10 trade value&#39;] = np.log10(<br>    pm[&#39;Trade Value (US$)&#39;].clip(lower=1)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*RsKMQ5hy9T3mHjtg4-2ayg.png" /></figure><p><em>Figure 2: Distribution of monthly trade values across partner records.</em></p><p>I followed this with a Kernel Density Estimate plot to compare the distributions of imports and exports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*ZdS6lXJPz718ex7oGnRt_g.png" /></figure><p><em>Figure 3: Distribution of import and export record values.</em></p><p>One notable result was that the median import record was approximately US$423,000, compared with approximately US$51,000 for exports.</p><p>This may initially appear contradictory because total exports were higher than total imports.</p><p>However, there is no contradiction.</p><p>The median describes a typical individual record, while the total describes the sum of all records. The UK had many more export partner records, including numerous smaller transactions.</p><p>I also used box plots and violin plots to compare the distributions across the two commodity categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_45rJcDV37eQ_AHX9o8vA.png" /></figure><p><em>Figure 4: Box plot and violin plot comparing trade values by commodity type and trade flow.</em></p><p>These charts showed that import records were generally larger than export records for both categories.</p><p>Unprocessed milk and cream exports had particularly small individual trade values, with a median of approximately US$12,000.</p><p>The box plot made the medians and spread easier to compare, while the violin plot showed the shape of the distributions.</p><h3>Investigating the relationship between imports and exports</h3><p>One question I found particularly interesting was whether countries that purchased more milk and cream from the UK also tended to supply more to the UK.</p><p>To investigate this, I used a pivot table to place the import and export values for each country side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*57utFD31ms5VASzaS12oMQ.png" /></figure><p><em>Figure 5: UK exports versus imports across countries with two way trade.</em></p><p>The analysis identified 25 countries with recorded imports from and exports to the UK.</p><p>The correlation coefficient was approximately 0.53.</p><p>This indicates a moderate positive relationship. In other words, countries that bought more from the UK tended, to some extent, to also sell more to it.</p><p>However, the points were not tightly concentrated around the regression line. The relationship was not strong enough to suggest that the two trade flows moved together consistently.</p><p>It is also important to remember that correlation does not establish causation.</p><h3>Examining export activity with a heatmap</h3><p>For the final visualisation, I wanted to compare the UK’s export activity across its major trading partners throughout the year.</p><p>I selected the ten largest export destinations and used a pivot table to organise their monthly trade values.</p><pre>exp_only = pm[<br>    pm[&#39;Trade Flow&#39;] == &#39;Exports&#39;<br>]<br><br>top10 = (<br>    exp_only.groupby(&#39;Partner&#39;)[&#39;Trade Value (US$)&#39;]<br>    .sum()<br>    .nlargest(10).index<br>)<br><br>heat = (<br>    exp_only[exp_only[&#39;Partner&#39;].isin(top10)]<br>    .pivot_table(<br>        index=&#39;Partner&#39;,<br>        columns=&#39;Period&#39;,<br>        values=&#39;Trade Value (US$)&#39;,<br>        aggfunc=&#39;sum&#39;<br>    )<br>    .loc[top10] / 1e6<br>)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T9k1ympz8ZNIEsJ43FshA.png" /></figure><p><em>Figure 6: Monthly UK milk and cream exports to its ten largest trading partners.</em></p><p>The heatmap made it easier to identify differences in monthly purchasing patterns.</p><p>Ireland maintained relatively high purchases of approximately US$38 million to US$42 million per month until July, after which its purchases declined during the autumn.</p><p>Algeria showed a different pattern, with a noticeable increase in purchases between April and June, reaching approximately US$22 million in June.</p><p>This was one of the most useful visualisations because it allowed me to compare several countries and twelve months in a single view.</p><h3>Taking the analysis further with SQL</h3><p>The notebook did not end with Python.</p><p>I also used SQL Server to solve five additional analytical tasks using the cohort’s week09 database.</p><p>The objective was to reproduce some of the grouping, aggregation and reshaping operations in SQL.</p><p>The exercises covered:</p><ul><li>Grouping by trade flow and commodity type using GROUP BY.</li><li>Creating a monthly imports versus exports table using conditional aggregation.</li><li>Calculating quarterly and annual subtotals using GROUPING SETS.</li><li>Ranking the top three trading partners using ROW_NUMBER() and window functions.</li><li>Preparing a tidy dataset for a stacked bar chart.</li></ul><p>One example was identifying the top three trading partners for each trade flow.</p><pre>WITH t AS (<br>    SELECT<br>        [Trade Flow] AS flow,<br>        Partner,<br>        SUM([Trade Value (US$)]) AS total<br>    FROM week09.countrymilk<br>    GROUP BY [Trade Flow], Partner<br>),<br>r AS (<br>    SELECT<br>        flow,<br>        Partner,<br>        total,<br>        ROW_NUMBER() OVER (<br>            PARTITION BY flow<br>            ORDER BY total DESC<br>        ) AS rnk<br>    FROM t<br>)<br>SELECT *<br>FROM r<br>WHERE rnk &lt;= 3;</pre><p>This exercise helped me understand how SQL window functions can solve ranking problems without having to create separate queries for imports and exports.</p><p>Key findings and interpretation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*p0SUaGshNX2OlAEMIbXhRA.png" /></figure><p>A few conclusions stood out.</p><p>First, the UK recorded a substantial trade surplus in the selected milk and cream categories during 2014.</p><p>Second, Ireland played a major role in both directions of trade. Its importance was particularly pronounced in unprocessed milk and cream exports.</p><p>Third, the UK’s export market was considerably broader than its import network, although a large proportion of exports was concentrated among a relatively small group of countries.</p><p>Finally, monthly analysis revealed that imports and exports did not follow identical patterns throughout the year.</p><p>These findings describe the selected commodities and reporting period. They should not be interpreted as a complete picture of the UK’s entire dairy industry or as evidence of the causes behind the observed trade relationships.</p><h3>Limitations and opportunities for further analysis</h3><p>There are some limitations worth acknowledging.</p><p>The extended analysis covers only 2014. One year of monthly observations is not enough to establish a recurring seasonal pattern or identify long term changes in trade.</p><p>The analysis also focuses on trade values rather than physical quantities. Changes in value could reflect changes in prices, quantities, product mix or currency effects.</p><p>Additionally, some country level records were very small. These may reflect genuine trade activity, reporting practices or data quality issues, and would require further investigation.</p><p>With more time and additional data, I would extend the analysis across multiple years, compare trade values with quantities and unit prices, and investigate whether the observed relationships remain consistent over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3223aed911" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Data Meets Curiosity: Two Tasks That Changed How I Think About Data Analysis]]></title>
            <link>https://medium.com/@ronphreylucky/when-data-meets-curiosity-two-tasks-that-changed-how-i-think-about-data-analysis-f974ceef6c18?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f974ceef6c18</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 15:50:05 GMT</pubDate>
            <atom:updated>2026-10-25T15:50:05.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*o7QnrSw0H6TjM3ohvMCG_w.png" /></figure><p>From finding the best summer holiday week with Python to investigating the relationship between GDP and life expectancy, here is what I learned by turning raw data into meaningful insights.</p><h3>Introduction</h3><p>Sometimes, data analysis begins with a simple question. What if we could use historical weather records to find the best week for a holiday? Or could we use economic data to understand why people in some countries live longer than others?</p><p>These were the questions behind two projects I explored using Python, Pandas, Matplotlib, and SQL. Although the projects addressed different problems, both taught me that the real work begins before we interpret the results.</p><h3>Finding the Best Summer Holiday Week</h3><p>Imagine planning a holiday without relying entirely on guesswork. Instead of choosing dates based on intuition, you examine historical weather records and let the data guide your decision.</p><p>That was the idea behind my first project.</p><p>I worked with daily weather observations, including maximum temperature, wind speed, humidity, dew point, and atmospheric pressure. Before analysing anything, I had to clean the data. Some column names contained unwanted HTML tags, and certain values needed to be converted into appropriate numerical or date formats.</p><p>With Pandas, I prepared the records for analysis and selected the summer months of June, July, and August.</p><p>The interesting part was defining what made a week suitable for a holiday. I treated warmer temperatures and higher atmospheric pressure as desirable, while lower wind speed, humidity, and dew point improved a week’s score.</p><p>I then calculated seven day rolling averages and standardised the measurements using z scores so that variables measured in different units could contribute to a combined score.</p><p>One important detail was using shift(-6) to align each seven day average with the starting date of its window. This allowed me to evaluate the weather on a particular day together with the following six days.</p><p>The highest scoring week was selected first, followed by the highest scoring week that did not overlap it.</p><p>The analysis identified 2 June to 8 June 2023 and 11 June to 17 June 2023 as the two best candidate weeks under my scoring system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*LpemRUXlGsBxVqc5E4FAfQ.png" /></figure><p>The graph makes the results easier to understand. The red line represents maximum temperature, while the blue line represents average dew point. The shaded regions identify the two selected periods.</p><p>What I found interesting was how the project transformed a subjective question into a repeatable analytical process. Instead of simply choosing a week that looked promising, I could compare candidate periods using explicit criteria.</p><p>However, the result depends on the scoring rules. It does not guarantee perfect weather, and atmospheric pressure is only an indirect indicator of settled conditions. The analysis demonstrates how data can support decisions, not eliminate uncertainty.</p><h3>Does a Country’s Wealth Determine Life Expectancy?</h3><p>The second project moved from weather patterns to a broader question about economic development and human wellbeing.</p><p>GDP measures the value of goods and services produced within an economy. Life expectancy at birth estimates how long a newborn would live on average if the mortality conditions represented by the relevant period remained applicable throughout life.</p><p>I wanted to investigate whether countries with higher GDP also tended to have higher life expectancy.</p><p>The data came from World Bank datasets stored in SQL Server. I retrieved the relevant records, cleaned the data, selected the necessary columns, and combined the GDP and life expectancy tables using Pandas.</p><pre>gdpVsLife = pd.merge(<br>    gdpClean,<br>    lifeClean,<br>    on=&quot;country&quot;,<br>    how=&quot;inner&quot;<br>)</pre><p>The inner join retained countries with matching records in both datasets.</p><p>I then used Spearman’s rank correlation to examine the relationship between GDP and life expectancy.</p><pre>from scipy.stats import spearmanr<br><br>correlation, pValue = spearmanr(<br>    gdpColumn,<br>    lifeColumn<br>)<br><br>print(&quot;The correlation is&quot;, correlation)</pre><p>The result was approximately 0.501, with a p value below 0.05.</p><p>This indicates a moderately positive monotonic relationship in the analysed data, and the notebook reports it as statistically significant.</p><p>In simpler terms, countries with higher GDP generally tended to have higher life expectancy, but the relationship was far from perfect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*qQoL402qlrSWTQOdSVqNcw.png" /></figure><p>Each dot represents a country. The horizontal position indicates GDP, while the vertical position indicates life expectancy.</p><p>The logarithmic scale makes it easier to compare countries with very different economic sizes. The graph also reveals considerable variation: countries with similar GDP values can have noticeably different life expectancies.</p><p>This is where interpretation becomes important. GDP alone cannot explain population health. Healthcare access, education, sanitation, inequality, conflict, and other social conditions may also influence how long people live.</p><p>Furthermore, a statistically significant correlation does not prove that greater GDP directly causes longer life expectancy.</p><p>The project therefore taught me to look beyond the number and investigate what might explain the pattern.</p><p>These projects reinforced three important lessons.</p><p>First, data cleaning is fundamental. Inconsistent values and missing observations can affect the reliability of an analysis.</p><p>Second, visualisation helps us see what summary statistics cannot fully explain. A graph can reveal patterns, variation, and exceptions that a single number may conceal.</p><p>Third, every analytical result depends on decisions. The variables selected, the transformations applied, and the statistical methods chosen all influence the conclusions.</p><p>Ultimately, I learned that Python and SQL are not simply tools for writing code. They help us turn questions into structured investigations and raw information into evidence we can interpret.</p><p>Good data analysis is not just about producing an answer. It is about understanding how that answer was reached, what it reveals, and where its limitations lie.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f974ceef6c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Dataset Has a Story, but Can You Trust the Ending?]]></title>
            <link>https://medium.com/@ronphreylucky/every-dataset-has-a-story-but-can-you-trust-the-ending-fc4ca85bb4e4?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4ca85bb4e4</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 10:14:55 GMT</pubDate>
            <atom:updated>2026-10-18T10:14:55.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Rlv4hLn4ZZwDcQ3l5HILAg.png" /></figure><h3>The moment data started making sense</h3><p>When I first started learning data analysis, I thought the process was straightforward. You load a dataset, write a few lines of Python or SQL, generate some output, and interpret what you see.</p><p>It sounds simple enough.</p><p>But as I spent more time working with NumPy, Pandas, and SQL, I began to understand something important. Writing a query that executes successfully is not the same as solving a problem. Getting a number from a dataset does not automatically make that number meaningful. And sometimes, the most important part of an analysis is not the result you obtain, but the question you ask after seeing it.</p><p>This week’s work gave me an opportunity to explore these ideas through practical exercises, from checking numerical values in Python to analysing weather records, calculating tuberculosis death rates, examining customer churn, and investigating suspicious patterns in loan approval data.</p><p>Each task introduced a different technical concept, but together, they taught me something much more valuable: data analysis is a process of turning raw information into evidence that people can use to make decisions.</p><p>Let me walk you through how that journey unfolded.</p><h3>Chapter One: Learning to Look Closer with NumPy</h3><p>Before we can draw conclusions from data, we need to understand what we are working with.</p><p>Imagine receiving a spreadsheet containing thousands of temperature readings, financial transactions, or sensor measurements from industrial equipment. Before analysing the data, you need to know whether the values are valid, whether two measurements are sufficiently similar, and how much memory your data occupies.</p><p>This is where NumPy becomes useful.</p><p>NumPy is a Python library designed for numerical computing. It provides arrays and mathematical operations that allow us to work efficiently with collections of values.</p><p>My first set of exercises focused on examining arrays and understanding their behaviour.</p><h3>The problem with missing and unusual values</h3><p>Imagine that a temperature monitoring system records the following readings:</p><pre>import numpy as np<br><br>a = np.array([1, 0, np.nan, np.inf])<br><br>print(np.isnan(a))</pre><pre>[False False  True False]</pre><p>At first glance, the array looks ordinary. It contains a one, a zero, a missing numerical value, and infinity.</p><p>However, each value means something different.</p><p>The number 1 is a valid numerical value. The number 0 is also valid, even if it represents a temperature or measurement that requires further investigation. np.nan represents a value that is not a number, often used to represent missing or undefined numerical data. Meanwhile, np.inf represents positive infinity.</p><p>The function np.isnan() checks each element to determine whether it is NaN. It returns a Boolean array containing True for NaN values and False otherwise.</p><p>This distinction matters because missing data should not be treated as zero automatically. If a machine fails to record its operating temperature, replacing the missing reading with zero could create the false impression that the machine operated at zero degrees.</p><p>The code is simple, but the principle is fundamental: before analysing data, understand what the values actually represent.</p><h3>When numbers are not quite what they seem</h3><p>Another exercise introduced complex numbers, real numbers, and scalar values.</p><pre>b = np.array([1 + 1j, 1 + 0j, 4.5, 3, 2, 2j])print(&quot;Is complex:&quot;, np.iscomplex(b))print(&quot;Is real:&quot;, np.isreal(b))print(&quot;Is scalar:&quot;, np.isscalar(3.1))print(&quot;Is list a scalar:&quot;, np.isscalar([3.1]))</pre><p>A complex number contains a real component and an imaginary component. In Python, the letter j represents the imaginary unit.</p><p>For example, 1 + 1j has both real and imaginary components, whereas 4.5 is a real number.</p><p>The functions np.iscomplex() and np.isreal() test the individual values. An interesting detail is that 1 + 0j is mathematically real because its imaginary component is zero, even though it is represented using complex number notation.</p><p>The function np.isscalar() answers a different question. It checks whether an object is a scalar rather than a collection. A single number such as 3.1 is a scalar, while [3.1] is a list containing one element.</p><p>Why does this matter?</p><p>Because data structures influence how we process information. A single measurement, a list of measurements, and an array of measurements may contain similar values, but they are not interchangeable in every operation.</p><h3>Equality is not always exact</h3><p>One of the more interesting lessons came from comparing floating point numbers.</p><p>Consider the following code:</p><pre>b = np.array([1 + 1j, 1 + 0j, 4.5, 3, 2, 2j])<br>print(&quot;2. iscomplex:&quot;, np.iscomplex(b))<br>print(&quot;   isreal:   &quot;, np.isreal(b))<br>print(&quot;   isscalar(3.1):&quot;, np.isscalar(3.1))<br>print(&quot;   isscalar([3.1]):&quot;, np.isscalar([3.1]))</pre><pre>iscomplex: [ True False False False False  True]<br>isreal:    [False  True  True  True  True False]<br>isscalar(3.1): True<br>isscalar([3.1]): False</pre><p>Both functions compare numerical values, but they operate at different levels.</p><p>np.isclose() compares corresponding elements and returns a Boolean array. np.allclose() checks whether all corresponding elements satisfy the specified tolerance and returns a single Boolean value.</p><p>This distinction becomes important when dealing with decimal values.</p><p>Computers represent many decimal fractions using binary floating point. As a result, calculations may produce values that differ slightly from their mathematically expected results.</p><p>For example, a calculation intended to produce 0.3 might produce a value extremely close to 0.3, rather than exactly 0.3.</p><p>In scientific computing, engineering, and financial analysis, deciding whether two values are sufficiently close can be more useful than demanding exact equality.</p><h3>Comparing arrays and understanding memory</h3><p>I also explored comparison operators and array memory usage.</p><pre>p = np.array([3, 5])<br>q = np.array([2, 5])<br>print(&quot;4. greater:      &quot;, np.greater(p, q))<br>print(&quot;   greater_equal:&quot;, np.greater_equal(p, q))<br>print(&quot;   less:         &quot;, np.less(p, q))<br>print(&quot;   less_equal:   &quot;, np.less_equal(p, q))</pre><pre> greater:       [ True False]<br> greater_equal: [ True  True]<br> less:          [False False]<br> less_equal:    [False  True]</pre><p>These functions compare corresponding elements.</p><p>The first comparison produces:</p><pre>[ True False]</pre><p>Three is greater than two, but five is not greater than five.</p><p>Other functions allow us to check whether values are greater than or equal to one another, less than one another, or less than or equal to one another.</p><p>These operations are useful when filtering measurements, identifying thresholds, and checking conditions across large collections of data.</p><p>I also examined the size and memory footprint of an array.</p><pre>arr = np.array([1, 7, 13, 105])<br>print(&quot;6. size:&quot;, arr.size, &quot;| itemsize:&quot;, arr.itemsize,<br>      &quot;| bytes:&quot;, arr.size * arr.itemsize, &quot;| nbytes:&quot;, arr.nbytes)</pre><pre>6. size: 4 | itemsize: 8 | bytes: 32 | nbytes: 32</pre><p>The size tells us the number of elements in the array. The item size tells us the memory occupied by each element in bytes. The nbytes attribute gives the total memory occupied by the array&#39;s elements.</p><p>For this particular array, there are four elements. Because NumPy normally stores these integers using a 64 bit integer type on standard platforms, each element occupies eight bytes, giving a total of 32 bytes.</p><p>The exact item size depends on the array’s data type.</p><p>This exercise helped me appreciate that data analysis is not only about the values we see on screen. It also involves understanding how data is represented and stored in memory.</p><h3>Chapter Two: Pandas and the Art of Organising Information</h3><p>If NumPy taught me to examine numerical values, Pandas helped me understand how to organise and manipulate data.</p><p>Pandas is a Python library designed for working with structured data. Its two central data structures are the Series and the DataFrame.</p><p>A Series is a one dimensional labelled collection of values. A DataFrame is a two dimensional structure made up of rows and columns.</p><p>Think of a Series as one column in a spreadsheet and a DataFrame as the entire spreadsheet.</p><p>This distinction became clearer as I worked through the Pandas exercises.</p><h3>From a list to a Series</h3><p>Consider the following example:</p><pre>import pandas as pds1 = pd.Series([2, 4, 6, 8, 10])print(s1)</pre><p>The output looks something like this:</p><pre>0     2<br>1     4<br>2     6<br>3     8<br>4    10<br>dtype: int64</pre><p>The values appear alongside an index.</p><p>By default, Pandas assigns an integer index starting from zero. This index identifies each element and can be used to access or align values.</p><p>The dtype at the bottom indicates the data type. In this case, the Series contains 64 bit integers.</p><p>I then converted the Series into a regular Python list:</p><pre>lst = s1.tolist()print(lst)print(type(lst))</pre><p>The result is:</p><pre>[2, 4, 6, 8, 10]<br>&lt;class &#39;list&#39;&gt;</pre><p>Why would this conversion be useful?</p><p>A Pandas Series has features such as an index, data type information, and specialised methods. A Python list is a more basic collection that may be convenient when passing values to functions that expect ordinary Python objects.</p><p>The choice depends on what we want to do next.</p><h3>Arithmetic operations with Pandas</h3><p>The next exercise explored arithmetic operations between two Series.</p><pre>sa = pd.Series([2, 4, 6, 8, 10])sb = pd.Series([1, 3, 5, 7, 9])print(&quot;Addition:&quot;)print(sa + sb)print(&quot;Subtraction:&quot;)print(sa - sb)print(&quot;Multiplication:&quot;)print(sa * sb)print(&quot;Division:&quot;)print(sa / sb)</pre><p>Pandas performs the operations element by element, aligning values according to their index labels.</p><p>For addition, the first elements are added together, followed by the second elements, and so on.</p><p>The resulting values are:</p><pre>Addition:       [3, 7, 11, 15, 19]<br>Subtraction:    [1, 1, 1, 1, 1]<br>Multiplication: [2, 12, 30, 56, 90]<br>Division:       [2.0, 1.3333..., 1.2, 1.1428..., 1.1111...]</pre><p>I also explored floor division:</p><pre>print(sa // sb)</pre><p>Floor division returns the mathematical floor of each quotient.</p><p>For example, dividing six by five gives 1.2, but floor division returns 1, the greatest integer less than or equal to 1.2.</p><p>It is important not to confuse floor division with ordinary division or integer conversion. Floor division rounds down toward negative infinity, so its behaviour can be surprising for negative numbers.</p><p>These exercises introduced a useful concept: Pandas allows us to perform operations across entire collections without writing an explicit loop for every element.</p><p>However, there is one important detail. Pandas aligns Series by their index labels, not simply by their physical positions. If two Series have different indexes, arithmetic operations may produce unexpected results or missing values.</p><p>That is why understanding the structure of our data is just as important as understanding the operation.</p><h3>Converting between dictionaries, arrays, and Series</h3><p>Another exercise involved converting a dictionary into a Pandas Series.</p><pre>data = {    &#39;a&#39;: 100,    &#39;b&#39;: 200,    &#39;c&#39;: 300,    &#39;d&#39;: 400,    &#39;e&#39;: 800}series = pd.Series(data)print(series)</pre><p>The dictionary keys become the Series index, while the corresponding values become the data.</p><p>This is particularly useful when information already exists as key and value pairs.</p><p>For example, imagine having the names of five machines and their respective production counts. Converting that dictionary into a Series would provide a convenient structure for further analysis.</p><p>I also converted a NumPy array into a Series:</p><pre>npa = np.array([10, 20, 30, 40, 50])series = pd.Series(npa)print(series)</pre><p>Pandas assigns a default index because the original NumPy array does not have labelled indexes.</p><p>The exercise demonstrated how NumPy and Pandas complement each other. NumPy provides efficient numerical arrays, while Pandas adds labels and convenient tools for structured data analysis.</p><h3>The problem with inconsistent data types</h3><p>One of the more practical exercises involved converting a Series containing mixed values into numeric data.</p><pre>s7 = pd.Series([100, 200, &#39;python&#39;, 300.12, 400])numeric = pd.to_numeric(s7, errors=&#39;coerce&#39;)print(numeric)</pre><p>The original Series contains integers, a decimal number, and the string &#39;python&#39;.</p><p>The string cannot be interpreted as a number, so errors=&#39;coerce&#39; converts it to NaN.</p><p>The result is a numeric Series in which valid values are preserved and the invalid value is marked as missing.</p><p>This is a common situation in real datasets.</p><p>A column that should contain prices might contain a word accidentally entered by a user. A column intended for dates might contain inconsistent text. A sensor log might include error messages among its measurements.</p><p>The ability to identify and handle such values is a crucial part of data cleaning.</p><p>However, there is an important distinction between handling invalid values and deleting them. Converting an invalid entry into NaN does not resolve the underlying problem. We still need to investigate why the value is invalid and decide how it should be treated.</p><p>In a production environment, silently discarding such records could introduce bias or hide an operational issue.</p><h3>Flattening nested data and sorting values</h3><p>I also worked with a Series containing lists.</p><pre>s10 = pd.Series([    [&#39;Red&#39;, &#39;Green&#39;, &#39;White&#39;],    [&#39;Red&#39;, &#39;Black&#39;],    [&#39;Yellow&#39;]])print(s10.explode().reset_index(drop=True))</pre><p>The explode() method transforms each element of a list into a separate row.</p><p>Instead of having three rows containing lists, the result becomes a single sequence of six colour values.</p><p>The reset_index(drop=True) operation then creates a new sequential index.</p><p>This is useful when data is stored in nested structures and needs to be converted into a more conventional tabular format.</p><p>Another exercise explored sorting a Series that contained both numeric values and text.</p><pre>s11 = pd.Series([100, 200, &#39;python&#39;, 300.12, 400])print(    s11.sort_values(        key=lambda values: pd.to_numeric(            values, errors=&#39;coerce&#39;        )    ))</pre><p>The key function converts the values into a numeric representation for sorting purposes. The word &#39;python&#39; becomes NaN in that temporary representation.</p><p>The original values are not replaced by the converted values merely because they are used as a sorting key.</p><p>This is a subtle but useful distinction. We can sometimes use a transformed version of a column to determine its ordering without permanently changing the original data.</p><p>I also explored adding new values to an existing Series using pd.concat().</p><p>These exercises reinforced a broader lesson: data rarely arrives in a perfect structure. Before meaningful analysis can begin, we often need to reshape it, standardise it, sort it, or combine it with other information.</p><h3>Chapter Three: Moving from Python to SQL</h3><p>After working with arrays and Series, I moved into a different environment: SQL.</p><p>This was where the exercises began to resemble the work of a data analyst answering questions for a business, a researcher investigating a public health problem, or an engineer examining operational records.</p><p>SQL, or Structured Query Language, is used to retrieve and manipulate data stored in relational databases.</p><p>Instead of loading every record into a Python environment and processing it there, we can ask the database to filter, aggregate, join, and rank records before returning the results.</p><p>My assessment used datasets stored in different database schemas. These included airport weather records, customer churn data, international trade statistics, tuberculosis data, population figures, and loan approval records.</p><p>The challenge was no longer simply understanding individual values. It was learning how to retrieve the right information and turn it into a meaningful answer.</p><h3>First, understand the database</h3><p>Before analysing a dataset, it helps to understand its structure.</p><p>My first SQL task used INFORMATION_SCHEMA.COLUMNS to list every table in the week06 schema and count the columns in each table.</p><pre>SELECT<br>    TABLE_NAME AS table_name,<br>    COUNT(*) AS n_columns<br>FROM INFORMATION_SCHEMA.COLUMNS<br>WHERE TABLE_SCHEMA = &#39;week06&#39;<br>GROUP BY TABLE_NAME<br>ORDER BY TABLE_NAME;</pre><p>Let’s break this down.</p><p>INFORMATION_SCHEMA.COLUMNS contains metadata about database columns. It tells us which columns exist, the tables they belong to, and other structural information.</p><p>The WHERE clause restricts the results to the week06 schema.</p><p>The GROUP BY clause groups the metadata by table, while COUNT(*) counts the columns associated with each table.</p><p>Finally, ORDER BY arranges the table names alphabetically.</p><p>This is a useful starting point when entering an unfamiliar database. Rather than immediately querying the data, we first establish what is available.</p><p>In practical projects, this habit can save time. Understanding the database structure helps us identify the correct tables, discover column names, and avoid making assumptions about the data.</p><h3>Missing values are not ordinary values</h3><p>One of the SQL tasks examined London weather records and asked three questions:</p><p>How many days had no recorded weather event? How many days mentioned rain? And how many days had measurable precipitation despite having no recorded event?</p><p>The query was:</p><pre>SELECT<br>    SUM(<br>        CASE<br>            WHEN [ Events] IS NULL THEN 1<br>            ELSE 0<br>        END<br>    ) AS no_event_days,</pre><pre>    SUM(<br>        CASE<br>            WHEN [ Events] LIKE &#39;%Rain%&#39; THEN 1<br>            ELSE 0<br>        END<br>    ) AS rain_days,</pre><pre>    SUM(<br>        CASE<br>            WHEN [ Events] IS NULL<br>             AND Precipitationmm &gt; 0 THEN 1<br>            ELSE 0<br>        END<br>    ) AS wet_but_no_event_days</pre><pre>FROM week06.london_2014;</pre><p>There are several important concepts in this query.</p><p>First, the column name is written as [ Events] because the actual column name contains a leading space. SQL Server permits column names that contain spaces, but they must be referenced appropriately.</p><p>Second, SQL handles missing values using NULL. We cannot reliably test for missing values with = NULL. Instead, we use IS NULL or IS NOT NULL.</p><p>Third, CASE allows us to evaluate a condition and return a value depending on whether that condition is satisfied.</p><p>For example:</p><pre>CASE<br>    WHEN Precipitationmm &gt; 0 THEN 1<br>    ELSE 0<br>END</pre><p>This returns one when precipitation is greater than zero and zero otherwise.</p><p>By combining CASE with SUM, we can count records satisfying a condition. The technique is called conditional aggregation.</p><p>The final condition is particularly interesting. It identifies records where the event field is missing even though precipitation was recorded.</p><p>That does not automatically mean the dataset is wrong. It could indicate that the event field was not populated, that the event classification follows a different rule, or that the records require further investigation.</p><p>The important thing is that the query helps identify an inconsistency worth examining.</p><p>A missing label does not necessarily mean that nothing happened.</p><p>That principle applies well beyond weather analysis. In business data, an absent category, missing transaction description, or incomplete maintenance record should not automatically be interpreted as evidence that no event occurred.</p><h3>Chapter Four: When the Average Tells the Wrong Story</h3><p>One of the most important technical lessons in the assessment involved integer data types and numerical calculations.</p><p>Suppose a dataset records whether a customer churned. The column contains only two values:</p><p>0 means the customer did not churn.</p><p>1 means the customer churned.</p><p>If we calculate the average of this binary variable, we can obtain the proportion of customers who churned, provided the calculation preserves decimal precision.</p><p>For example, suppose four customers have the following outcomes:</p><pre>import numpy as npchurn = np.array([0, 0, 1, 0])print(np.mean(churn))</pre><p>The result is:</p><pre>0.25</pre><p>This means that 25 percent of the customers in this small example churned.</p><p>The same principle can be applied to a SQL query.</p><pre>SELECT<br>    ROUND(AVG(CAST(Churn AS DECIMAL(10, 2))), 3)<br>        AS churn_rate<br>FROM week16.customer_churn_prediction;</pre><p>The explicit conversion ensures that the average is calculated using a decimal representation rather than relying on an integer data type.</p><p>There is an important technical correction worth understanding here: in SQL Server, AVG() applied directly to an integer column returns an integer result type, but the average is calculated from the values before the final result is converted to that type. The result can therefore lose its fractional component. Casting the column to a decimal before calculating the average preserves the decimal result.</p><p>For example, an average of 0.25 from an integer column can be returned as 0, even though the underlying calculation is not zero.</p><p>This is dangerous because the query may execute successfully while producing an answer that misrepresents the data.</p><p>The same issue can arise when calculating average temperatures stored as integers. A true average of 11.8 degrees could be presented as 11 if the resulting value is converted to an integer.</p><p>An alternative is to multiply a binary variable by a decimal value such as 1.0 before aggregation, or to use an explicit decimal conversion.</p><p>The lesson is simple: understanding a query means understanding not only its syntax, but also the data types that determine its numerical behaviour.</p><h3>Chapter Five: Customer Churn and the Importance of Context</h3><p>The next task examined customer churn by contract type.</p><p>The business question was straightforward: how many customers belonged to each contract category, how many churned, and what percentage of customers churned within each category?</p><p>I approached it using conditional aggregation.</p><pre>SELECT<br>    Contract_Type,<br>    COUNT(*) AS customers,</pre><pre>    SUM(<br>        CASE<br>            WHEN Churn = 1 THEN 1<br>            ELSE 0<br>        END<br>    ) AS churned,</pre><pre>    ROUND(<br>        100.0 * SUM(<br>            CASE<br>                WHEN Churn = 1 THEN 1<br>                ELSE 0<br>            END<br>        ) / COUNT(*),<br>        1<br>    ) AS churn_rate_pct</pre><pre>FROM week16.customer_churn_prediction</pre><pre>GROUP BY Contract_Type</pre><pre>ORDER BY churn_rate_pct DESC;</pre><p>The query groups customers according to their contract type.</p><p>COUNT(*) calculates the number of records in each group. The conditional SUM counts the customers whose churn value is one. The final expression divides the number of churned customers by the total number of customers in each group and multiplies the result by 100.</p><p>The 100.0 is intentional. It helps ensure that the calculation uses decimal arithmetic rather than losing the fractional component through integer arithmetic.</p><p>Finally, ORDER BY churn_rate_pct DESC places the contract categories with the highest churn rates first.</p><p>This is a useful example of how a relatively short SQL query can answer a practical business question.</p><p>A company might use such an analysis to identify customer segments that deserve closer investigation.</p><p>However, a high churn rate does not explain why customers leave. It only identifies a pattern.</p><p>To understand the reasons behind that pattern, we might need to investigate pricing, service quality, contract duration, customer satisfaction, or other relevant variables.</p><p>Descriptive analysis tells us what is happening. Further investigation helps us understand why.</p><p>That distinction is essential when moving from data analysis to business decision making.</p><h3>Chapter Six: International Trade and the Power of GROUP BY and HAVING</h3><p>Another task involved international trade data.</p><p>The objective was to identify the partner countries to which the United Kingdom exported milk in all twelve months of 2014, together with the total export value for each country.</p><p>This problem required more than simply grouping records.</p><pre>SELECT<br>    Partner,<br>    SUM([Trade Value (US$)]) AS total_exports_usd</pre><pre>FROM week09.comtrade_milk_uk_monthly_14</pre><pre>WHERE [Trade Flow] = &#39;Exports&#39;<br>  AND Partner &lt;&gt; &#39;World&#39;</pre><pre>GROUP BY Partner</pre><pre>HAVING COUNT(DISTINCT Period) = 12</pre><pre>ORDER BY total_exports_usd DESC;</pre><p>The query introduces a distinction between WHERE and HAVING.</p><p>WHERE filters individual records before grouping. In this case, it retains export records and excludes the aggregate row labelled World.</p><p>GROUP BY then collects the records by partner country.</p><p>SUM() calculates the total trade value for each partner.</p><p>But the question asks for countries represented in all twelve months of the year. This is where HAVING becomes useful.</p><p>The expression:</p><pre>HAVING COUNT(DISTINCT Period) = 12</pre><p>retains only those partner groups with twelve distinct reporting periods.</p><p>The word DISTINCT matters because it counts unique periods rather than simply counting records.</p><p>This approach assumes that Period correctly represents the monthly reporting periods and that the dataset&#39;s reporting structure is consistent with the question.</p><p>It is also important to distinguish between twelve monthly records and twelve distinct months. A country could have multiple records in one month, so counting records alone would not reliably establish that all twelve months were represented.</p><p>This exercise demonstrated how SQL can express a business rule directly in a query.</p><p>Instead of retrieving all the records and checking each country manually, we can use grouping and filtering to isolate the records that satisfy the requirement.</p><p>It also taught me that the order of operations matters conceptually. Filtering, grouping, aggregating, and filtering groups are different stages of the same process.</p><h3>Chapter Seven: Joining Two Datasets to Tell a Bigger Story</h3><p>Data becomes much more powerful when different sources can be combined.</p><p>One of the assessment tasks involved joining tuberculosis data from the World Health Organization dataset with population data from the World Bank dataset.</p><p>The objective was to identify the five countries with the highest tuberculosis deaths per 100,000 people, using the World Bank population figures as the denominator.</p><p>The query was:</p><pre>SELECT TOP 5<br>    w.Country,</pre><pre>    ROUND(<br>        1.0 * w.[TB deaths] * 100000<br>        / b.[SP.POP.TOTL],<br>        1<br>    ) AS tb_deaths_per_100k</pre><pre>FROM week06.who_pop_tb_all AS w</pre><pre>JOIN week08.wb_pop_2013 AS b<br>    ON w.Country = b.country</pre><pre>ORDER BY tb_deaths_per_100k DESC;</pre><p>The calculation is based on a simple formula:</p><p>\[ \text{Deaths per 100,000 people} = \frac{\text{TB deaths}}{\text{Population}} \times 100,000 \]</p><p>Why multiply by 100,000?</p><p>Because raw death counts alone are not sufficient for comparing countries with different population sizes.</p><p>A country with a large population might record more deaths simply because it has more people. Expressing deaths relative to population provides a standardised measure that is more useful for comparison.</p><p>The JOIN combines records from the two datasets where the country names match. The ORDER BY clause ranks the calculated rates from highest to lowest, and TOP 5 returns the first five records.</p><p>The factor 1.0 helps preserve decimal arithmetic in the calculation.</p><p>However, this task also exposed a major challenge in data integration: two datasets can describe the same entity without identifying it in exactly the same way.</p><p>For example, international datasets may use different country names, spellings, or official naming conventions. One source may use Viet Nam, while another uses Vietnam. Other countries may have longer official names in one dataset and shorter names in another.</p><p>A join based on exact name equality will not recognise these as equivalent.</p><p>The following task investigated this problem using a left join.</p><pre>SELECT<br>    COUNT(*) AS who_countries_without_wb_match</pre><pre>FROM week06.who_pop_tb_all AS w</pre><pre>LEFT JOIN week08.wb_pop_2013 AS b<br>    ON w.Country = b.country</pre><pre>WHERE b.country IS NULL;</pre><p>A left join preserves all records from the WHO dataset, whether or not a matching World Bank record exists.</p><p>The WHERE b.country IS NULL condition then identifies records for which the join found no match.</p><p>This is known as an anti join pattern.</p><p>It is useful when identifying missing relationships between datasets, such as customers without corresponding account records, products without supplier matches, or countries without population data.</p><p>In a real data project, I would prefer standardised country identifiers, such as ISO country codes, over names wherever suitable identifiers are available. If that is not possible, a carefully reviewed mapping table can help reconcile different naming conventions.</p><p>There is also an important analytical consideration: the two datasets must refer to compatible time periods, and the meaning of the death count must be consistent with the population denominator.</p><p>A mathematically correct formula does not automatically guarantee a valid comparison. The definitions and coverage of the source data matter too.</p><h3>Chapter Eight: Comparing the Weather Across Six Cities</h3><p>One of the more interesting exercises involved combining weather records from six cities: Beijing, Brasilia, Cape Town, Delhi, London, and Moscow.</p><p>The objective was to calculate the average mean temperature for each city in 2014.</p><p>The records were stored in separate tables, which meant I needed a way to combine them into one dataset before calculating the averages.</p><p>This was an ideal use case for UNION ALL.</p><pre>SELECT<br>    city,</pre><pre>    ROUND(<br>        AVG(CAST([Mean TemperatureC] AS DECIMAL(10, 2))),<br>        1<br>    ) AS avg_mean_temp_c</pre><pre>FROM (<br>    SELECT<br>        &#39;Beijing&#39; AS city,<br>        [Mean TemperatureC]<br>    FROM week06.beijing_pek_2014</pre><pre>    UNION ALL</pre><pre>    SELECT<br>        &#39;Brasilia&#39;,<br>        [Mean TemperatureC]<br>    FROM week06.brasilia_bsb_2014</pre><pre>    UNION ALL</pre><pre>    SELECT<br>        &#39;Cape Town&#39;,<br>        [Mean TemperatureC]<br>    FROM week06.capetown_cpt_2014</pre><pre>    UNION ALL</pre><pre>    SELECT<br>        &#39;Delhi&#39;,<br>        [Mean TemperatureC]<br>    FROM week06.delhi_del_2014</pre><pre>    UNION ALL</pre><pre>    SELECT<br>        &#39;London&#39;,<br>        [Mean TemperatureC]<br>    FROM week06.london_2014</pre><pre>    UNION ALL</pre><pre>    SELECT<br>        &#39;Moscow&#39;,<br>        [Mean TemperatureC]<br>    FROM week06.moscow_svo_2014</pre><pre>) AS all_cities</pre><pre>GROUP BY city</pre><pre>ORDER BY city;</pre><p>The six SELECT statements retrieve the temperature column from each city table. UNION ALL stacks the results vertically, preserving the rows from each source.</p><p>The derived table, named all_cities, gives the combined dataset a consistent structure.</p><p>Each record has a city label and a temperature value.</p><p>Once the records are combined, the outer query groups them by city and calculates the average temperature.</p><p>I converted the temperature column to a decimal before applying AVG() and rounded the final result to one decimal place.</p><p>This ensures that the final averages can retain fractional values.</p><p>The task demonstrated an important data engineering principle: information stored in separate tables can often be analysed together once it has been brought into a common structure.</p><p>It also highlighted the difference between UNION and UNION ALL.</p><p>UNION removes duplicate rows, while UNION ALL preserves them. When combining daily weather observations from different tables, preserving every observation is generally appropriate, especially when each source represents a distinct city.</p><p>Removing duplicates without understanding the data could accidentally discard legitimate records.</p><p>A further consideration is that an annual average does not tell the entire story of a city’s climate. Seasonal variation, extreme temperatures, missing observations, and differences in data coverage can all influence how the result should be interpreted.</p><p>The average is a useful starting point, not a complete description.</p><h3>Chapter Nine: Finding the Hottest Day of Every Month</h3><p>The next task focused on a single city.</p><p>Rather than calculating one average for the entire year, I needed to identify the hottest day in each month of London’s 2014 weather records.</p><p>The requirement included a tie breaking rule: if two days had the same maximum temperature, the earlier date should be selected.</p><p>This was a good opportunity to use a common table expression and a window function.</p><pre>WITH ranked AS (<br>    SELECT<br>        MONTH(TRY_CONVERT(date, GMT)) AS month_no,</pre><pre>        TRY_CONVERT(date, GMT) AS day,</pre><pre>        [Max TemperatureC] AS max_temp,</pre><pre>        ROW_NUMBER() OVER (<br>            PARTITION BY MONTH(TRY_CONVERT(date, GMT))<br>            ORDER BY<br>                [Max TemperatureC] DESC,<br>                TRY_CONVERT(date, GMT) ASC<br>        ) AS rn</pre><pre>    FROM week06.london_2014<br>)</pre><pre>SELECT<br>    month_no,<br>    day,<br>    max_temp</pre><pre>FROM ranked</pre><pre>WHERE rn = 1</pre><pre>ORDER BY month_no;</pre><p>This query may look intimidating at first, but it becomes easier to understand when broken into stages.</p><p>The common table expression, introduced with WITH ranked AS, creates a temporary named result that can be referenced by the main query.</p><p>Within that result, TRY_CONVERT(date, GMT) attempts to convert the GMT column into a date. If a value cannot be converted, it returns NULL rather than raising the conversion error that an unsuccessful ordinary conversion could produce.</p><p>MONTH() extracts the month number from the converted date.</p><p>The most important part is the window function:</p><pre>ROW_NUMBER() OVER (<br>    PARTITION BY MONTH(TRY_CONVERT(date, GMT))<br>    ORDER BY<br>        [Max TemperatureC] DESC,<br>        TRY_CONVERT(date, GMT) ASC<br>)</pre><p>PARTITION BY divides the records into monthly groups for ranking purposes.</p><p>Within each month, ORDER BY ranks the highest maximum temperature first. When temperatures tie, the earlier date comes first.</p><p>ROW_NUMBER() then assigns each record a sequential number within its month.</p><p>The outer query filters for rn = 1, leaving only the top ranked record from each month.</p><p>This is a powerful technique because it solves a problem that ordinary aggregation alone cannot solve conveniently.</p><p>An expression such as MAX([Max TemperatureC]) would give the maximum temperature for each month, but it would not by itself identify the complete date of the corresponding observation. A window function allows us to rank the original rows and retain the record we need.</p><p>I found this concept particularly useful because similar problems occur in many industries.</p><p>A manufacturing engineer might need the day with the highest machine vibration each month. A business analyst might need the highest sales transaction for each region. A financial analyst might need the most recent transaction for each account.</p><p>In each case, the objective is to identify a particular record within a group.</p><p>Window functions make that possible without requiring separate queries for every group.</p><h3>Chapter Ten: Understanding Running Totals</h3><p>Another SQL task returned monthly UK milk export values and a cumulative total for the year.</p><p>This introduced one of the most practical applications of window functions.</p><pre>WITH monthly AS (<br>    SELECT<br>        Period,</pre><pre>        SUM([Trade Value (US$)]) AS exports_usd</pre><pre>    FROM week09.comtrade_milk_uk_monthly_14</pre><pre>    WHERE [Trade Flow] = &#39;Exports&#39;<br>      AND Partner &lt;&gt; &#39;World&#39;</pre><pre>    GROUP BY Period<br>)</pre><pre>SELECT<br>    Period,<br>    exports_usd,</pre><pre>    SUM(exports_usd) OVER (<br>        ORDER BY Period<br>        ROWS UNBOUNDED PRECEDING<br>    ) AS ytd_exports_usd</pre><pre>FROM monthly</pre><pre>ORDER BY Period;</pre><p>The first stage aggregates the export values by month.</p><p>The second stage calculates a running total.</p><p>A running total is a cumulative sum that adds each period’s value to the values from all preceding periods.</p><p>Imagine that monthly exports were 100, 150, and 200 units of currency. The running totals would be 100, 250, and 450.</p><p>The calculation uses:</p><pre>SUM(exports_usd) OVER (<br>    ORDER BY Period<br>    ROWS UNBOUNDED PRECEDING<br>)</pre><p>The OVER clause turns the sum into a window calculation. The ORDER BY specifies the sequence in which the cumulative values are calculated, while ROWS UNBOUNDED PRECEDING defines the window as starting at the first row and ending at the current row.</p><p>Unlike a regular aggregate function, this calculation retains a row for every month while adding the cumulative result.</p><p>That is the key difference.</p><p>If we simply grouped the data and summed all exports, we would get one total for the entire period. With a running total, we can observe how the cumulative figure changes over time.</p><p>This technique is useful in revenue reporting, budget tracking, inventory analysis, production monitoring, and many other situations where understanding progress over time matters.</p><p>It can help answer questions such as how much revenue has been generated so far this year or how much material has been consumed since the beginning of a reporting period.</p><p>One detail deserves attention: the Period column must sort in genuine chronological order for the running total to be meaningful. If periods are stored as text in a format that does not sort chronologically, the ordering needs to be corrected first.</p><p>Again, the logic of the calculation is only as reliable as the structure of the underlying data.</p><h3>Chapter Eleven: When the Data Looks Too Perfect</h3><p>The final assessment task was particularly important because it moved beyond writing SQL and into evaluating the quality of the information itself.</p><p>The business question came from a Head of Credit who wanted to know how loan approval rates varied by property area and credit history.</p><p>The task used a dataset called week17.loan_approval_prediction.</p><p>The query grouped records by property area and credit history, counted applications, and calculated the percentage of approved loans.</p><pre>SELECT<br>    Property_Area,<br>    Credit_History,</pre><pre>    COUNT(*) AS applications,</pre><pre>    ROUND(<br>        100.0 * SUM(<br>            CASE<br>                WHEN Loan_Approved = 1 THEN 1<br>                ELSE 0<br>            END<br>        ) / COUNT(*),<br>        1<br>    ) AS approval_rate_pct</pre><pre>FROM week17.loan_approval_prediction</pre><pre>GROUP BY<br>    Property_Area,<br>    Credit_History</pre><pre>ORDER BY<br>    Property_Area,<br>    Credit_History;</pre><p>Technically, the query is relatively straightforward.</p><p>The more interesting part came after examining the resulting pattern.</p><p>The notebook’s reflection recorded the following behaviour: every Rural application had Credit_History = 0 and was rejected, producing a zero percent approval rate. Every Semiurban and Urban application had Credit_History = 1 and was approved, producing a 100 percent approval rate.</p><p>In other words, property area, credit history, and the approval outcome lined up perfectly in the observed data.</p><p>That should raise questions.</p><p>In real lending environments, loan decisions are influenced by multiple factors. Credit history may matter, but so can income, existing debt, repayment capacity, loan amount, employment stability, and institutional lending policies.</p><p>A dataset in which every group perfectly predicts the outcome may reflect a simplified synthetic dataset, a filtering process, a data generation rule, or some other structural issue.</p><p>The pattern alone does not establish which explanation is correct.</p><p>But it is enough to justify investigating the dataset before using it to train a model.</p><p>Imagine building a machine learning model on this data.</p><p>A model could learn an apparently successful rule: reject Rural applications and approve Urban and Semiurban applications.</p><p>If the model were evaluated using data generated by the same underlying rule, it might achieve impressive performance metrics.</p><p>Yet that would not prove that it had learned a reliable relationship applicable to real loan applicants.</p><p>It might simply have learned the rule used to construct the dataset.</p><p>This is where data analysis becomes closely connected to responsible machine learning.</p><p>A model can only learn from the patterns presented to it. If those patterns are unrealistic, biased, incomplete, or generated using simplistic assumptions, the model may reproduce those limitations.</p><p>There is also a fairness concern. Property area is a geographical characteristic, and using it as a direct basis for loan approval could produce discriminatory outcomes or create regulatory concerns depending on the context and applicable law.</p><p>The appropriate response is not to assume wrongdoing or immediately discard the data. It is to investigate.</p><p>I would begin by checking the data generation process, reviewing the number of records in each group, examining the distributions of other variables, and confirming whether the approval outcomes were created from a deterministic rule.</p><p>I would also investigate whether the dataset had been filtered or transformed before it reached the analysis stage.</p><p>Only after establishing how the data was produced would I decide whether it was suitable for modelling.</p><p>This task taught me one of the most important lessons in the entire notebook.</p><p>A technically correct analysis can still lead to a poor decision if the underlying data is not trustworthy.</p><p>Sometimes, the most valuable contribution a data analyst can make is to explain why a dataset should not yet be used to train a model.</p><h3>Chapter Twelve: The Challenges That Changed How I Think</h3><p>Looking back at the work, several challenges stood out.</p><h3>1. Understanding how data types influence results</h3><p>At first, many numerical operations seemed intuitive. Addition adds values, averages calculate means, and comparisons determine whether one value is greater than another.</p><p>But the exercises showed that data types influence the results we receive.</p><p>Floating point comparisons require an understanding of tolerance. Mixed data types require careful conversion. Integer averages may lose fractional information when the result is returned as an integer.</p><p>I learned to pay attention to the type of data entering a calculation, not just the operation being performed.</p><h3>2. Distinguishing between similar SQL concepts</h3><p>SQL contains many concepts that look similar but serve different purposes.</p><p>WHERE filters records before aggregation. HAVING filters groups after aggregation. GROUP BY creates groups. Window functions calculate values across related rows while preserving individual records.</p><p>The easiest way to understand these concepts was to connect each one to the question it answers.</p><p>If I wanted to exclude unwanted records before calculating totals, I used WHERE.</p><p>If I wanted to retain only groups satisfying a condition, I used HAVING.</p><p>If I wanted to rank records within categories, I used a window function.</p><p>This approach made the syntax easier to remember because I was learning the reasoning behind the code rather than memorising isolated commands.</p><h3>3. Combining datasets reliably</h3><p>Joining WHO data with World Bank population figures highlighted the difficulty of matching information across independent sources.</p><p>Different names can refer to the same country. Different reporting periods can complicate comparisons. Missing matches can lead to incomplete analyses.</p><p>I learned that data integration requires more than finding two tables with apparently similar columns. We need to understand what those columns represent and whether their values can be matched reliably.</p><h3>4. Knowing when to question the result</h3><p>The loan approval exercise reinforced the importance of critical thinking.</p><p>It is easy to focus on whether a query runs successfully or whether a model achieves a high score.</p><p>It is harder, but more important, to ask whether the result is plausible, whether the data represents the real world, and whether a conclusion could lead to a harmful decision.</p><p>I want to carry that habit into every future project.</p><p>When a result looks unusual, I should investigate it rather than immediately celebrating it.</p><p>When a model appears exceptionally accurate, I should examine the data generation process and check for leakage, bias, or unrealistic patterns.</p><p>When a query returns an answer, I should still ask whether that answer makes sense.</p><h3>Final Thoughts: Learning to Think Like a Data Analyst</h3><p>This week’s work started with relatively small tasks: identifying missing numerical values, comparing arrays, converting lists into Series, and performing arithmetic operations.</p><p>It progressed into SQL queries that combined datasets, calculated rates, ranked observations, generated running totals, and investigated patterns in loan approval data.</p><p>The technical tools were different, but the underlying objective remained the same.</p><p>I was learning how to move from raw data to meaningful answers.</p><p>NumPy helped me understand numerical data and precision.</p><p>Pandas taught me how to organise, transform, and clean structured information.</p><p>SQL showed me how to retrieve and analyse data stored across relational tables.</p><p>Window functions helped me rank records and track cumulative changes over time.</p><p>Most importantly, the final assessment reminded me that analytical thinking does not end when the code finishes running.</p><p>A result must be interpreted. Its assumptions must be examined. Its limitations must be understood.</p><p>And when something does not look right, the analyst must be willing to question it.</p><p>I am beginning to see data analysis as more than a collection of libraries, functions, and queries. It is a way of approaching problems systematically, testing assumptions, and using evidence to make better decisions.</p><p>There is still a great deal to learn, but this week’s exercises have given me a stronger foundation to build on.</p><p>My biggest takeaway is this:</p><p>Do not just learn how to make code produce an answer. Learn how to determine whether that answer deserves to be trusted.</p><p>That is the difference between simply writing code and learning to think like a data analyst.</p><p>What has been the most important lesson in your data analysis journey so far? Was it learning a difficult technical concept, debugging a query, or discovering that the data itself was telling a different story than you expected? I would love to hear your experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4ca85bb4e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Enabled Digital Twins: How Machine Learning Can Predict Machinery Failure Before It Happens]]></title>
            <link>https://medium.com/@ronphreylucky/ai-enabled-digital-twins-how-machine-learning-can-predict-machinery-failure-before-it-happens-2a513754c225?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a513754c225</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 04:25:50 GMT</pubDate>
            <atom:updated>2026-10-13T05:10:34.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI-Enabled Digital Twins: How Machine Learning Can Predict Machinery Failure Before It Happens.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*uwnunoUsNDHLtHcxiXb1kw.png" /></figure><p>Exploring the role of artificial intelligence, remaining useful life prediction, and digital twins in the future of industrial maintenance.</p><h3>Introduction</h3><p>Imagine a manufacturing plant where a critical machine begins to deteriorate. Instead of waiting for the machine to break down or relying on a routine maintenance schedule, engineers receive an early indication that its performance is declining. They can estimate how much useful operating life remains, examine changes in sensor readings, and determine whether the equipment requires closer inspection.</p><p>This is the promise of AI-enabled predictive maintenance.</p><p>Industrial facilities depend on machinery such as electric motors, pumps, compressors, gearboxes, fans, and production equipment. When these assets fail unexpectedly, the consequences can include production downtime, increased maintenance expenses, damaged components, and potential safety risks. For industries where continuous operation is essential, identifying equipment degradation before it develops into a serious failure can be extremely valuable.</p><p>Traditional maintenance approaches remain important, but advances in artificial intelligence (AI), machine learning (ML), and digital twin technology are creating opportunities for more condition-aware maintenance systems.</p><p>One particularly promising approach is the integration of an AI-based Remaining Useful Life (RUL) prediction model with a digital twin. Rather than simply predicting equipment degradation, this approach aims to represent the condition of an asset digitally, update its virtual state as new observations become available, and present information that supports maintenance decisions.</p><p>This article explores how such a system works, the technologies involved, and how it can be developed and evaluated using machine learning.</p><h3>Understanding predictive maintenance</h3><p>Maintenance strategies can broadly be divided into three categories: reactive, preventive, and predictive maintenance.</p><p>Reactive maintenance involves repairing equipment after a failure occurs. Although this may be reasonable for inexpensive, non-critical components, it can be costly when applied to essential production machinery.</p><p>Preventive maintenance involves servicing equipment according to a predetermined schedule. For example, a motor might be inspected every three months, regardless of its actual condition. This reduces dependence on emergency repairs, but it can lead to unnecessary maintenance or fail to detect deterioration that develops between scheduled inspections.</p><p>Predictive maintenance takes a different approach. It uses equipment condition data and analytical models to estimate developing problems and support decisions about when maintenance may be required.</p><p>Sensor measurements such as vibration, temperature, pressure, electrical current, rotational speed, and operating cycles can provide useful information about the condition of machinery. Machine learning models can analyse these measurements to identify patterns associated with degradation.</p><p>However, detecting an abnormal reading is not the same as predicting when a machine may fail. This distinction introduces the concept of Remaining Useful Life.</p><h3>What is Remaining Useful Life (RUL)?</h3><p>Remaining Useful Life refers to the estimated amount of operating life an asset has left before reaching a defined failure condition or end-of-life threshold.</p><p>For example, suppose a machine learning model estimates that a component has 120 operating cycles remaining before it reaches the failure threshold defined in the training data.</p><p>This estimate gives maintenance engineers information they can use to investigate the equipment, plan inspections, assess spare-parts requirements, and consider an appropriate maintenance window.</p><p>RUL prediction is a regression problem because the model estimates a numerical value rather than simply assigning a class such as “healthy” or “faulty.”</p><p>A simplified machine learning workflow might look like this:</p><p>Machine operating data</p><p>Temperature, vibration, pressure, speed and operating cycles</p><p>Machine learning model</p><p>Learns patterns associated with equipment degradation</p><p>RUL estimate</p><p>Predicts remaining operating cycles or another clearly defined life measure</p><p>Maintenance review</p><p>Combines the prediction with asset criticality, inspection findings and operating conditions</p><p>It is important to recognise that an RUL estimate is not a guarantee of when failure will occur. Actual equipment life can be affected by changing loads, operating environments, maintenance activities, and failure mechanisms that were not represented in the training data.</p><p>Furthermore, a prediction expressed in operating cycles cannot automatically be interpreted as days or months. Such a conversion requires a defensible relationship between operating cycles and elapsed time.</p><h3>What is a digital twin, and why does it matter?</h3><p>A digital twin is a digital representation of a specific physical asset or system that maintains a defined relationship with its real-world counterpart through data, models, and state updates.</p><p>A digital twin can help engineers understand how an asset is performing, examine historical behaviour, and evaluate its current condition. Depending on the implementation, it may also support simulations and what-if analysis.</p><p>It is important to distinguish a digital twin from a conventional dashboard. A dashboard can display sensor readings and machine learning predictions, but a digital twin additionally maintains an asset-specific representation and a defined mechanism for updating that representation as new information becomes available.</p><p>In an AI-enabled maintenance system, the digital twin provides the context in which machine learning predictions can be interpreted.</p><p>For example, consider a pump in a manufacturing facility. Its virtual representation could maintain its operating history, recent temperature trends, vibration measurements, estimated RUL, and maintenance-review status.</p><p>When new observations arrive, the system updates the pump’s virtual state and generates a new estimate using the selected model. Engineers can then examine the prediction alongside the available evidence instead of relying on a single isolated number.</p><p>The digital twin does not eliminate the need for engineering judgement. Its purpose is to make equipment information more structured, accessible, and useful.</p><h3>Integrating AI, machine learning, and digital twins</h3><p>The real value of the proposed approach comes from integrating several components into one coherent workflow.</p><p>1. Data acquisition and preparation</p><p>The process begins with collecting equipment data. In a live industrial deployment, this might involve sensors, programmable logic controllers, industrial monitoring systems, or historical maintenance records.</p><p>The data must be checked for missing observations, inconsistent measurements, sensor faults, and other quality issues. Features may then be selected or engineered to represent the machine’s operating condition.</p><p>2. Machine learning and RUL prediction</p><p>The prepared data are passed to a trained model that estimates the remaining useful life.</p><p>The proposed research will compare a simple baseline against two tree-based regression approaches: Random Forest and gradient boosting. These models are suitable starting points for structured sensor data because they can learn nonlinear relationships without requiring a complex deep learning architecture.</p><p>An LSTM or another sequence model could be explored later if the core experiments and prototype are completed successfully.</p><p>3. Digital asset state updating</p><p>The system maintains a virtual record of the asset. This record can contain the latest observation, operating cycle, recent sensor trends, predicted RUL, and model version.</p><p>As time-ordered observations are processed, the virtual asset record is updated to reflect the latest available information.</p><p>4. Maintenance-oriented visualisation</p><p>A user interface brings the different components together. Engineers can view the estimated RUL, historical trends, relevant health indicators, and an indication of whether further maintenance review may be appropriate.</p><p>Where a defensible uncertainty estimation method is available, the interface can also display prediction intervals rather than implying that the estimated RUL is exact.</p><p>This integration is what makes the research more than a standalone machine learning experiment. It examines how predictions can be incorporated into an asset-specific representation and presented in a way that supports engineering decisions.</p><h3>How can the system be developed and tested?</h3><p>A practical way to investigate this concept is to begin with a public equipment degradation dataset rather than immediately attempting to connect the system to a live manufacturing plant.</p><p>The proposed study will use the NASA C-MAPSS turbofan engine degradation dataset as its initial experimental benchmark. This dataset contains simulated engine operating and sensor data that have been used in prognostics research.</p><p>Although the dataset represents aircraft engines rather than typical factory machinery, it provides a structured starting point for developing and evaluating RUL prediction methods.</p><p>The research can follow five main stages.</p><h3>Stage 1: Explore and prepare the dataset</h3><p>The first step is to understand the available sensor measurements, operating conditions, engine identifiers, and operating cycles.</p><p>The target variable will be defined as RUL in operating cycles. Data preparation will be designed to prevent information leakage, particularly by ensuring that observations from the same engine are not improperly distributed across training and validation groups.</p><h3>Stage 2: Train and compare machine learning models</h3><p>A simple baseline will be established first. Random Forest and gradient boosting will then be trained and compared using a consistent evaluation protocol.</p><p>Model performance will be assessed using metrics such as Mean Absolute Error (MAE) and Root Mean Squared Error (RMSE).</p><p>MAE measures the average magnitude of prediction errors, while RMSE penalises larger errors more heavily. Both are useful because a model that performs well on average may still make particularly poor predictions at critical stages of degradation.</p><h3>Stage 3: Examine the reliability of predictions</h3><p>The evaluation will investigate how prediction errors change across the observed degradation trajectory.</p><p>Where feasible, prediction intervals will be explored using a method such as conformal prediction calibrated on separate validation data. This would help communicate uncertainty around the estimated RUL.</p><p>If uncertainty estimation cannot be implemented reliably, the system should state that limitation rather than display unsupported confidence values.</p><h3>Stage 4: Build the digital twin prototype</h3><p>A lightweight application developed in Python, potentially using Streamlit, will serve as the interface for the virtual asset representation.</p><p>The prototype will replay historical observations in chronological order, update the selected asset’s virtual state, and display the model’s RUL estimate alongside sensor trends and maintenance-review indicators.</p><p>Because the initial study will use historical simulated data, this will be a data-driven digital twin prototype rather than a fully connected, real-time industrial deployment.</p><h3>Stage 5: Evaluate the integrated system</h3><p>The final evaluation will consider both predictive performance and system functionality.</p><p>This includes verifying that the correct asset is selected, observations are processed in chronological order, virtual state updates are consistent, predictions are reproducible, and the interface communicates units and limitations clearly.</p><p>The research will also examine whether the model’s performance is sufficient to justify further investigation and what additional data would be required before deployment in a real manufacturing environment.</p><h3>What are the potential industrial benefits?</h3><p>An effective AI-enabled digital twin could support several maintenance activities.</p><ul><li>Earlier identification of degradation: Changes in sensor patterns and predicted remaining life could help engineers identify assets that require closer investigation.</li><li>More informed maintenance planning: RUL estimates could contribute to decisions about inspection timing, maintenance scheduling, and spare-parts preparation.</li><li>Better visibility of asset condition: Presenting sensor trends and predictions together could help maintenance teams understand why an asset has been flagged for review.</li><li>More structured condition monitoring: A virtual asset record can organise historical observations, model outputs, and condition indicators in one place.</li><li>Improved use of maintenance resources: More informative condition assessments could help teams prioritise inspections, subject to the reliability of the models and the quality of the underlying data.</li></ul><p>These are potential benefits rather than outcomes established by the proposed experiment. Demonstrating actual reductions in downtime or maintenance expenditure would require a separate evaluation using real industrial data and operational evidence.</p><h3>Challenges and limitations</h3><p>Despite its potential, the integration of AI and digital twins presents several challenges.</p><p>First, the quality of predictions depends on the representativeness of the training data. A model trained on simulated turbofan degradation may not perform reliably on an industrial pump, gearbox, or electric motor without additional data and validation.</p><p>Second, machine learning predictions can be misleading if the evaluation process allows data leakage or if the model is tested under conditions that differ substantially from those used for training.</p><p>Third, uncertainty must be communicated responsibly. An RUL estimate of 120 cycles should not be presented as an assurance that a machine will operate safely for exactly 120 more cycles.</p><p>Finally, maintenance decisions depend on more than predicted life. Asset criticality, inspection results, safety requirements, spare-parts availability, and operating conditions must all be considered.</p><p>For these reasons, the proposed prototype will support maintenance review rather than make autonomous maintenance decisions or claim to provide a safety-certified solution.</p><h3>Conclusion</h3><p>The integration of artificial intelligence, machine learning, and digital twin technology offers a promising approach to predictive maintenance in manufacturing.</p><p>RUL prediction provides an estimate of how much operating life an asset may have remaining. A digital twin adds an asset-specific representation that can be updated as observations are processed, while a maintenance-oriented interface connects predictions with sensor trends and operational context.</p><p>The proposed research, AI-Enabled Digital Twin for Predictive Maintenance and Remaining Useful Life Prediction of Industrial Machinery, will investigate this integration through a reproducible machine learning experiment and a lightweight digital twin prototype.</p><p>By comparing baseline and tree-based models, examining prediction errors, exploring uncertainty estimation, and evaluating the integrated workflow, the study aims to demonstrate how machine learning outputs can be transformed into more useful maintenance information.</p><p>The broader lesson is that successful predictive maintenance requires more than an accurate algorithm. It requires reliable data, rigorous evaluation, transparent communication of uncertainty, and a clear understanding of how predictions should inform engineering decisions.</p><p>The ultimate objective is not simply to predict when machinery might fail, but to help engineers make better-informed decisions about equipment condition, inspection, and maintenance.</p><p>Research note: This article is based on the proposed research framework and methodology. It describes planned experiments and potential applications, not completed model results or verified industrial savings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a513754c225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Beyond the Basics: Working with Modules, JSON, Dates, Errors, and Virtual Environments.]]></title>
            <link>https://medium.com/@ronphreylucky/python-beyond-the-basics-working-with-modules-json-dates-errors-and-virtual-environments-f9878e0fe71e?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9878e0fe71e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 10:54:28 GMT</pubDate>
            <atom:updated>2026-09-27T10:54:28.992Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding some of the Python concepts that turn simple scripts into more reliable and practical applications.</p><p>When learning Python, it is easy to focus on syntax: variables, loops, functions, lists, and dictionaries. These are important, but writing useful Python programs requires more than knowing the language syntax.</p><p>You eventually need to work with dates, mathematical operations, structured data, external packages, user input, and unexpected errors. You also need to understand how to organize dependencies so that one project does not interfere with another.</p><p>This is where concepts such as <strong>modules, packages, JSON, </strong><strong>datetime, exception handling, </strong><strong>pip, and virtual environments</strong> become important.</p><p>This article explores these concepts and demonstrates how they work together in practical Python programming.</p><h3>1. Python Modules: Reusing Functionality Instead of Reinventing It</h3><p>A Python program does not have to contain every function it needs.</p><p>Python provides modules containing reusable functionality that can be imported into our programs.</p><p>For example, the math module provides mathematical operations that would otherwise require us to implement them ourselves.</p><pre>import math</pre><pre>print(math.sqrt(144))</pre><p>The result is:</p><pre>12.0</pre><p>Here, math is the module while sqrt() is a function provided by that module.</p><p>This distinction is important because Python programs frequently depend on functionality defined elsewhere.</p><h3>Importing an entire module</h3><pre>import math</pre><pre>result = math.sqrt(144)</pre><p>We access the function using the module name:</p><pre>math.sqrt()</pre><h3>Importing a specific function</h3><p>Alternatively:</p><pre>from math import sqrt</pre><pre>result = sqrt(144)</pre><p>Now the function can be called directly.</p><p>The difference is therefore not about what the function does, but about <strong>how it is made available in the program</strong>.</p><h3>2. Modules vs Packages</h3><p>As Python projects become larger, a single file is often not enough.</p><p>A <strong>module</strong> is generally a Python file containing reusable code.</p><p>For example:</p><pre>calculator.py</pre><p>A <strong>package</strong> in Python is a way of organizing related modules into a structured collection. While a module is typically a single .py file, a package can contain multiple modules and subpackages.</p><p>For example, imagine we are building a data processing application:</p><pre>data_project/<br>│<br>├── calculations/<br>│   ├── __init__.py<br>│   ├── statistics.py<br>│   └── mathematics.py<br>│<br>├── data/<br>│   ├── __init__.py<br>│   ├── cleaning.py<br>│   └── processing.py<br>│<br>└── main.py</pre><p>Here, calculations and data can be organized as packages, while statistics.py, mathematics.py, cleaning.py, and processing.py are modules.</p><h3>Package vs Module</h3><p>The easiest way to understand the relationship is:</p><p><strong><em>A module is a file; a package is a way of organizing related modules.</em></strong></p><p>For example:</p><pre>math_tools.py</pre><p>could be a module.</p><p>While:</p><pre>math_tools/<br>    __init__.py<br>    algebra.py<br>    geometry.py<br>    statistics.p</pre><p>can represent a package containing several related modules.</p><h3>The __init__.py File</h3><p>You will often see a file named:</p><pre>__init__.py</pre><p>inside a Python package.</p><p>For example:</p><pre>my_package/<br>├── __init__.py<br>├── calculations.py<br>└── utilities.py</pre><p>The file is associated with the package and can contain initialization code or expose selected functionality from the package.</p><p>In modern Python, a directory can also function as a <strong>namespace package</strong> without an __init__.py file, but you will still commonly encounter __init__.py in conventional Python packages.</p><p>It is therefore useful to recognize the file even when it contains no code.Importing from a Package</p><p>Suppose we have:</p><pre>my_package/<br>├── __init__.py<br>└── calculations.py</pre><p>And calculations.py contains:</p><pre>def add(a, b):<br>    return a + b</pre><p>We can import the function from the module inside the package:</p><pre>from my_package.calculations import add<br><br>result = add(10, 5)<br><br>print(result)</pre><p>Output:</p><pre>15</pre><p>The import path tells Python exactly where the function is located:</p><pre>my_package → calculations → add</pre><p>This becomes increasingly useful as projects grow and functionality is separated into different files.</p><h3>Standard Library Packages vs Third Party Packages</h3><p>Not every package has to be installed manually.</p><p>Python comes with a large <strong>standard library</strong>, which contains modules and packages that are available as part of a normal Python installation.</p><p>Examples include:</p><pre>import math<br>import json<br>import datetime</pre><p>These do not normally require:</p><pre>pip install</pre><p>On the other hand, many popular libraries are third-party packages.</p><p>For example:</p><pre>pip install numpy</pre><p>allows us to install NumPy into the current Python environment.</p><p>Other commonly used third-party packages include libraries for data analysis, machine learning, web development, visualization, and API development.</p><h3>4. Working with Dates and Times</h3><p>Dates are another common requirement in software.</p><p>Applications need dates to:</p><ul><li>record events</li><li>calculate age</li><li>determine the difference between two dates</li><li>calculate upcoming events</li><li>display information in a readable format</li></ul><p>Python provides the datetime module for this purpose.</p><p>For example:</p><pre>from datetime import datetime</pre><pre>now = datetime.now()</pre><pre>print(now)</pre><p>We can also access individual components:</p><pre>print(now.year)<br>print(now.month)<br>print(now.day)</pre><p>This allows us to work with the year, month, and day independently.</p><h3>5. Formatting Dates for Humans</h3><p>Computers can represent dates in a way that is useful internally but not necessarily convenient for users.</p><p>For example, we may want to display today’s date as:</p><pre>27-09-2026</pre><p>rather than a longer datetime representation.</p><p>Python’s strftime() method allows us to format a datetime object:</p><pre>today = datetime.now()</pre><pre>formatted_date = today.strftime(&quot;%d-%m-%Y&quot;)</pre><pre>print(formatted_date)</pre><p>The formatting codes tell Python how the date should be displayed.</p><pre>%d → day<br>%m → month<br>%Y → four-digit year</pre><p>This becomes particularly useful when building applications that interact with users.</p><h3>6. Parsing Dates from User Input</h3><p>Formatting is only half of the problem.</p><p>Sometimes a program receives a date as a string:</p><pre>25-12-2026</pre><p>Python needs to convert that string into a datetime object before performing date calculations.</p><p>This is where strptime() is useful.</p><pre>date_string = &quot;25-12-2026&quot;</pre><pre>date = datetime.strptime(date_string, &quot;%d-%m-%Y&quot;)</pre><pre>print(date)</pre><p>There is an important distinction between the two functions:</p><pre>strftime()<br>datetime → string</pre><p>while:</p><pre>strptime()<br>string → datetime</pre><p>Remembering this difference is useful whenever an application receives dates from users or external data sources.</p><h3>7. Using Dates to Calculate Age</h3><p>Once dates can be converted into Python datetime objects, we can perform useful calculations.</p><p>For example, a program can ask for a user’s birth year:</p><pre>birth_year = int(input(&quot;Enter your birth year: &quot;))</pre><pre>current_year = datetime.now().year</pre><pre>age = current_year - birth_year</pre><pre>print(f&quot;You are approximately {age} years old.&quot;)</pre><p>The process is straightforward:</p><ol><li>Receive the birth year.</li><li>Convert the input into an integer.</li><li>Obtain the current year.</li><li>Subtract the birth year from the current year.</li><li>Display the result.</li></ol><p>This simple example demonstrates how different Python features can be combined to solve a practical problem.</p><h3>8. JSON: Moving Structured Data Between Systems</h3><p>Modern applications constantly exchange data.</p><p>One common format used for this is <strong>JSON — JavaScript Object Notation</strong>.</p><p>JSON represents structured information using objects, arrays, strings, numbers, booleans, and other supported data types.</p><p>For example:</p><pre>{<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;grade&quot;: &quot;A&quot;<br>}</pre><p>Python provides the built-in json module for working with this format.</p><pre>import json</pre><h3>9. Converting Python Objects to JSON</h3><p>Suppose we have a Python dictionary:</p><pre>student = {<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;grade&quot;: &quot;A&quot;<br>}</pre><pre>We can convert it into a JSON string using json.dumps():</pre><pre>import json</pre><pre>student = {<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;grade&quot;: &quot;A&quot;<br>}</pre><pre>json_data = json.dumps(student)</pre><pre>print(json_data)</pre><p>The important concept here is <strong>serialization</strong>.</p><p>We are taking a Python object and converting it into a JSON representation that can be stored or transmitted.</p><h3>10. Converting JSON Back into Python</h3><p>The reverse process is called <strong>deserialization</strong>.</p><p>Suppose we receive this JSON:</p><pre>json_data = &#39;{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 25, &quot;grade&quot;: &quot;A&quot;}&#39;</pre><p>We can convert it into a Python object:</p><pre>import json</pre><pre>student = json.loads(json_data)</pre><pre>print(student)</pre><p>The four JSON functions worth understanding are:</p><p>json.dumps()Python object → JSON string</p><p>json.loads()JSON string → Python object</p><p>json.dump()Python object → JSON file</p><p>json.load()JSON file → Python object</p><p>That distinction becomes especially important when working with JSON files.</p><h3>11. Reading and Writing JSON Files</h3><p>Consider a list of student records:</p><pre>students = [<br>    {<br>        &quot;name&quot;: &quot;John&quot;,<br>        &quot;age&quot;: 20,<br>        &quot;grade&quot;: &quot;A&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Mary&quot;,<br>        &quot;age&quot;: 21,<br>        &quot;grade&quot;: &quot;B&quot;<br>    }<br>]</pre><p>We can store this information in a JSON file:</p><pre>import json</pre><pre>with open(&quot;students.json&quot;, &quot;w&quot;) as file:<br>    json.dump(students, file, indent=4)</pre><p>The data can later be retrieved:</p><pre>with open(&quot;students.json&quot;, &quot;r&quot;) as file:<br>    students = json.load(file)</pre><pre>print(students)</pre><p>This creates a simple persistence mechanism where structured data can survive after the Python program has stopped running.</p><p>However, the JSON must be valid. If the file contains malformed JSON, attempting to load it can result in a JSON parsing exception.</p><h3>12. User Input and the Problem of Unexpected Data</h3><p>User input is another area where Python programs need to be careful.</p><p>Consider:</p><pre>number = int(input(&quot;Enter a number: &quot;))</pre><p>We expect the user to enter something such as:</p><pre>25</pre><p>But what happens if they enter:</p><pre>hello</pre><p>Python cannot convert &quot;hello&quot; into an integer, so an exception occurs.</p><p>This is where <strong>exception handling</strong> becomes important.</p><h3>13. Handling Exceptions with try and except</h3><p>Python provides try and except for handling situations where an operation may fail.</p><p>For example:</p><pre>try:<br>    number = int(input(&quot;Enter a number: &quot;))<br>    print(100 / number)</pre><pre>except ValueError:<br>    print(&quot;Please enter a valid number.&quot;)</pre><pre>except ZeroDivisionError:<br>    print(&quot;You cannot divide by zero.&quot;)</pre><p>There are two different problems being handled.</p><h3>Invalid input</h3><p>If the user enters:</p><pre>ab</pre><p>Python raises a ValueError because the string cannot be converted to an integer.</p><h3>Division by zero</h3><p>If the user enters:</p><pre>0</pre><p>the conversion succeeds, but:</p><pre>100 / 0</pre><p>produces a ZeroDivisionError.</p><p>Handling these exceptions allows the program to respond appropriately instead of terminating unexpectedly.</p><h3>14. Exception Handling Is About Control</h3><p>A useful way to think about try/except is that it gives the programmer control over predictable failure situations.</p><p>For example:</p><pre>try:<br>    age = int(input(&quot;Enter your age: &quot;))<br>except ValueError:<br>    print(&quot;The age must be an integer.&quot;)</pre><p>The program is not assuming that every input will be correct.</p><p>Instead, it establishes a rule:</p><p><em>If this operation fails in a known way, handle that failure here.</em></p><p>This principle becomes increasingly important as programs interact with users,files, APIs, databases, and external systems.</p><h3>15. pip: Managing Python Packages</h3><p>Python’s built in modules provide a lot of functionality, but Python also has a huge ecosystem of external packages.</p><p>pip is used to install Python packages.</p><p>For example:</p><pre>pip install numpy</pre><p>We can also install a specific version:</p><pre>pip install numpy==1.26.4</pre><p>To see installed packages:</p><pre>pip list</pre><p>This becomes important when a project depends on packages that are not included in Python’s standard library.</p><h3>16. Why Virtual Environments Matter</h3><p>Imagine working on two Python projects.</p><p>Project A requires one version of a package:</p><pre>Package X → version 1</pre><p>Project B requires another:</p><pre>Package X → version 2</pre><p>Installing everything globally can create dependency conflicts.</p><p>A <strong>virtual environment</strong> solves this by creating an isolated environment for a project.</p><p>We can create one using:</p><pre>python -m venv myenv</pre><p>On Windows, it can be activated with:</p><pre>myenv\Scripts\activate</pre><p>On macOS/Linux:</p><pre>source myenv/bin/activate</pre><p>Once activated, packages installed with pip belong to that environment.</p><p>For example:</p><pre>pip install numpy</pre><p>We can then verify the installation:</p><pre>pip list</pre><p>This makes each project more self-contained and easier to manage.</p><p>Learning Python is not simply about memorizing syntax. It is about understanding how different components of the language help us build programs that can <strong>process information, interact with users, handle errors, manage data, and use external functionality</strong>.</p><p>Modules give us reusable functionality.</p><p>datetime allows us to work with dates and times.</p><p>math provides mathematical operations and constants.</p><p>JSON gives us a structured format for storing and exchanging data.</p><p>Exception handling helps programs respond to unexpected situations.</p><p>pip allows us to install additional Python packages.</p><p>Virtual environments allow us to isolate those dependencies between projects.</p><p>These concepts may seem like separate pieces when learning them individually, but together they represent an important transition from <strong>writing simple Python statements to building practical Python applications</strong>.</p><p>And that is one of the most important stages in learning Python: understanding not just <em>what</em> a feature does, but <strong>why it exists and where it fits into a real software development workflow</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9878e0fe71e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Python Classes to a Library Management System: My Journey into Object-Oriented Programming.]]></title>
            <link>https://medium.com/@ronphreylucky/from-python-classes-to-a-library-management-system-my-journey-into-object-oriented-programming-bee6d27dc430?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bee6d27dc430</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 08:26:30 GMT</pubDate>
            <atom:updated>2026-09-20T08:26:30.506Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning Python, I thought Object-Oriented Programming (OOP) was mostly about creating classes and objects.</p><p>I was wrong.</p><p>The more I practiced, the more I realized that OOP is really about learning how to structure code around <strong>objects, relationships, behavior, and responsibilities</strong>.</p><p>During my recent Python OOP coursework, I worked through several concepts including classes and objects, inheritance, method overriding, polymorphism, iterators, variable scope, super(), and Method Resolution Order (MRO).</p><p>The most interesting part was seeing these concepts move from isolated examples into a small <strong>Library Management System</strong>.</p><p>This article documents what I learned and, more importantly, how my understanding evolved while implementing the concepts.</p><h3>Starting with Classes and Objects</h3><p>The first concept I worked with was the foundation of OOP: <strong>classes and objects</strong>.</p><p>A class can be thought of as a blueprint, while an object is an actual instance created from that blueprint.</p><p>For example:</p><pre>class Car:<br>    def __init__(self, brand, model):<br>        self.brand = brand<br>        self.model = model<br><br>    def display_details(self):<br>        return f&quot;Brand: {self.brand}, Model: {self.model}&quot;</pre><p>I can then create objects from the class:</p><pre>car1 = Car(&quot;Toyota&quot;, &quot;Corolla&quot;)<br>car2 = Car(&quot;Tesla&quot;, &quot;Model 3&quot;)<br><br>print(car1.display_details())<br>print(car2.display_details())</pre><p>Although both objects come from the same class, they contain different data.</p><p>This helped me understand an important distinction:</p><p><em>A class defines what an object can have and do, while an object contains the actual values.</em></p><p>I also learned about the __init__() method, which is automatically called when an object is created.</p><p>For example:</p><pre>p1 = Person(&quot;John&quot;, 36)</pre><p>Python calls:</p><pre>__init__(self, &quot;John&quot;, 36)</pre><p>This is where attributes such as name and age are initialized.</p><h3>Understanding self</h3><p>One of the concepts that initially required some thought was self.</p><p>Consider:</p><pre>class Car:<br>    def __init__(self, brand, model):<br>        self.brand = brand<br>        self.model = model</pre><p>When I create:</p><pre>car1 = Car(&quot;Toyota&quot;, &quot;Corolla&quot;)</pre><p>self refers to car1.</p><p>So:</p><pre>self.brand = brand</pre><p>effectively means:</p><pre>car1.brand = &quot;Toyota&quot;</pre><p>This made the relationship between an object and its attributes much clearer to me.</p><p>The same idea applies to methods:</p><pre>car1.display_details()</pre><p>Python knows that the method should operate on car1.</p><h3>The __str__() Method.</h3><p>Another interesting concept was the __str__() dunder method.</p><p>Without a custom __str__() method, printing an object doesn&#39;t normally give a useful human-readable representation.</p><p>I created:</p><pre>class Name:<br>    name = &quot;Lucky&quot;</pre><pre>    def __str__(self):<br>        return &quot;My name is Lucky&quot;</pre><p>Now:</p><pre>person = Name()<br>print(person)</pre><p>produces:</p><pre>My name is Lucky</pre><p>This helped me understand that Python’s double-underscore methods, commonly called <strong>dunder methods</strong>, allow us to define how objects behave with built-in Python operations.</p><h3>Inheritance: Reusing Existing Code</h3><p>After understanding classes, I moved into inheritance.</p><p>Inheritance allows a child class to reuse attributes and methods from a parent class.</p><p>For example:</p><pre>class Animal:<br>    def speak(self):<br>        return &quot;Animals make unique sounds&quot;<br></pre><pre>class Dog(Animal):<br>    def speak(self):<br>        return &quot;Woof!&quot;</pre><p>Dog inherits from Animal, but it provides its own implementation of speak().</p><p>This introduced me to <strong>method overriding</strong>.</p><p>The parent class says:</p><pre>speak()</pre><p>but the child class changes what that method does.</p><p>This became even clearer when I created multiple levels of inheritance:</p><pre>class LivingBeing:<br>    def __init__(self):<br>        self.is_alive = True<br></pre><pre>class Animal(LivingBeing):<br>    def speak(self):<br>        return &quot;All animals speak&quot;<br></pre><pre>class Bird(Animal):<br>    def fly(self):<br>        return &quot;A bird flies&quot;</pre><p>A Bird object can access:</p><pre>Bird1.is_alive<br>Bird1.speak()<br>Bird1.fly()</pre><p>even though is_alive was defined in LivingBeing and speak() was defined in Animal.</p><p>That was one of the moments where inheritance became much more intuitive.</p><h3>super(): Connecting Parent and Child Classes</h3><p>Inheritance also introduced me to super().</p><p>Consider:</p><pre>class Vehicle:<br>    def __init__(self, brand, model):<br>        self.brand = brand<br>        self.model = model<br></pre><pre>class Car(Vehicle):<br>    def __init__(self, brand, model, doors):<br>        super().__init__(brand, model)<br>        self.doors = doors</pre><p>The Car class does not need to rewrite:</p><pre>self.brand = brand<br>self.model = model</pre><p>Instead:</p><pre>super().__init__(brand, model)</pre><p>calls the parent class’s initialization method.</p><p>This is especially useful when classes become more complex.</p><h4>Polymorphism: Same Interface, Different Behavior</h4><p>One of the most interesting OOP concepts I encountered was <strong>polymorphism</strong>.</p><p>The basic idea is that different objects can respond to the same method in different ways.</p><p>For example:</p><pre>class Car:<br>    def move(self):<br>        return &quot;Car drives&quot;<br></pre><pre>class Bicycle:<br>    def move(self):<br>        return &quot;Bicycle pedals&quot;</pre><p>I can place both objects in one list:</p><pre>objects = [Car(), Bicycle()]</pre><p>and simply do:</p><pre>for obj in objects:<br>    print(obj.move())</pre><p>The loop doesn’t need to know whether obj is a Car or a Bicycle.</p><p>Each object knows how to implement move().</p><p>This idea also helped me understand why Python’s built-in len() works with different data types.</p><p>For example:</p><pre>a_string = &quot;my name is lucky&quot;<br>a_list = [1, 2, 4, 5, 7]<br>a_dictionary = {&quot;name&quot;: &quot;lucky&quot;}</pre><pre>print(len(a_string))<br>print(len(a_list))<br>print(len(a_dictionary))</pre><p>The same function is used, but Python knows how to determine the length of each type.</p><h3>Polymorphism Without Checking Object Types</h3><p>I also implemented polymorphism using shapes.</p><p>Instead of checking:</p><pre>if object is a Rectangle:</pre><p>or:</p><pre>if object is a Circle:</pre><p>I could simply call:</p><pre>shape.area()</pre><p>For example:</p><pre>shapes = [<br>    Rectangle(4, 5),<br>    Circle(3),<br>    Triangle(6, 8)<br>]</pre><pre>total_area = 0</pre><pre>for shape in shapes:<br>    total_area += shape.area()</pre><p>The loop doesn’t care what type of shape it receives.</p><p>As long as the object provides an area() method, the operation works.</p><p>This was a practical demonstration of one of the most useful ideas in Python:</p><p><em>Focus on what an object can do rather than what type of object it is.</em></p><h3>Iterators: Understanding __iter__() and __next__()</h3><p>Another major part of the coursework was iterators.</p><p>Before this exercise, I was comfortable using:</p><pre>for number in numbers:<br>    print(number)</pre><p>But I wanted to understand what was happening underneath.</p><p>A custom iterator normally implements two methods:</p><pre>__iter__()<br>__next__()</pre><p>For example:</p><pre>class CountDown:<br>    def __init__(self, n):<br>        self.n = n</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        if self.n &lt;= 0:<br>            raise StopIteration</pre><pre>        current = self.n<br>        self.n -= 1</pre><pre>        return current</pre><p>Now I can write:</p><pre>for number in CountDown(5):<br>    print(number)</pre><p>and get:</p><pre>5<br>4<br>3<br>2<br>1</pre><p>The important part was understanding StopIteration.</p><p>When there are no more values to return, the iterator raises:</p><pre>StopIteration</pre><p>Python’s for loop understands this signal and stops automatically.</p><h3>Building an Infinite Iterator</h3><p>I also created an iterator that generates even numbers:</p><pre>class EvenNumbers:<br>    def __init__(self):<br>        self.current = 2</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        value = self.current<br>        self.current += 2<br>        return value</pre><p>This iterator doesn’t naturally stop.</p><p>Therefore, I controlled the loop with a counter:</p><pre>even_numbers = EvenNumbers()<br>count = 0</pre><pre>for number in even_numbers:<br>    print(number)</pre><pre>    count += 1</pre><pre>    if count == 10:<br>        break</pre><p>This was useful because it showed me that an iterator doesn’t necessarily need to represent a finite collection.</p><p>It can generate values continuously until the program decides to stop.</p><h3>Scope: Local, Global and Nonlocal Variables</h3><p>Another area I explored was variable scope.</p><p>I learned that a variable created inside a function is normally local to that function.</p><p>For example:</p><pre>count = 10</pre><pre>def increment():<br>    count = 5<br>    print(count)</pre><pre>increment()</pre><pre>print(count)</pre><p>The count inside the function is different from the global count.</p><p>I then learned about the global keyword.</p><pre>total = 0</pre><pre>def add_to_total(n):<br>    global total<br>    total += n</pre><p>This allows the function to modify the global variable.</p><p>I also learned about nonlocal, which is useful with nested functions:</p><pre>def outer():<br>    message = &quot;Hi&quot;</pre><pre>    def inner():<br>        nonlocal message<br>        message = &quot;Hi, updated from inner!&quot;</pre><pre>    inner()<br>    print(message)</pre><p>The nonlocal keyword allows the nested function to modify a variable belonging to its enclosing function.</p><h3>A Small but Important Lesson: Shadowing</h3><p>One exercise gave me a practical lesson about Python’s built-in functions.</p><p>Consider:</p><pre>def show_len_behavior():<br>    numbers = [1, 2, 3, 4, 5]</pre><pre>    print(len(numbers))</pre><pre>    len = 100</pre><pre>    print(len(numbers))</pre><p>The second call fails because the local variable:</p><pre>len = 100</pre><p>shadows the built-in len() function within that scope.</p><p>This was a good reminder that variable names matter.</p><p>Creating variables with names such as:</p><pre>len<br>list<br>str<br>sum</pre><p>can unintentionally hide Python’s built-in functionality.</p><h3>Multiple Inheritance and MRO</h3><p>I also explored multiple inheritance.</p><p>For example:</p><pre>class Flyer:<br>    def move(self):<br>        return &quot;Flying&quot;<br></pre><pre>class Swimmer:<br>    def move(self):<br>        return &quot;Swimming&quot;<br></pre><pre>class Duck(Flyer, Swimmer):<br>    def move(self):<br>        return super().move()</pre><p>Here, Duck inherits from both Flyer and Swimmer.</p><p>But both parent classes contain a method called move().</p><p>So which one does Python use?</p><p>This is where <strong>Method Resolution Order (MRO)</strong> becomes important.</p><p>Python follows a specific order when searching for a method or attribute.</p><p>For:</p><pre>class Duck(Flyer, Swimmer):</pre><p>Python checks the relevant inheritance chain according to the class’s MRO.</p><p>This prevents Python from randomly choosing between methods when multiple inheritance is involved.</p><h3>Bringing Everything Together: A Library Management System</h3><p>The final and most practical part of the coursework was designing a Library Management System.</p><p>This was where many of the individual concepts started coming together.</p><p>The system was designed around books, members, borrowing operations, inheritance, polymorphism, iterators, scope, and class variables.</p><p>I created a base Book class:</p><pre>class Book:<br>    def __init__(self, title, author, year):<br>        self.title = title<br>        self.author = author<br>        self.year = year<br>        self.is_borrowed = False</pre><pre>    def get_description(self):<br>        return f&quot;{self.title} by {self.author} released in {self.year}&quot;</pre><p>Then I created specialized book types:</p><pre>class EBook(Book):<br>    ...</pre><p>and:</p><pre>class PrintedBook(Book):<br>    ...</pre><p>Both inherit from Book, but they can provide their own implementation of get_description().</p><p>This is inheritance combined with polymorphism.</p><h3>Different Members, Different Borrowing Rules</h3><p>I also created a member hierarchy.</p><p>A general member can borrow books, while specialized members have different limits.</p><p>For example:</p><pre>class StudentMember(member):<br>    def __init__(self, name, member_id, grade_level):<br>        super().__init__(name, member_id)<br>        self.grade_level = grade_level<br>        self.borrow_limit = 2</pre><p>while a teacher can have a different limit:</p><pre>class TeacherMember(member):<br>    def __init__(self, name, member_id, department):<br>        super().__init__(name, member_id)<br>        self.department = department<br>        self.borrow_limit = 5</pre><p>The same borrow_book() concept can therefore behave differently depending on the type of member.</p><h4>Encapsulation and Protected Attributes.</h4><p>The project also introduced me to encapsulation.</p><p>The member’s borrowed books were stored using:</p><pre>self._borrowed_books = []</pre><p>The single underscore communicates that this is intended to be treated as a protected attribute.</p><p>The library name, on the other hand, was represented using:</p><pre>self.__library_name = library_name</pre><p>The double underscore triggers Python’s name mangling behavior and provides stronger protection against direct access.</p><p>This helped me understand that encapsulation isn’t simply about hiding data. It is about controlling how different parts of a program interact with an object’s internal state.</p><p>The biggest lesson from this exercise wasn’t memorizing Python syntax.</p><p>It was learning to think about <strong>relationships between objects</strong>.</p><p>At the beginning, concepts such as inheritance, polymorphism, iterators, scope, and MRO felt like separate topics.</p><p>After implementing them repeatedly, I started seeing how they connect.</p><p>For example:</p><p><strong>Inheritance</strong> allows a class to reuse behavior.</p><p><strong>Method overriding</strong> allows a child class to provide specialized behavior.</p><p><strong>Polymorphism</strong> allows different objects to be used through a common interface.</p><p><strong>Iterators</strong> allow objects to control how their values are accessed sequentially.</p><p><strong>Encapsulation</strong> helps control access to an object’s internal state.</p><p><strong>Scope</strong> determines where variables can be accessed and modified.</p><p>And <strong>MRO</strong> determines how Python resolves attributes and methods through an inheritance hierarchy.</p><p>The Library Management System brought several of these ideas together in one application.</p><h3>Final Thoughts</h3><p>This assignment changed my understanding of OOP from something that looked like a collection of Python rules into a way of thinking about software.</p><p>I started with simple questions such as:</p><p><em>What is a class?</em></p><p>Then moved into:</p><p><em>How does an object inherit behavior?</em></p><p>Then:</p><p><em>How can different objects respond to the same method?</em></p><p>And eventually:</p><p><em>How can I combine these concepts to build an actual system?</em></p><p>That progression was probably the most valuable part of the exercise.</p><p>I’m still learning, and there are areas I want to improve especially designing larger class hierarchies, writing cleaner abstractions, handling resources safely, and building more complete real-world applications.</p><p>But one thing has become much clearer:</p><p><strong>Learning OOP isn’t just about learning how to write classes. It’s about learning how to make different parts of a program work together.</strong></p><p>And this project was a good step in that direction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bee6d27dc430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Python Crash Course: From “Hello World” to FizzBuzz.]]></title>
            <link>https://medium.com/@ronphreylucky/my-python-crash-course-from-hello-world-to-fizzbuzz-0bd9f598ce00?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd9f598ce00</guid>
            <category><![CDATA[beginner-friendly]]></category>
            <category><![CDATA[python-crash-course]]></category>
            <category><![CDATA[number-guessing-game]]></category>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 15:58:50 GMT</pubDate>
            <atom:updated>2026-09-05T15:58:50.555Z</atom:updated>
            <content:encoded><![CDATA[<p>I just wrapped up my first week of practice with Python, and I wanted to document the journey ,not just for myself but for anyone else starting out and wondering what a beginner’s first real week with the language actually looks like. The brief was simple but firm: work through a set of Tasks, Assignments, and Assessments, and no shortcuts with AI. Everything below is code I wrote, tested, and in a few cases, had to go back and fix.</p><h3>Starting With the Basics</h3><p>Every Python journey starts the same way, printing something to the screen. My first program greeted the world, and my second one took it further by asking for a name and an age and stitching them into a personalized message using an f-string:</p><pre>name = input(&#39;What is your name? &#39;)<br>age = input(&#39;What is your age? &#39;)<br>print(f&#39;Hello {name}, you are {age} years old!&#39;)</pre><p>From there, the tasks moved quickly into core building blocks: checking whether a number is even or odd using the modulo operator, printing a multiplication table with a for loop, and calculating a factorial by multiplying downward from a starting number. Each of these felt small on its own, but together they built the muscle memory for reading and manipulating numbers.</p><p>One task that took a bit more thought was finding the largest number in a list without using Python’s built in max(). The idea is to start by assuming the first item is the largest, then walk through the rest of the list comparing each item against your current &quot;champion,&quot; replacing it whenever you find something bigger. It&#39;s a simple pattern, but it&#39;s the foundation for a lot of searching and sorting logic you&#39;ll meet later.</p><pre>numbers = [2, 5, 19, 10, 67]<br>largest_number = numbers[0]<br>for num in numbers:<br>    if num &gt; largest_number:<br>        largest_number = num<br>print(&#39;The largest number on your list is&#39;, largest_number)</pre><p>I also worked through counting vowels in a sentence, writing a function that returns a sum, difference, and product for two numbers as a tuple, reversing a string manually with a loop (instead of Python’s [::-1] shortcut), and generating the first ten Fibonacci numbers. That last one turned out to be one of my favorites starting with a two item list and repeatedly appending the sum of the last two entries until you hit the length you want:</p><pre>fib = [0, 1]<br>while len(fib) &lt; 10:<br>    next_number = fib[-1] + fib[-2]<br>    fib.append(next_number)<br>print(fib)</pre><h3>Leveling Up With Assignments</h3><p>The assignments section is where things got more realistic less “exercise,” more “small program someone might actually use.”</p><p><strong>The Student Grades System</strong> asked me to collect scores across five subjects, average them, and assign a letter grade. I stored the subjects in a dictionary, pulled the values into a list, averaged them, and passed the result through a helper function that mapped score ranges to grades (A, B, C, or F).</p><p><strong>The Simple Calculator</strong> is where I ran into my first real bug, and it taught me a lesson about case sensitivity. My initial version validated user input against [&#39;Add&#39;,&#39;Sub&#39;,&#39;Mul&#39;,&#39;Div&#39;], but I was also lowercasing the input with .lower() meaning the comparison could never match. The fix was validating against lowercase strings throughout, and restructuring the function so it actually took num1 and num2 as arguments instead of calling helper functions with no parameters at all (which, unsurprisingly, threw errors).</p><pre>num1 = int(input(&#39;Enter the first number: &#39;))<br>sign = input(&#39;Please enter the sign, either add, sub, mul or div: &#39;).lower()<br>while sign not in [&#39;add&#39;, &#39;sub&#39;, &#39;mul&#39;, &#39;div&#39;]:<br>    sign = input(&#39;Please enter the sign, either add, sub, mul or div: &#39;).lower()<br>num2 = int(input(&#39;Enter the second number: &#39;))<br><br>print(f&#39;The result is: {calculator(sign, num1, num2)}&#39;)</pre><p><strong>The Shopping Cart</strong> exercise pushed me to think about input validation more seriously. My first draft tried to check if a price was a valid float using price is not float, which doesn&#39;t actually validate anything is checks whether two objects are literally the same thing in memory, not whether a string can be converted to a number. The correct approach was wrapping the conversion in a try/except ValueError block and looping until the user gave valid input:</p><pre>while True:<br>    price_input = input(f&quot;Enter the price of {item}: &quot;)<br>    try:<br>        price = float(price_input)<br>        break<br>    except ValueError:<br>        print(&quot;That&#39;s not a valid number, please try again.&quot;)</pre><p><strong>The Guessing Game</strong> had me build a number-guessing loop where the program picks a random number and gives “too high” / “too low” feedback until the user gets it right, then asks if they’d like to play again. This is the assignment that most resembled a “real” program it had state, user interaction, and a replay loop.</p><p><strong>File Handling</strong> rounded out the assignments by having me collect a list of student names, write them to a text file, and then read that file back and print its contents my first taste of Python’s open() and the with statement for managing files safely.</p><h3>Testing My Understanding: The Assessments</h3><p>The last section was fifteen short-answer and coding questions meant to check whether the concepts had actually stuck. A few highlights:</p><ul><li><strong>Lists vs. tuples</strong>: a list can be changed after creation; a tuple can’t. Lists use [], tuples use ().</li><li><strong>if __name__ == &quot;__main__&quot;:</strong>: this line makes sure a block of code only runs when the file is executed directly, not when it&#39;s imported as a module elsewhere.</li><li><strong>Swapping variables without a third one</strong>: Python makes this trivial with a, b = b, a.</li><li><strong>== vs. </strong><strong>is</strong>: == checks if two values are equal; is checks if two variables point to the exact same object in memory. This distinction came back to bite me earlier in the shopping cart exercise, so it was good to nail down explicitly.</li><li><strong>FizzBuzz</strong>: the classic loop from 1 to whatever limit, print “Fizz” for multiples of 3, “Buzz” for multiples of 5, and “FizzBuzz” for multiples of both.</li><li><strong>Local vs. global variables</strong>: a local variable only exists inside the function it’s defined in; a global variable is accessible throughout the whole program.</li><li><strong>Filtering even numbers</strong>, <strong>finding the second-largest number in a list</strong> (a one liner once you sort it), counting words in a sentence using .split(), and checking for palindromes with a simple string reversal comparison rounded out the rest.</li></ul><h3>What I Took Away From Week 1</h3><p>Looking back at the whole set, a pattern emerges: almost every meaningful bug I hit came from one of two things comparing values incorrectly (case sensitivity, is vs. ==) or not validating user input before trying to use it. Those aren&#39;t exotic mistakes; they&#39;re the same ones every beginner runs into, which is oddly reassuring. Getting comfortable catching and fixing them is arguably a bigger skill than memorizing syntax.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd9f598ce00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Understanding of Logistic Regression and Multi-Class Prediction.]]></title>
            <link>https://medium.com/@ronphreylucky/a-comprehensive-understanding-of-logistic-regression-and-multi-class-prediction-fb312ba8a5f8?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb312ba8a5f8</guid>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 06:54:53 GMT</pubDate>
            <atom:updated>2025-12-05T06:54:53.132Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction.</strong></li></ol><p>Logistic Regression is a statistical and machine learning technique used for binary ,where the goal is to predict one of two or more possible outcomes(e.g fraud vs not fraud,spam vs not spam).Unlike Linear Regression, which predicts continuous values,Logistics Regression estimates the probability of an event coccuring.</p><p>Logistic Regression was originally designed for binary classification(0 or 1) But in real problems, you may have 3,4 or more classes.To solve this,Logistic regression uses two main strategies:</p><ol><li><strong>One-vs-Rest(OVR) method also called One vs all method.</strong></li></ol><p>This method creates one Logistic regressio model per class.</p><p>How it works</p><p>If you have 3 classes: class 1,2 and 3</p><p>OVR will create:</p><p>Model 1:A vs (B+C)</p><p>Model 2: B vs (A+C)</p><p>Model 3: C vs(A+B)</p><p>Each Model is Binary.It gives a probability:</p><p>P(A|x) from model 1</p><p>P(B|x) from model 2</p><p>P(C|x) from model 3.</p><p>Then Logistic Regression chooses the class with the highest probability.</p><p>How prediction works in OVR.</p><p>Let’s say after running all 3 models, you get:</p><p>Class Probability A 0.32 B 0.55 C 0.27</p><p>The Model predicts: Class B cause it has the highest probability.</p><p>Advantages include Simple to understand,Works with any binary classifier,efficient when class are not too many etc.</p><p>Disadvantages include Creates many models,more computation,Each model is trained independently etc.</p><p>2.<strong>SOFTMAX(Multinomial Logistics Regression).</strong></p><p>Softmax -&gt; a single model that handles all classes together.</p><p>Instead of building multiple binary models, multinomial logistics regression builds one model that computes a score for each class,then converts all scores into probabilities using softmax.</p><ul><li>Each class has a score representing the model’s confidence for that class.</li><li>Softmax exponentiates these scores and divides by the sum of all exponentiated scores, producing a probability distribution across all classes.</li></ul><p>This approach ensures that higher scores correspond to higher probabilities and all probabilities are interpretable in a consistent way. The predicted class is the one with the highest probability, but unlike OvR, Softmax naturally accounts for the relative differences between all classes.</p><h3>2. Mathematical Foundation</h3><h3>2.1 Linear Combination</h3><p>Logistic Regression starts with a linear model:</p><p>z=w0​+w1​x1​+w2​x2​+⋯+wn​xn​</p><p>where</p><ul><li>xi​ = input features</li><li>wi​ = model weights</li><li>w0​ = bias (intercept)</li></ul><h3>2.2 Sigmoid (Logistic) Function</h3><p>The linear output z is passed through a sigmoid function:</p><p>σ(z)=1+e−z1​</p><p>This converts any real number into a probability between 0 and 1.</p><h3>2.3 Output Interpretation</h3><p>P(y=1∣x)=σ(z)</p><p>Classification rule:</p><p>y^​={1 ​if P≥0.5 otherwise​ 0.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb312ba8a5f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DETAILED MAREKTING INSIGHT REPORT]]></title>
            <link>https://medium.com/@ronphreylucky/detailed-marekting-insight-report-ef0fd4dfa4bf?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef0fd4dfa4bf</guid>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 07:19:14 GMT</pubDate>
            <atom:updated>2025-01-30T07:21:07.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>MAREKTING INSIGHT REPORT</h4><p>Title : Superstore Sales Analysis.</p><p>Tools used:Python(pandas,Matplotlib),JupyterNotebook.</p><p><strong>1.INTRODUCTION.</strong></p><p>This report analyzes the <a href="https://www.kaggle.com/datasets/bravehart101/sample-supermarket-dataset">Sample Supermarket Dataset</a> ,containing 9,994 transactions across 3 product categories(office supplies,Furniture,Technology).The analyis focuses on identfying opportunities to optimize marketing strategies and resource allocation.For more about data-driven training programs, visit <a href="https://hng.tech/internship">HNG internship</a>.</p><p><strong>2.KEY OBSERVATIONS.</strong></p><p>2.1 Product Category Performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*AOIYm8EnTz9eGoxXGvy1GA.png" /></figure><p>Sales Leadership:</p><blockquote>Technology: $836,154.0330(Highest Volume)</blockquote><blockquote>Office Supplies: $71,9047.0320(lowest Volume)</blockquote><p>Profitability:</p><pre>==== Category Profit Margins ====<br>Technology: 17.4%<br>Furniture: 2.5%<br>Office Supplies: 17.0%</pre><p>INSIGHT:while Furniture drives less volume than office supplies, office supplies products deliver superior profitability.A little shift in marketing focus to office supplies could improve ROI.</p><p>2.2 Regional Disparities:</p><pre>==== regional Profit Margins ====<br>West: 14.9%<br>East: 13.5%<br>Central: 7.9%<br>South: 11.9%</pre><blockquote>Top Performer:</blockquote><blockquote>West Region: $72,5457.8245 in sales and $108,418.4489 in profit.</blockquote><blockquote>Underperformer:</blockquote><blockquote>Central Region: $50,1239.8908 in sales and $39,706.3625 in profit.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*6FOo3L5VZXAuLH190Uu-sQ.png" /></figure><p>3.Technical Findings</p><p>Data Quality: No missing values detectedespecially in the key columns (Sales,Profit and Category) and every column was given in the right data type.</p><p>Anomaly: Furniture category shows low profit margin(2.5%) compared to other categories.</p><p>Conclusion</p><ol><li>Consider reallocation of furniture supplies and budget to office supplies.</li><li>Regional audits for Central Region Operations.</li></ol><p>For business needing experts analysis to implement such strategies, explore <a href="https://hng.tech/hire/data-analysts">HNG Hire</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef0fd4dfa4bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Report on Geospatial Analysis and Outlier Detection]]></title>
            <link>https://medium.com/@ronphreylucky/report-on-geospatial-analysis-and-outlier-detection-f5f174cd774e?source=rss-926787b5dd8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5f174cd774e</guid>
            <dc:creator><![CDATA[Ronphreylucky]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 20:14:20 GMT</pubDate>
            <atom:updated>2024-07-04T20:14:20.528Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Dataset Preparation:</strong></p><ul><li>We used goe-code by awesome table in google sheet to derive the latitude and longitude for each wards.</li></ul><p><strong>Neighbour ward Identification:</strong></p><ul><li><strong>Geodesic Distance Calculation:</strong> I used geodesic distance to calculate the distance between each polling unit and all other units.</li><li><strong>Spatial Clustering</strong>: I used BALLTREE from sklearn with a distance of 1km to group polling units into clusters based on geographical proximity.</li></ul><p><strong>Outlier Detection</strong>:</p><ul><li><strong>Statistical Measures Calculation</strong>: For each cluster, I calculated the mean, median, and standard deviation of vote counts for each party.</li><li><strong>Outlier Identification</strong>: I Used Z-score (with a threshold of ±3) or IQR method (1.5 times IQR above the third quartile or below the first quartile) to identify outliers in vote counts.</li><li><strong>Outlier Score Assignment</strong>: I Assign scores to polling units based on the deviation of their vote counts from the cluster’s average.</li></ul><p><strong>Sorting and Reporting:</strong></p><ul><li><strong>Sorting by Outlier Scores:</strong> The dataset was sorted by the outlier scores for each party to identify the most significant outliers.</li><li><strong>Detailed Reporting:</strong> A detailed report was generated explaining the methodology and findings, highlighting the top 3 outliers and their closest polling units.</li></ul><p><strong>Sorted List of Polling Units by Outlier Scores:</strong></p><ul><li>The sorted list for each party includes polling units with the highest deviations in vote counts compared to their neighbours.</li></ul><p><strong>2.2 Top 3 Outliers for Each Party:</strong></p><ul><li><strong>Polling Unit ID: 12–08–04–007 (Party: LP)</strong></li><li><strong>Outlier Score:</strong> 572.36</li><li><strong>Neighbours:</strong> 12–08–04–012, 12–08–04–011, 12–08–04–010, 12–08–04–009, 12–08–04–008, 12–08–04–006, 12–08–04–005, 12–08–04–004, 12–08–04–003</li><li><strong>Polling Unit ID: 12–09–11–009 (Party: LP)</strong></li><li><strong>Outlier Score:</strong> 561.85</li><li><strong>Neighbours:</strong> 12–09–11–022, 12–09–11–018, 12–09–11–001, 12–09–11–021, 12–09–11–008</li><li><strong>Polling Unit ID: 12–09–05–001 (Party: LP)</strong></li><li><strong>Outlier Score:</strong> 556.00</li><li><strong>Neighbour:</strong> 12–09–05–040</li></ul><h3>3. Detailed Examples of Top 3 Outliers</h3><p><strong>3.1 Polling Unit ID: 12–08–04–007 (Party: LP)</strong></p><ul><li><strong>Votes Comparison:</strong></li><li><strong>Unit Votes:</strong> 1200</li><li><strong>Neighbour Average Votes:</strong> 627.64</li><li><strong>Explanation:</strong> This unit shows a significantly higher number of votes for the LP compared to its neighbours, indicating a possible anomaly.</li><li><strong>Visualization:</strong> A scatter plot highlighting this unit and its neighbours.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*cv_Aww1smmg5xh6v.png" /></figure><p><strong>3.2 Polling Unit ID: 12–09–11–009 (Party: LP)</strong></p><ul><li><strong>Votes Comparison:</strong></li><li><strong>Unit Votes:</strong> 1150</li><li><strong>Neighbour Average Votes:</strong> 588.15</li><li><strong>Explanation:</strong> This unit also shows a substantial deviation in votes for the LP, raising questions about the voting pattern.</li><li><strong>Visualization:</strong> A scatter plot highlighting this unit and its neighbours.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*eOux45gt81mtC3JN.png" /></figure><p><strong>3.3 Polling Unit ID: 12–09–05–001 (Party: LP)</strong></p><ul><li><strong>Votes Comparison:</strong></li><li><strong>Unit Votes:</strong> 1100</li><li><strong>Neighbour Average Votes:</strong> 544.00</li><li><strong>Explanation:</strong> The significant deviation in votes suggests this unit might be an outlier.</li><li><strong>Visualization:</strong> A scatter plot highlighting this unit and its neighbours.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*7iaIMpc0MH82w41E.png" /></figure><h3>Conclusion</h3><p><strong>Key Insights:</strong></p><ul><li>Significant outliers were identified, with some polling units showing substantially higher votes for certain parties compared to their neighbours.</li><li>The methodology effectively highlighted polling units that deviate from the norm, indicating potential areas for further investigation.</li></ul><p><strong>Visualizations:</strong></p><ul><li>Scatter plots provided clear visual evidence of outliers, making it easier to understand the deviations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*XVODmQLMCon42F_D.png" /></figure><p><strong>Future Recommendations:</strong></p><ul><li>Further investigation into the identified outliers to understand the reasons behind the significant deviations.</li><li>Use of more sophisticated statistical methods to enhance the outlier detection process.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5f174cd774e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>