<?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 simon kamande on Medium]]></title>
        <description><![CDATA[Stories by simon kamande on Medium]]></description>
        <link>https://medium.com/@kamandesimone?source=rss-494c015b13d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yH-GAAZXDRQo5J7lb7P-4w.jpeg</url>
            <title>Stories by simon kamande on Medium</title>
            <link>https://medium.com/@kamandesimone?source=rss-494c015b13d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamandesimone/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[DATABASE NORMALIZATION]]></title>
            <link>https://medium.com/@kamandesimone/database-normalization-f4024d6ff215?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4024d6ff215</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database-normalization]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-modeling]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 16:08:54 GMT</pubDate>
            <atom:updated>2024-02-27T16:08:54.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*MMwDdRNvgRmfK3p-tQFDLA.png" /></figure><p>This is a topic that you have probably heard of it and maybe you really dont know what it entails. well let me turn from a novice to a pro with this indepth article.This will be part <strong>one</strong> of how to handle data normalization in a database we will just be doing the overview of it and in <strong>part two</strong> i will actually be modelling our data to the tables that we are going to create in the following project ,from creating dimension tables to fact tables using C<strong>ommon Table Expressions CTE ‘s</strong> and with the help of <strong>ERD daigrams</strong> we will understand relationships between our tables ,and so part two of this project we will actully be implementing all this data normalization using <strong>DBT</strong> and we will be using<strong> snowflake</strong> to handle our data .Its a project you dont want to miss.</p><p><strong>What is data /data base normalization? </strong><em>Data normalization is the process of effectively designing a database effectively to avoid data redundancy,and to avoid anomalies</em>.</p><p>LEVELS OF DATA NORMALIZATION.</p><p>We have levels of data normalisation namely</p><ol><li>First Normal Form (1NF)</li><li>Second Normal Form(2NF)</li><li>Third Normal Form (3NF)</li></ol><p>We have upto 6 NF but for industries’ normal normalization it extends upto 3NF</p><p>We are going to visualize the steps that we will be undertaking using a dataset that we have downloaded from kaggle .Thus if we have an indentical data in an industry ,this would be an ideal way of normalizing the database for optimum perfomance.We will be highlighting some few columns of our data to fully understand our data.We will be using<strong> Excel</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWrsc2QFvoom-wQDS0SSNA.png" /><figcaption>original snippet of our whole data</figcaption></figure><p>we have the foloowing columns Row_id,Order_id,Order_date,Ship_date,Ship_mode,Customer_id,Customer_name,Segment,Country,City,State,Postal_code,Region,Product_id,Category,Sub_category,Product_name,Sales.</p><p><strong>FIRST NORMAL FORM (1NF)</strong></p><p>We have two rules that the 1NF follows</p><ol><li><em>Every column/attribute must have only a single value.</em></li><li><em>Each row should be unique,either through single or multiple columns not mandatory to have primary key.</em>In the above snippet we can see that our data has unique values and we can also fix this issue in excel where we can get rid of duplicates value.</li></ol><p><strong>SECOND NORMAL FORM (2NF)</strong></p><p>We also have two rules that we follow</p><ol><li><em>Our data must be in 1NF.Must have satisfied the 1NF for it to go through</em></li><li><em>All non key attributes must be fully dependent on candidate key</em> -Candidate key these are all sets of columns which uniquely identify a re cord. If a non key column has a partial dependency on candidate key we split them into separate tables.</li></ol><p>I can expound on the above guideline in the above table we have the order id and the order date means that the order_date column is fully dependent on the Order_id column.we also have the product _id and the city column,Means there is no/partial dependency on the columns meaning we have to split in to different columns .Thus in the below table the candidate keys includes ; Order_id,Customer_id and the product_id.</p><p>In regards to this we will split the data in the following ways ;</p><p><strong>Table 1</strong> will have order_id,Order_date,Ship_date,Ship_mode</p><p><strong>Table 2</strong> will have Customer_id,Customer_name,Segment, Country,City,State,Postal_code,Region</p><p><strong>Table 3</strong> will have Product_id,Category,Sub_category,Product_name,Sales.</p><p>3. <em>Every table should have a primary key and the relationship between tables should be formed using foreign keys.</em></p><p>We will be visualizing all these below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*z4_esOPxdgSjK_Zupwpn9g.png" /><figcaption>orders table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*7pxzJyRyXlutMko1cnXEvg.png" /><figcaption>customers table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*s9kHa3AYdDKHgJxJroVXLQ.png" /><figcaption>products table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*4M8xxECnt1QlLxQFqgpFdA.png" /><figcaption>defining relationships</figcaption></figure><p>Now this is how our database /datawarehouse should look like.We will be implementing CTE sql commands to create these tables using DBT .We will create an ERD diagram that expalains properly our data model and database.This is done for easier understanding to someone who is not conversant with tis field. We will move on to 3NF</p><p><strong>THIRD NORMAL FORM</strong></p><p>It follows the following rules</p><ol><li><em>Must be in 2NF FORM</em></li><li><em>Avoid Transitive Relationship</em> — lets say we have the table T and we have columns A,B and C .A is depedent on B and B is depedent on C,Then we can say A is transitively dependent on C .Thus we should avoid having this in the same table.As we can see in the above data above we can clearly see that we dont have transitive dependencies.</li></ol><p><strong>DIFFERENT ANOMALIES THAT WE OVERCOME</strong></p><ol><li><em>INSERTION ANOMALY</em> — We have if a customer makes different orders ,means the customerinformation becomes redundant while in other columns the data is changing.</li><li><em>DELETION ANOMALY </em>— If we have lets say an order is made and then canceled then we will only delete the data for the order table</li><li><em>UPDATE ANOMALY </em>— Lets say we are updating the price of an item we will just update a single row in the order table rather than updating all the rows that have that item.</li></ol><p><strong>ADVANTAGES OF NORMALIZATION OF A DATABASE.</strong></p><ol><li>Reduces data redundancy and inconsistency.</li><li>Makes writing to the database faster.</li><li>Speeds up Update,Insert and Delete</li><li>Maintains data integrity.</li><li>Able to make more joins</li><li>Optimizsed data storage saves on space.</li></ol><p>While some people may be not be using databases as often ,they have shifted to data warehousing in various cloud providers such as<strong> big query,</strong> <strong>Amazon redshift</strong> and <strong>snowflake</strong>.In this datawarehouses we now move to data modelling.Data modelling is done using dbt and in <strong>part two</strong> of this project i will be guiding on dbt and how we can create data models and later create visulizations in power bi.all in all data base and data normalization is a must tool for proefficeint data handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4024d6ff215" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WHY KENYAN MPS ARE NEVER RE-ELECTED]]></title>
            <link>https://medium.com/@kamandesimone/why-kenyan-mps-are-never-re-elected-a4230eb8a40b?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4230eb8a40b</guid>
            <category><![CDATA[power]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[corruption]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 08:10:37 GMT</pubDate>
            <atom:updated>2023-09-08T08:10:37.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDCpzPck0yJhkHOjwgPDbQ.jpeg" /></figure><p>Kenya’s political landscape has been raising eyebrows for some time now. Since 1988, the number of Members of Parliament (MPs) winning re-election has been on a steady decline. To understand the gravity of this situation, let’s consider the numbers. In 2013, only 42 percent of the 210 MPs from the previous term managed to secure re-election. To put it in context, let’s compare this to the 2017 and 2022 elections when we saw significantly different outcomes.</p><p>In 2017, out of the 290 MPs in Kenya’s Parliament, 124 were re-elected. This means about 43 percent of incumbents managed to keep their seats. However, the 2022 elections showed a slight improvement, with 144 MPs being re-elected. While this marked a boost, it still left around 50 percent of MPs losing their seats.</p><p>But what’s causing this downward trend in re-election rates? One theory gaining traction is that frequent changes in MPs may be hampering the development of their constituencies. In simpler terms, it’s like having a new manager at your favorite restaurant every month — they might have their own ideas, but they might not finish what the previous manager started. This article will dive into the numbers and reasons behind why Kenyan MPs are finding it increasingly tough to get re-elected and what this means for the nation’s future.;</p><p><strong>Gender</strong></p><p><strong>Age</strong></p><p><strong>region in the country</strong></p><p><strong>corruption allegations</strong></p><p><strong>perfomance in the constituency</strong></p><p><strong>shift of power in the national level</strong></p><p><strong>stronger competitors</strong></p><p>These are some of the factors that attribute to a change of mp every 5 years.</p><p><strong>Gender</strong></p><p>Politics in Kenya, like in many other places, has been largely dominated by men for a long time. It’s been tough for women to break through, but there have been some changes in recent years. Let’s look at the numbers to understand what’s happening.</p><p>In the 2013 general elections, there were only 16 female Members of Parliament (MPs) elected. Out of these, only 6 managed to win re-election in 2023. That’s just 37.5 percent.</p><p>Moving to the 2017 elections, there were 23 female MPs elected. But the big change came in 2022 when 29 women were elected as MPs. Out of these, 12 were re-elected in 2022, accounting for 52.1 percent.</p><p>This shows that even though female MPs face tough competition from their male counterparts, they are proving that they can win and get re-elected. However, it’s essential to note that these numbers are still quite small when you compare them.</p><p>In 2013, only 16 out of 290 MPs were women, which is about 5.5 percent. In 2017, it was slightly better with 23 out of 290, or 7.9 percent. And in 2022, we saw the highest number yet with 29 out of 290, which is about 10 percent.</p><p>So, even though progress is being made, there’s still a long way to go. Being a man in the recent elections gave you a 90 percent chance of winning over your female counterpart, which shows that gender bias in politics is still a significant issue that needs to be addressed.</p><p><strong>AGE</strong></p><p>Kenyan politics has seen a significant shift in the ages of its Members of Parliament (MPs) over the past four decades. Let’s take a closer look at the numbers.</p><p>Between 1983 and 1988, the typical age of an MP in Kenya was 43 years old. Fast forward to today, and the typical age has risen to 48 years old. That’s an increase of 5 years over the last 40 years, reflecting a trend towards older MPs.(in an article by Chris orwa)</p><p>When we break it down by region, we see some interesting variations. In Western Kenya and Nyanza, the typical age is even higher, with MPs averaging around 54 and 52 years old, respectively.</p><p>However, it’s important to note that these numbers aren’t set in stone. We have even older MPs who manage to get elected. This data highlights the evolving landscape of Kenyan politics, where the age of MPs has been on the rise, but there’s still room for diverse representation, including older individuals making their mark in the political arena.</p><p><strong>SHIFT OF POWER IN THE NATIONAL LEVEL</strong></p><p>When a new government takes charge, it often signifies a major shift in the political landscape. This shift brings in new political waves, trending parties, and MPs who don’t align with these changes can find themselves out of a job. In Kenya, the power often lies with the party, and constituents tend to vote for the party rather than the individual MP, resulting in significant turnover.</p><p>Let’s look at some numbers to understand this phenomenon better. In 2013, when the presidency shifted from the late President Mwai Kibaki, only 42 percent of the MPs were re-elected. Notably, 78 MPs attempted to secure other positions like Governor and Senator, but only 30 succeeded.</p><p>Even in 2017, when there was no change in the presidency, a substantial number of MPs were sent packing. Only 42 percent of the MPs were re-elected.</p><p>The most recent shift in power came in 2022 when His Excellency William Ruto assumed the presidency. Out of 290 MPs, 144 were re-elected. However, 59 MPs who belonged to the Jubilee and ODM parties had to switch to the trending UDA party to secure re-election. This shift underscores the adage, “shape up or shape out,” as it’s likely that if they hadn’t switched, only 85 MPs would have been re-elected.</p><p>This pattern highlights the volatile nature of Kenyan politics, where party affiliation often plays a crucial role in an MP’s fate, regardless of their individual performance or track record.</p><p><strong>DEATH</strong></p><p>This could not be a major factor but 10 mps died in office between 2017 and 2022 thus this could also be a factor</p><p><strong>REGION</strong></p><p>In Kenyan politics, the odds of an MP getting re-elected can vary significantly from one region to another. Factors like development initiatives, lack of competition, and the perception of irreplaceability can play a crucial role. Let’s take a closer look at three distinct regions — Central (Murang’a and Kiambu), North Eastern (Wajir and Garrissa), and Nyanza (Kisumu and Siaya) — to understand how re-election rates differ.</p><p><strong>1. Central Region (Murang’a and Kiambu):</strong><br> — In Murang’a, only one MP was re-elected in 2013, and three in 2017.<br> — In Kiambu County, four MPs were re-elected in 2017, but this number dropped to three in 2022.</p><p><strong>2. North Eastern Region (Wajir and Garrissa):</strong><br> — In Garrissa, two MPs managed to secure re-election in 2017 and two in 2022.<br> — Wajir County saw a similar trend, with one MP being re-elected in 2017 and one in 2022.</p><p>3.<strong> Nyanza Region (Kisumu and Siaya):</strong><br> — In Siaya County, two MPs were re-elected in 2017, and this number increased to five in 2022.<br> — Kisumu also showed strong continuity, with five MPs being re-elected in 2017 and five in 2022.</p><p>Interestingly, Siaya region stands out as having a higher likelihood of re-electing its MPs compared to the other regions. The reasons behind this regional variation could be multifaceted. It may include strong support for incumbent MPs due to effective development projects, less competition within their parties, or a deep-rooted connection between the MPs and their constituents.</p><p>This regional disparity in re-election rates sheds light on the complex dynamics of Kenyan politics, where different regions have distinct preferences and patterns when it comes to choosing their representatives.</p><p><strong>STRONGER COMPETITORS</strong></p><p>For Members of Parliament (MPs) in Kenya, the path to re-election is often marked by challenges and rivalries, and the odds of being ousted by a fellow constituent — sometimes a relative newcomer to the political arena — are substantial. In 2022, a whopping 133 first-time MPs were elected to the National Assembly. These individuals were essentially newcomers, representing constituents who had placed their trust in someone new to the parliamentary stage. But how do experienced MPs manage to navigate the fierce competition that often comes their way?</p><p>Let’s delve into the numbers. In 2017, a staggering 166 MPs were sent packing, which meant that 57% of the MPs elected that year were newcomers. These political rookies proved to be stronger competitors, ousting a significant portion of the incumbent MPs. In 2022, although the tide had somewhat shifted, the competition remained fierce, with 45% of the sitting MPs losing their seats to determined challengers.</p><p>These figures shed light on the demanding nature of Kenyan politics, where re-election is never guaranteed, and first-time MPs have proven to be formidable opponents. Experienced MPs must continuously adapt, connect with their constituents, and demonstrate their effectiveness to secure their place in the National Assembly. The evolving landscape of Kenyan politics keeps both incumbents and newcomers on their toes, making each election a dynamic and competitive affair.</p><p><strong>CORRUPTION RELATED CASES</strong></p><p>In the realm of Kenyan politics, a troubling reality has emerged — one that raises questions about the power of memory and the significance placed on ethical conduct. In a random sample of 10 MPs embroiled in allegations and scandals related to graft and corruption, a staggering 7 of them managed to secure re-election in 2022. The hard pill to swallow here is that even in the face of serious corruption charges, politicians can seemingly get away with it and still find themselves back in office.</p><p>This situation prompts a series of introspective questions. How quickly do people forget the misdeeds of their elected representatives? Or is it possible that constituents simply prioritize other factors over allegations of corruption? The truth of the matter remains elusive, as it challenges the ideals of transparency and accountability that are fundamental to a healthy democracy.</p><p>The implications of this phenomenon are profound, highlighting the complex relationship between voters and their elected officials. It raises concerns about the impact of corruption on Kenya’s political landscape and the values that underpin the choices made in the ballot box. In a nation where the fight against corruption is an ongoing battle, the ability of politicians embroiled in such scandals to maintain their positions serves as a stark reminder of the intricacies of Kenyan politics.</p><p><strong>PERFOMANCE</strong></p><p>In the realm of Kenyan politics, performance evaluation has become a significant indicator of an MP’s worthiness in the eyes of their constituents. In 2018, a survey conducted by Infotrack assessed the performance of MPs, ranking them based on their effectiveness in their respective constituencies. What’s striking is that out of the top 10 MPs identified as the best performers, a remarkable 8 of them were successfully re-elected in 2022. This scenario paints an ideal picture where effective performance not only earns MPs recognition but also secures them a second chance to serve their communities.</p><p>This observation suggests that voters place a premium on tangible achievements and results when casting their ballots. MPs who have demonstrated their commitment to improving the lives of their constituents, whether through development projects, policy initiatives, or responsive leadership, are rewarded with continued trust and re-election.</p><p>The correlation between performance and re-election underscores the importance of delivering on campaign promises and maintaining a strong connection with the electorate. It signifies a growing awareness among Kenyan voters that they have the power to hold their representatives accountable for their actions.</p><p>In this ideal scenario, performance becomes the foundation upon which the political relationship between MPs and their constituents is built, reinforcing the notion that effective governance can lead to a second term in office. However, it also raises the bar for all elected officials, emphasizing the imperative of delivering results and fulfilling the aspirations of those they serve…</p><p><em>conclusion</em></p><p>Politics in Kenya has transformed into a fiercely competitive arena, so much so that even children now see it as a potential career path. It’s a field where success is hardly a stroke of luck; it’s the result of hard-fought battles and determined efforts. The nation’s political landscape is dotted with affluent politicians, further emphasizing that re-election is no happenstance. It’s a well-earned victory that comes with a price.</p><p>But, as the dust settles after each election, a critical question emerges: Is the relentless cycle of re-election harmful to the development of our constituencies? Let’s narrow our focus to <strong>Tetu Constituency in Nyeri</strong>, a constituency that has been electing new MPs every five years for the past three and a half decades. Even the late Nobel Prize winner, Professor Wangari Maathai, couldn’t secure re-election.</p><p>A news story aired on NTV in July 2022 paints a telling picture of Tetu Constituency. It reveals that only recently did the constituency witness the establishment of a new police post, a petrol station, a bank, and a savings and credit cooperative organization (SACCO). Despite its rich history, the constituency has languished in underdevelopment, seemingly caught in a cycle of political shifts.</p><p>It raises a poignant question: Are we, as citizens, inadvertently doing more harm than good by electing a new MP every five years? In many cases, incoming MPs often undertake projects that erase the work of their predecessors — painting over the legacy with their own colors, adding a new banner to the roads, and reworking projects that were already underway. This practice contradicts the ideal of building upon the progress made by former MPs and instead perpetuates a cycle of stagnation.</p><p>In conclusion, the competitive nature of Kenyan politics can yield progress, but it also carries the potential to stall development in our constituencies. It’s time to reflect on the impact of our choices and consider the long-term consequences of our electoral decisions. As we navigate the political landscape, let’s aim for continuity and sustained development rather than a perpetual cycle of erasing and starting anew. Our constituencies deserve better — a future where development knows no political boundaries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4230eb8a40b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARIMA AND SARIMA MODELS]]></title>
            <link>https://medium.com/@kamandesimone/arima-and-sarima-models-b3873ed9489d?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3873ed9489d</guid>
            <category><![CDATA[arima-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 14:30:04 GMT</pubDate>
            <atom:updated>2023-08-18T14:30:50.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*slPCQADrletqNirCci0hNg.png" /></figure><p>In the below notebook we will be implementing a time series prediction model using ARIMA MODEL(Autoregressive Integrated Moving Average) and SARIMA(Seasonal Autoregressive Integrated Moving Average)</p><ul><li>Autoregressive (AR): This component refers to using past values of the time series itself to predict future values. In other words, it’s a regression of the series against itself.</li><li>Integrated (I): This component involves differencing the series to make it stationary, which means removing trends and making the series’ statistical properties more consistent over time.</li><li>Moving Average (MA): This component involves using past forecast errors (residuals) to predict future values. It’s like a regression of the forecast errors.</li></ul><p>ARIMA models are typically denoted as ARIMA(p, d, q), where:</p><ul><li>p: The order of the autoregressive component (AR)</li><li>d: The degree of differencing (I)</li><li>q: The order of the moving average component (MA)</li></ul><p>SARIMA model takes into account the seasonal patterns in the data.</p><ul><li>Seasonal: This component accounts for the repeating patterns that occur at regular intervals in the data, such as monthly, quarterly, or yearly patterns.</li></ul><p>SARIMA models are typically denoted as SARIMA(p, d, q)(P, D, Q, s), where the capital letters represent the seasonal components:</p><ul><li>P: The order of the seasonal autoregressive component</li><li>D: The degree of seasonal differencing</li><li>Q: The order of the seasonal moving average component</li><li>s: The length of the seasonal cycle (e.g., s = 12 for monthly data with a yearly cycle)</li></ul><p>These models are widely used in time series analysis and forecasting to capture the underlying patterns and trends in the data.In the folllwoing article we will clearly distinguish when to use arima and sarima models.We will also fit our dataset using bothe the ARIMA and SARIMA MODELS and see why we use each in every sitiuation.In the below code we will convert the datetime column and also drop all the other columns and be left with only the target column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*9IZK94TEBqF-9kwM_JHLeg.png" /></figure><p>We will then look at the distribution of our dataset how the sales vary year to year</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*GCmpX1oYnrBjdX1IKF6vfg.png" /></figure><p>We can also look and calculate the mean saleds of each year</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*qNGLJ3sOCO3o32UWjg6gwA.png" /><figcaption>We can see 2019 recorded the highest sales</figcaption></figure><p>We can also look at the distribution of the dataframe through the months</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*uD5S3drhyVREYgrL9KUMxw.png" /><figcaption>The monthly distribution of our data</figcaption></figure><p>In the following code we will be executng where we will be plotting the rolling mean and the standard deviation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*jZlzWLBhxZk_GKZVsNDlzw.png" /></figure><p>For the below code we will be determining whether our datais seasonal or stationery ,this will form a basis of the model we will use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*bZjhgdpuyKDiw_Yoa-p7Xw.png" /></figure><p>After the plotting of the above data we can clearly see that our data is seasonal . After knowing this we can decide on which model to use whether its SARIMAX OR ARIMA. If our data is seasonal we use SARIMAX and if its stationery we use ARIMA . Since we have already come to a conclusion that our data is seasonal and that we shall be adopting a sarimax model then we willstart figuring out the parameters to use to build the model . we need the p,d q values in order to build this model(SARIMAX /ARIMA)</p><p>We will start by figuring out our d value. The value od d is either 0 or 1 if the data is stationery we should use 0 and if the data is seasonal we should use 1</p><p>In the below line of code we will be looking for the value of p the value of p we would simply put it as after which line do we see our plotted line distend and have the biggest change in the curve . we look at that line and after we see it then we can actually determine the value of p</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*LALgOxVBfoSTrBuTXu81dQ.png" /></figure><p>In the below code we will be looking for the value of q(moving average).in the below plots we find the correlation and that why the first figure plotted will always coincide with 1and thus to find q we look at where from the first plot do we start risig againand its quite clear we start rising from the second plot excluding the first plot and thus our q is eqal to 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*NlXMjrpfJkoPE2LUKGU42w.png" /></figure><p>As we said both arima and sarima would work on the data but lets see the effect of using a ARIMA MODEL on a stationery trend (keep in mind we should be using sarima model)We will fit the arima model and we wil see the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*uFAmwpC4ujtYgzaxF8LZNw.png" /><figcaption>fitting the arima model</figcaption></figure><p>We will now look at the results of our predictions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*E5z8-amPKMUHCC3H8l1yig.png" /><figcaption>The results of the arima model</figcaption></figure><p>Its quite clear that our model is perfoming below expectation and thus using Arima model it would be very unwise since the data is seasonal</p><p>In the code below we will be now using the sarima model and we willbe qrouping the values and we are using PDQ and fixing the values to 1 to assume that for the whole year we have one pq and d and it repeats itself every 12 months</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*xmAxaAewSgi2hkZaTMxs6g.png" /><figcaption>fitting the sarima model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*ouIvtDn50_1l7JSPAeG5ew.png" /><figcaption>the fitted sarima model</figcaption></figure><p>W can see now our model has been predicted correctly and its perfoming very well.The secret is first understanding the data when we understand the data whether is seasonal or stationery then we can know which model to fit and thus the correct predictions will be made consequent to that and thus the correct forecasts area made.The code is<a href="https://github.com/stilinsk/ARIMA-AND-SARIMA-MODELS/blob/main/ARIMA%20(2).ipynb"> here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3873ed9489d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BIG DATA USING PYSPARK]]></title>
            <link>https://medium.com/@kamandesimone/big-data-using-pyspark-aeffa14a23a0?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeffa14a23a0</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 07:40:54 GMT</pubDate>
            <atom:updated>2023-08-18T13:38:15.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*twoBXmIywTejws23Qx6f6g.png" /></figure><p>Welcome to the realm of PySpark: where big data meets its match. In this article, we’ll dive into the transformative capabilities of PySpark and its role in simplifying complex data processing.Make sure you configure your machine to java.</p><p>In this article, we’ll create a model to predict whether a customer will commit to a term deposit at a bank using PySpark. We’ll implement different classification models and fine-tune algorithms. After setting up a Spark session and configuring dependencies on our machine, we’ll proceed with the implementation. This will allow us to build an efficient model without unnecessary verbosity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*3l-p0M9owU-VF7NbCP1VDw.png" /><figcaption>initializing the spark session</figcaption></figure><p>We will look at the first five columns using the spark.dataframe.take,very different from how we use pandas library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*VDN2gtvtgzsc7WiXRvKYRw.png" /><figcaption>reading the first five columns using spark</figcaption></figure><p>Since we are solving a classification problem we will look at the distribution of the target column to ensure our dataframe is not biased to one classed and that our target column is balanced</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*JzRW5uPyDq0X14wCWeVhaA.png" /><figcaption>distribution of our target column</figcaption></figure><p>Next we will be looking at the summary statistics of our numeric columns . This comes in handy when dealing with outliers and also looking at the distribution of the various columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*CX8Axrz2MvmxZutfOg06mw.png" /></figure><p>Next we will be looking at the correlations of diffferent columns.This comes in handy when fitting the model where columns with lesser correlations are dropped. This is similar to the pairplot that we do when dealing with pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*G0Y0Y7VuBQ4S6eBhcVpTfA.png" /><figcaption>pairplot as we look at the correlation of columns in our dataframe</figcaption></figure><p>We can see that there is not that concrete correlation between the columns above Therefore we can keeep all the variables for our modelexcept for the time (dayand month)basicallly a month will not likely influemvce whether a deposit will be made or not</p><p>We will create a spark pipeline that will order the order of sequence for the preprocessing of our data.We will start with category indexing ,One Hot encoding and Vector Assembler-a feature transformer that merges multiple columns into a vector column The code is available at the databricks site and it indexes each categorical columnusing the string Indexer and converts the indexed categories into one hot encoded varibales. The resulting output has the binary vectors appended to the end of each row. We use the StringIndexer again to encode our labels to label indices. Next, we use the VectorAssembler to combine all the feature columns into a single vector column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Z_B7Jm4EuV9T2xZ4CtbBw.png" /><figcaption>we have the stages stringindexer,encoder and then the vector assembler</figcaption></figure><p>Vector Assembler: A VectorAssembler is created to assemble all the feature columns, including the one-hot encoded categorical columns and the numeric columns, into a single feature vector named ‘features’. The input columns are specified as assemblerInputs, which is a concatenation of the one-hot encoded categorical column names and the numeric column names. The VectorAssembler is added to the stages list.</p><p>The stages list will contain all the necessary stages of the data preprocessing pipeline, including string indexing, one-hot encoding, label string indexing, and vector assembling. These stages can then be used in a Pipeline for further processing or training a machine learning mod</p><p>we will then use a pipeline to chain multiple transformers and estimators together to specify our algorithm workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*YLq-WZ5htiXk--6Bh18usA.png" /><figcaption>the implementation of the pipeline</figcaption></figure><p>Creating a Pipeline: The Pipeline is instantiated with the stages list, which contains all the stages above then fit the Pipeline</p><p>Transforming the Data: The fitted Pipeline is then applied to the input dataframe df using pipelineModel.transform(df). This step executes the data transformations defined in the Pipeline and produces a new dataframe with the transformed features.</p><p>Selecting Columns: The selectedCols list is defined to specify the columns to be selected in the transformed dataframe. It includes the ‘label’ column, which represents the transformed target variable, the ‘features’ column, which contains the assembled feature vector, and cols, which likely refers to the remaining columns in the original dataframe.</p><p>Selecting Columns in the Transformed Dataframe: The df.select(selectedCols) operation is performed to select only the specified columns from the transformed dataframe. This operation creates a new dataframe with only the selected columns.</p><p>After transforming our dataset we will then split our data into training and test data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*xTkp5N2G2ubQojWKv45MgQ.png" /><figcaption>splitting the dataset</figcaption></figure><h3>Next we will be fitting the logistic regression on our dataset and determine its perfomance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*5aBJ_OAbGxft_TLO5P3CSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*hBUJIzWXm-SvOjERPi_DjQ.png" /><figcaption>The training roc is 88.77</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*TENGTvFrEAQZCxpRY-maOw.png" /><figcaption>the test roc is 88.56</figcaption></figure><p>We obtain a plot showing the ROC curve, which illustrates the trade-off between the true positive rate and the false positive rate. The area under the ROC curve is a performance metric that quantifies the overall classification performance of the logistic regression model.As we can see the roc of the test and train dataset is very close to one another thus our model is perfoming fairly very well.Next we will implement a ParamGridBuilder and a crossvalidator and also check its perfomance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*G6GhTDLA_FNiRKKibN3C6g.png" /><figcaption>We can see its perfomance when tuned goes down slightly abit</figcaption></figure><h3>We will implement a decison tree classifier</h3><p>Decision trees are widely used since they can easily interpret ,handel categorical data and extend multiclass classifications and hanldel and capture non-linearities and feature interactions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*U51sqp_ZmNAMY6lARiNtyA.png" /><figcaption>the perfomance is 78.08 slightly worse perfomance than the logistic regression</figcaption></figure><h3>We can improve the decision tree model by using the ensemble random forest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*9JelQG-XW31EOdfeXINaTA.png" /><figcaption>the random forest model perfoms very well</figcaption></figure><h3>We will use the Gradient-Boosted-Tree-classifier</h3><p>A gradient boosted tree classifier works by iteratively training a sequence of decision trees, where each subsequent tree focuses on correcting the mistakes made by the previous trees, and the final prediction is obtained by combining the predictions of all the trees through a weighted sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*ihuHOQC9fKABxp18i7ygsg.png" /><figcaption>The gradient boosted trr model perfoms the best</figcaption></figure><p>In conclusion, through our utilization of PySpark, we have successfully constructed and fine-tuned diverse machine learning algorithms to create an effective classification model. This model holds the potential to predict customer commitment to term deposits with a high degree of accuracy. By deploying this model using Databricks, we can harness its power to make informed decisions and enhance the bank’s overall efficiency and success in acquiring term deposits.The code is executed<a href="https://github.com/stilinsk/PYSAPRK-CLASSIFCATION-MODEL"> here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeffa14a23a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARE DEEP LEARNING MODELS REALLY THE BEST ?]]></title>
            <link>https://medium.com/@kamandesimone/are-deep-learning-models-really-the-best-c5f7e410ccf8?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f7e410ccf8</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 05:33:55 GMT</pubDate>
            <atom:updated>2023-07-25T05:33:55.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*k6QjtHcIDeFMnXECRHJQtA.png" /></figure><h3>ARE DEEP LEARNING MODELS REALLY THE BEST ?</h3><p>In the final part of our series, we will analyze the performance of our dataset by implementing a deep learning model. The article below will shed light on whether we can achieve better results with this approach.</p><p>In the previous parts of our series, we observed that the random forest model outperformed the other model. Now, we are interested in investigating whether the deep learning model will yield better results.</p><p>In this model, we are focusing on predicting insurance premium prices based on various independent features. Before proceeding, we begin by normalizing our data, a process that standardizes the data to ensure it is on a similar scale, facilitating better training of the model.</p><p>One new aspect in the deep learning model is the introduction of a validation set. This dataset contains data that the model has not encountered during training. The validation set serves the purpose of evaluating the performance of our model on unseen data. This allows us to gauge how well our model generalizes to new and unseen instances.</p><p>By incorporating normalization and validation set, we aim to assess the performance of our deep learning model and determine if it surpasses the random forest model’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*aESVB6Se5M4jnfQJQxuqGQ.png" /><figcaption>normalisation of our data</figcaption></figure><p>The build_model() function defines a sequential model using keras.Sequential(). This model consists of three layers: two hidden layers with 64 units each, using the ReLU activation function, and an output layer with a single unit.</p><p>The optimizer chosen for this model is the RMSprop optimizer with a learning rate of 0.001, defined as tf.keras.optimizers.RMSprop(0.001).</p><p>The model is then compiled using model.compile(), specifying the loss function as mean squared error (&#39;mse&#39;). The optimizer and evaluation metrics are also specified, with mean absolute error (&#39;mae&#39;) and mean squared error (&#39;mse&#39;) as the metrics to track during training process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*TXd-tWaf6703ImsDuPqazQ.png" /><figcaption>This comes in handy when monitoring a large dataset that takes alot of time to train to monitor whether its still working</figcaption></figure><p>We will then monitor the perfomance of our epochs .we have used 1000 epochs since our dataset is not that large . Lets look at the perfomance of our last 10 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*HiRYbbUBktRWcUhV1nF56g.png" /></figure><p>We will then look at the perfomance of our model.remember we have a validation set that we will use to test the perfomance of our model. Specifically we will be looking at our validation mae and validation mse we will look at whether it is overfitting or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*jjiOU4sYbDra_G2ge8ApqQ.png" /><figcaption>this is the code to print our metrics for evaluation of our deep learning model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*2xt4h8jlN9VKrNVFKHVRTA.png" /><figcaption>the perfomance of our models</figcaption></figure><p>As we can see our model is not perfoming at its level best and this may be due to instancces of overfitting and thats why our validation mae and validation mse are tending to become constant thus we will tune our mode and use early stopping as our parameter where if the model notices that its perfomance is not improving then the model stops training we will see the implementation in the below code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Rcni8RsViVvE_fFX9hT11Q.png" /><figcaption>we have used early stopping to fine tune our model to improve its perfomance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*2jk6_Y3RMiOwn3kpQagKDg.png" /></figure><p>As we can see from our model the point it has sstopped improving then the training has stopped thus we can see the val mse and val mae is hence reducing thus our model perfomance is good.lets look at our mae and look how well our model is perfoming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*jDT415wobONyQr9L9z8Osg.png" /><figcaption>our model has a perfomance of 3133</figcaption></figure><p>Our deep learning model’s performance can be evaluated based on its mean absolute error (MAE), which measures the average difference between our predicted values and the actual values in the dataset. The current MAE for our model stands at 3133, indicating how far off our predictions are from the true values on average.</p><p>Throughout this series, we have assessed the performance of several machine learning models. When comparing our random forest model and XGBoost model to the deep learning models, we observed that the former two performed slightly better. However, it’s essential to note that the superiority of a model can depend on the nature of the dataset and the specific problem at hand. Therefore, it is not always the case that deep learning models outperform other methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f7e410ccf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MASTERING XGBOOST ALGORITHM]]></title>
            <link>https://medium.com/@kamandesimone/mastering-xgboost-algorithm-9c37cbf6ce81?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c37cbf6ce81</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 13:01:50 GMT</pubDate>
            <atom:updated>2023-07-25T05:27:37.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*qamomavev3LFpdfAFG8dNw.png" /></figure><blockquote>Machine learning: the art of teaching computers to be as confused as we are, but with fancy algorithms.”</blockquote><p>Welcome to our third model of our regression machine learning algorithms.We have part <a href="https://medium.com/@kamandesimone/mastering-the-art-of-linear-regression-45a235a8709b">one</a> and <a href="https://medium.com/@kamandesimone/mastering-random-forest-algorithm-936b38728c1a">two</a>, we will delve into a powerful model known as XGBOOST which works by:</p><p><strong>Decision Tree Boosting: </strong>XGBoost is based on the concept of boosting, which involves training an ensemble of weak learners, typically decision trees, sequentially. Each tree in the ensemble is built to correct the mistakes made by the previous trees.</p><p><strong>Objective Function:</strong> XGBoost defines an objective function that needs to be optimized during the training process. The objective function consists of two parts: a loss function that quantifies the difference between predicted and actual values, and a regularization term that controls the complexity of the model.</p><p><strong>Gradient Descent Optimization:</strong> XGBoost uses gradient descent optimization to minimize the objective function. It iteratively builds decision trees, where each subsequent tree is fitted to the negative gradient (residuals) of the objective function with respect to the predictions of the previous trees.</p><p><strong>Feature and Instance Weighting:</strong> XGBoost incorporates feature and instance weighting to improve model performance. Feature weighting assigns importance scores to each feature, indicating their relevance in making predictions. Instance weighting assigns higher weights to instances that were previously misclassified, allowing the subsequent trees to focus more on correcting those mistakes.</p><p><strong>Regularization Techniques:</strong> XGBoost employs various regularization techniques to prevent overfitting and enhance generalization. These include shrinkage (learning rate), which controls the contribution of each tree, and column subsampling, which randomly selects a subset of features at each split.</p><p><strong>Prediction Aggregation:</strong> Once all the trees are built, predictions from each tree are aggregated to obtain the final prediction. For regression tasks, the predictions are averaged, and for classification tasks, XGBoost uses a logistic function to transform the raw predictions into probabilities.</p><p>By utilizing gradient boosting, optimization techniques, and regularization, XGBoost creates a strong ensemble model that delivers accurate predictions. It is highly customizable, offering numerous hyperparameters to fine-tune the model’s performance and achieve superior results on various machine learning tasks.</p><p>We will be using the<a href="https://github.com/stilinsk/article-linear-reg/blob/main/insurance.xls"> insurance data </a>set we used in the <a href="https://github.com/stilinsk/article-linear-reg/blob/main/random%20forest%20regression%20(7).ipynb">part 2</a> of our series.we will also at the end after getting all the results we will compare the perfomance of each model and we will see which model was appropriate to use in this sitiuation.We will be looking the total premiums one is due to pay based on their age, bme,no of children,whether they smoke,sex and region.</p><p>In the preprocessing stage of the dataset, various steps were undertaken to prepare the data for the model . I implemented the xgboost regressor by fitting the model using a pipeline for data preprocessing and model training using the scikit-learn library. In this pipeline, we have applied data preprocessing using a ColumnTransformer, which applies different transformations to the numeric and categorical features in your dataset. The numeric features are standardized using StandardScaler, and the categorical features are one-hot encoded using OneHotEncoder. and evaluating it as shown below</p><p>I implemented theby fitting the model and evaluating it as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*u5hPFOfKcUbd6ND380YuHA.png" /></figure><p>As it can be seen when we evaluate our model we see the r2 score of train data is 0.99 and of test data is 0.83Thus we can clarly see that our data is overfitting . The simplest way to determine whether a model is overfiting or not then the test and train data should be close to one another.Thus we will need to tune the model to find the best params to tune our model to reduce overfitting.</p><p>Here are the parameters we can use to train our model:</p><h3>The following are the parameters :</h3><p><strong>learning_rate:</strong> It determines the step size at each boosting iteration. A lower learning rate makes the model more robust but requires more iterations to converge.</p><p><strong>max_depth:</strong> It specifies the maximum depth of each decision tree. Deeper trees can capture complex relationships but may overfit the data if not properly controlled.</p><p><strong>n_estimators:</strong> It sets the number of boosting iterations or the total number of trees in the model. More trees can improve performance, but there is a trade-off with computational complexity.</p><p><strong>subsample:</strong> It determines the fraction of the training instances to be used for training each tree. It helps in reducing overfitting by introducing randomness.</p><p><strong>colsample_bytree:</strong> It specifies the fraction of features (columns) to be used when constructing each tree. Similar to subsampling, it introduces randomness and reduces overfitting.</p><p><strong>reg_alpha:</strong> It controls L1 regularization (Lasso) on the leaf weights. It encourages sparsity in the model by adding a penalty term to the loss function.</p><p><strong>reg_lambda:</strong> It controls L2 regularization (Ridge) on the leaf weights. It adds a penalty term to the loss function to prevent overfitting and stabilize the model.</p><p><strong>min_child_weight:</strong> It sets the minimum sum of instance weights (Hessian) needed in a child node to continue splitting. It helps in preventing overfitting by enforcing a minimum number of samples in leaf nodes.</p><p><strong>gamma:</strong> It specifies the minimum loss reduction required to make a further partition on a leaf node. Higher values result in fewer splits, which can help control the complexity of the model. will be implemented as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*7OYk_3ofhm7cUFm1UyDtQw.png" /></figure><p>As clearly shown above we have implemented a Gridsearchcv where we also implement the pipeline also for preprocessing our data and we have sought for the best parameters of our model. we have established the learning_rate as 0.01,max_depth as 3, min_child_weight as1,n_estimators as 300,reg alpha as 0 reg_lambda as 0.5,sub_sample as 0.8,colsample_bytree as 0.8 gamma as 0. we have also seen that our test r2 as 0.87 and train r2 as 0.86 . we can see our model has greatly improved and we have greatly reduced overfitting and as per our XGBOOST model we can say that our model is perfoming at optimum.</p><p>After comparing from our last random forest model we can clearly see that the random forest actually perfoms better than the xgboost model and so in this case scenario we would actually prefer the random forest model to this one.</p><p>IN order to make our series complete we will be using a deep learning neural network and observe its perfomance .Well how does deep learning compare with the normal scikit-learn models.see you in the last part of this series.</p><p>In conclusion, the XGBoost model stands as a remarkable tool for data scientists seeking optimal predictive performance. Its ability to leverage boosting techniques, handle complex datasets, and optimize performance metrics sets it apart from traditional machine learning algorithms. By harnessing the power of XGBoost, data scientists can unlock hidden patterns, make accurate predictions, and extract valuable insights from their data. As the field of machine learning continues to advance, XGBoost remains a go-to choice for tackling a wide range of predictive modeling tasks, providing a powerful and reliable tool to drive data-driven decision-making. The code has been implemented <a href="https://github.com/stilinsk/xgboost-pipeline-model">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c37cbf6ce81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MASTERING RANDOM FOREST ALGORITHM]]></title>
            <link>https://medium.com/@kamandesimone/mastering-random-forest-algorithm-936b38728c1a?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/936b38728c1a</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 15:01:33 GMT</pubDate>
            <atom:updated>2023-07-24T18:50:44.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Yys1hPIWCSaYA2kElO_lDg.png" /></figure><blockquote>Machine learning: where data whispers its secrets, painting a sweeter picture of the world.</blockquote><p>In <a href="https://medium.com/@kamandesimone/mastering-the-art-of-linear-regression-45a235a8709b">part two</a> of our series, we will explore the Random Forest algorithm in detail, focusing on a regression task. However, we will be using a different dataset than the one in part one. This decision is based on the size of the dataset, as the previous one was too large to train and tune the model effectively on a simple laptop within a reasonable timeframe. By utilizing a more manageable dataset, we can provide a thorough explanation of the Random Forest algorithm and its application in regression tasks. Stay tuned for an in-depth exploration of Random Forest and its optimization for better predictions.</p><p>Here is a brief introduction to how the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">random forest algorithim</a> works: <strong>Data Sampling:</strong> Random Forest works by randomly selecting subsets of the original training data, with replacement. This technique is known as bootstrapping or bagging. Each subset is called a “bootstrap sample.</p><p><strong>Building Decision Trees:</strong> For each bootstrap sample, a decision tree is constructed using a subset of the features. The features are selected randomly at each split of the tree. This randomness helps to reduce the correlation between individual trees and promotes diversity in the forest.</p><p><strong>Voting for Predictions:</strong> Once the decision trees are built, predictions are made by each tree individually. In the case of regression, the predicted values from all trees are averaged to obtain the final prediction. For classification, each tree assigns a class label, and the class with the majority vote becomes the predicted class.</p><p><strong>Ensemble Prediction:</strong> The final prediction of the Random Forest model is obtained by aggregating the predictions of all individual trees. The averaging or voting process helps to reduce overfitting and improves the overall robustness and accuracy of the model.</p><p>The Random Forest can work with large datasets, and is less prone to overfitting compared to a single decision tree. Additionally, it can provide estimates of feature importance, which can be helpful for understanding the importance of different features in the data.</p><p>Overall, Random Forest is a powerful and widely used algorithm for supervised learning tasks, known for its accuracy, scalability, and robustness. You can read more on how a <a href="https://scikit-learn.org/stable/modules/tree.html">Decsion tree works</a>.</p><p>We will be using data from an <a href="https://github.com/stilinsk/article-linear-reg/blob/main/insurance.xls">insurance datase</a>t where we will be predicting the amount of premiums one is due to pay based on their age, bme,no of children,whether they smoke,sex and region.</p><p>In the preprocessing stage of the dataset, various steps were undertaken to prepare the data for the Random Forest regression task. Non-numerical data was encoded, converting them into numerical representations. Additionally, the distribution of data in each column was examined and analyzed in detail. This exploration helps in identifying the appropriate values to use for filling missing values, such as the median or mean. Furthermore, understanding the data distribution provides insights into what to anticipate during the prediction phase, setting expectations for the target variable. For a comprehensive understanding of the data preprocessing steps and findings, please refer to the detailed explanations available in <a href="https://github.com/stilinsk/article-linear-reg/blob/main/random%20forest%20regression%20(7).ipynb">my GitHub repository.</a></p><p>I implemented the random forest regressor by fitting the model using a pipeline for data preprocessing and model training using the scikit-learn library. In this pipeline, we have applied data preprocessing using a ColumnTransformer, which applies different transformations to the numeric and categorical features in your dataset. The numeric features are standardized using StandardScaler, and the categorical features are one-hot encoded using OneHotEncoder. and evaluating it as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*6EsiKx-_tjkbHwSFTLqtYA.png" /></figure><p>As it can be seen when we evaluate our model we see the r2 score of train data is 0.97 and of test data is 0.86 Thus we can clarly see that our data is overfitting . The simplest way to determine whether a model is overfiting or not then the test and train data should be close to one another.Thus we will need to tune the model to find the best params to tune our model to reduce overfitting.</p><p>These are the parameters to tune our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*ib90XrTbTzgY2FJ6fuCrkg.png" /><figcaption>how the random forest tunes the decision tree algorithm</figcaption></figure><p><strong>n_estimators :</strong>The number of decision trees in the forest.Incresing the number of estmators can improve the perfomance it also increases the computation time and mem requirements</p><p><strong>max_depth: </strong>The maximum depth of each decision tree in the forest. It determines the maximum number of levels in the decision tree. Setting a higher value can allow the model to capture more complex relationships in the data, but it can also lead to overfitting.</p><p><strong>min_samples_split:</strong> The minimum number of samples required to split an internal node. It controls how the decision tree is built by specifying the minimum number of samples required to make a further split. A higher value can prevent overfitting, but it can also lead to underfitting if set too high.</p><p><strong>min_samples_leaf:</strong> The minimum number of samples required to be at a leaf node. It specifies the minimum number of samples required to form a leaf node. Similar to min_samples_split, a higher value can prevent overfitting, but it can also lead to underfitting.</p><p><strong>max_features:</strong> The number of features to consider when looking for the best split. It determines the maximum number of features to consider at each split. The code will be implemented as follows,we will still use the pipeline to transfrom our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*htI2vr9ixD6j9qPjGFAMZA.png" /><figcaption>our tunes model perfomance</figcaption></figure><p>In the above model we have tuned the model and we look for the best parameters and train the model on our best parameters we have seen our max_depth is 5,min_samplles_leaf is 4, min _samples_split is 2,and n_estimators is 100. we get our model whose r2score of the test data is 0.87 and of train data is 0.88 .Thus we have greatly reduced overfitting and we can say our model is perfoming at optimum.Random forest has a feature known as feature importance where e look at the extent of the effect of every indipendent column on our target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*ufOKRaZfd_oTili58hFzRQ.png" /><figcaption>feature importance of each indipendent columns</figcaption></figure><p>We can see that the columns that really have an impact on our target columns are “smoker”, “bmi”, “age”, “children”, “region”, “sex”.</p><p>The model is broadly explained line by line in <a href="https://github.com/stilinsk/random-forest-pipeline-model">my github repository c</a>ode line by line. In conclusion, the Random Forest algorithm is a robust and versatile ensemble learning method that combines multiple decision trees to deliver accurate predictions. With its ability to handle large datasets, reduce overfitting, and provide feature importance insights, Random Forest is a powerful tool for various machine learning tasks. Consider leveraging the strengths of Random Forest to enhance your predictive modeling and gain valuable insights from your data.Lets meet for part three as we look into detail an XGBOOST Model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936b38728c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Art of Linear Regression]]></title>
            <link>https://medium.com/@kamandesimone/mastering-the-art-of-linear-regression-45a235a8709b?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a235a8709b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 14:43:18 GMT</pubDate>
            <atom:updated>2023-06-05T10:34:32.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*r8zPuHOnXZX5dAoa-n0g2w.png" /></figure><blockquote><strong>“Machine learning: the catalyst that sparks innovation, propelling us into a future of endless possibilities.”</strong></blockquote><p>The data science life cycle can be both expensive and time-consuming, particularly when dealing with large datasets. The complexity increases when multiple models are involved, further impacting implementation costs and the overall duration of the cycle. Therefore, it becomes crucial to develop well-optimized models with carefully chosen hyperparameters to maximize their performance. In this three-part series, we will delve into the intricacies of each model, starting with LINEAR REGRESSION , followed by RANDOM FOREST and XGBOOST. By exploring these models in detail, we aim to enhance their performance and achieve superior results.</p><p>We will utilize real-life data sourced from<a href="https://catalog.data.gov/dataset/real-estate-sales-2001-2018"> DATA.GOV</a>, ensuring the practicality of our models (I higly advocate DATA.GOV as it gives real life data in real time thus practicing on messy data ). Consistency in data usage across all models will allow for a fair comparison of their performance at the end, once we conclude the XGBoost model. Initially, we will delve into the fundamentals of Linear Regression, which involves fitting a line that best represents the data points. By identifying the optimal line, the model becomes proficient in making predictions. The implementation of a cost function and the utilization of gradient descent further enhance the learning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*iSDmy77yUvXeaJ5HoyvVDg.png" /><figcaption>diagramatic representation of a linear regression model</figcaption></figure><p>To streamline our analysis, we will preprocess the data by selecting and retaining only 6 relevant columns from the original dataset, optimizing its efficiency. Additionally, we will apply standardization to ensure consistent scaling across the features. To further enhance the model’s performance, we will leverage Principal Component Analysis (PCA) for dimensionality reduction, facilitating a more compact representation of the data. After this preprocessing step, we will designate the X variable (independent variables) and y variable (dependent variable). To evaluate the model’s effectiveness, we will perform a train-test split. Finally, we will train our model on the training dataset. The code snippet for this process is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*ELNmFmR1GXRUi6oVOpXf8A.png" /></figure><p>we can see the mean absolute error shows 23889 our model ths is perfoming relly poorly we will need to use a technique called regularization. we will be using L1(<a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html">lasso regression:</a>)L1 regularization adds a penalty term to the loss function of a model, equal to the absolute value of the coefficients multiplied by a constant lambda. and L2 (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html">Ridge regression</a>:L2 regularization adds a penalty term to the loss function of a model, equal to the squared magnitude of the coefficients multiplied by a constant lambda.)to fine tune our model</p><p>You might be wondering why we are not utilizing GridSearchCV to tune hyperparameters for our linear regression model. The reason is that linear regression does not possess specific hyperparameters that require tuning. Unlike other models, linear regression does not have regularization parameters or complex structures that necessitate grid search and cross-validation. Therefore, the default hyperparameters of the linear regression algorithm are often sufficient for achieving optimal results. This simplicity and efficiency make linear regression an appealing choice for predictive modeling tasks. But does it make it the best ? we will have an answer at the end of our part 3 series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Ux79VGpq4LjAv8GiZDBzdg.png" /></figure><p>After tuning our model using the l1 and l2 models we see that our model has improved though slightly but these are the commonly used methods of improving our linear regression model.</p><p>In addition to this we can still use another method known as a cross validation score works by <strong>spllitting the data</strong>: The dataset is divided into multiple subsets or “folds.” The most common approach is k-fold cross-validation, where the data is split into k equal-sized folds. Each fold represents a different train-test split<strong>.Training and testing</strong>: The model is trained on a portion of the data called the training set, which consists of k-1 folds. The remaining fold is used as the test set. This process is repeated k times, with each fold serving as the test set exactly oncePerformance <strong>evaluation:</strong> The model is trained and evaluated k times, generating k performance metrics (e.g., accuracy, mean absolute error) corresponding to each fold. The average and standard deviation of these metrics are often calculated to assess the model’s overall performance<strong>.Model selection and</strong> <strong>hyperparameter tuning</strong>: Cross-validation can also be used to compare different models or tune hyperparameters. By evaluating multiple models or parameter configurations using cross-validation, it becomes possible to identify the one that performs the best on average across the folds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*gCnHFFjZFLu8K8fT4WdrAg.png" /><figcaption>cross validation implementation</figcaption></figure><p>The main advantages of cross-validation are that it provides a more robust estimate of a model’s performance, reduces the impact of data variability, and helps detect issues like overfitting or underfitting. It allows you to assess how well your model is likely to perform on unseen data and make more informed decisions about model selection, hyperparameter tuning, and generalization capabilities.We can see our model has greatly improved thus cross validation has actually improved our data a great deal.</p><p>In conclusion, linear regression is good and widely-used algorithm in the field of machine learning. It provides a straightforward approach for modeling the relationship between variables and making predictions. By estimating the coefficients of the linear equation, it enables us to understand the impact of different features on the target variable. With its simplicity and interpretability, linear regression remains a valuable tool for various applications, from predicting house prices to analyzing market trends. Its versatility and ease of implementation make it an essential technique for data scientists and analysts alike. The model is expalained in detail in my <a href="https://github.com/stilinsk/article-linear-reg">github repository</a>. See you in part two of the three series as we take on random Forest</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a235a8709b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WEBSCRAPPING AMAZON BOOKS FOR DATA SCIENCE USING SELENIUM]]></title>
            <link>https://medium.com/@kamandesimone/webscrapping-amazon-books-for-data-science-using-selenium-d8ef04d731d9?source=rss-494c015b13d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ef04d731d9</guid>
            <category><![CDATA[python-webscraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[simon kamande]]></dc:creator>
            <pubDate>Wed, 10 May 2023 00:13:38 GMT</pubDate>
            <atom:updated>2023-05-11T19:21:17.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFL6J1OJVBwB2xCHXyWdOQ.png" /></figure><h3>WEBSCRAPING FOR DATA SCIENCE USING SELENIUM</h3><blockquote><strong>“Without data you are just another person with an opinion” — W.Edward Deming</strong></blockquote><blockquote>Unveiling Personalized Book Recommendations: Web Scraping for an End-to-End Model (Part 1)</blockquote><blockquote>Join us on an exciting journey as we build a groundbreaking end-to-end book recommendation model. In Part 1, we delve into the vital step of web scraping, unlocking a world of data for personalized recommendations. Through automation and data science techniques, we gather rich insights from book descriptions, author , reviews, and more. Prepare to explore the fusion of technology and literature, revolutionizing how we discover captivating reads. Welcome to a transformative adventure in data science and personalized book recommendations.</blockquote><p>Let’s embark on an exhilarating web scraping journey to uncover the treasures of <a href="https://www.amazon.in/">Amazon’s</a> vast book collection. With Chrome as our trusted companion, we’ll create a seamless browsing experience using a Chrome <a href="https://chromedriver.storage.googleapis.com/index.html?path=114.0.5735.16/">web driver</a>. This exciting process begins with importing the necessary libraries and setting up our driver. Then, with a click of a button, we’ll navigate to the webpage where our adventure truly begins — the captivating realm of Amazon’s book offerings. Get ready to indulge in the sweetness of data extraction as we set the stage for an extraordinary exploration of books. Together, we’ll unveil the magic of Amazon’s literary universe, one page at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUWl2MNqoDofizI3lBH66A.png" /></figure><p>we will then navigate to our amazon website and inspect the code to the website for the webscraping process to commence. In every website we have the search text bar where we input what we are actually looking for from the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3l3oOZE7aCvg_Dcb74EHtQ.png" /><figcaption>html css code for the amazon website</figcaption></figure><p>As we can clearly see we have the code for the input button .We will have to access that code and add it to our notebook and actually run it as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axnGmnEjm-kjrnF_FQHo3A.png" /><figcaption>the code to acess our search text box</figcaption></figure><p>From then on the webpage changes just like in the code above and books from amazon are displayed . From here on we will be extracting the following:</p><ol><li>Name of the book 2. Author of the book 3. Overall rating of each book 4.Number f poeple who reviewed the book 5. The type of the book copy available and 5. Price of the book</li></ol><p>We will begin by creating a dataframe where we will store all the values we have extracted and create a loops that loops over the first 50 columns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*CWc6LGT7ytG_PmT-O3mo1w.png" /></figure><p>We will start by extracting the name of the book on the below photo we will be inspecting the webpage and also how the code actually should be executed :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-r_zFpTEqe6bFGXr_1HyQ.png" /><figcaption>the code to extract the book name</figcaption></figure><p>we will then move on to scrap the author’s name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGZY5dPjEK6P9-WRx72fBQ.png" /></figure><p>we will then scrapthe overall rating of each book:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mV26kHFbxUKhtCta5Ol2A.png" /><figcaption>a code extracting the overall rating of each book</figcaption></figure><p>We will then scrap the total number of people who actually reviewed the book for rating</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kljj3xqbZ-DNdrsz8IuYoQ.png" /><figcaption>a code for scrapping the number of people who reviewd the book</figcaption></figure><p>We will then scrap the type of book type :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4CZSl2n9qJy_uhJgVnWPg.png" /><figcaption>a code to scrapp the book type</figcaption></figure><p>We will finally scrap the price of each book</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0xblGML_CPIE2X5SrH0Uw.png" /><figcaption>scrapping the book type</figcaption></figure><p>we will be scraping multiple pages so we will need to click the next button on the webpage upto the 50th page the entire code looks as the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yl4LeQBfDcY-FZ-d34eiWA.png" /><figcaption>whole code</figcaption></figure><p>After have extracted the pages we will vary the number of pages we want to scrap depending on the requirements.We will need to create a dataframe and for this particular code we will save in a file called ‘Books.csv in the downloads folder in our pc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xklu3LsRPQRziYDvLPdeeA.png" /></figure><p>we can look at our dataframe and inspect whether we have all the values in our new file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzM8tlYlHJYqol4JIGKUqQ.png" /></figure><p>We can actually seee we have scraped all the data for some pages .<em>The process of scrapping data is often tideous but this is the simplest it can ever be.</em></p><blockquote>This is a whole model showing actually how to scrap the data and <strong>in the next workbook we will be completing the end to end project where we will be creating a Book reccommendation model . for the whole code here is my </strong><a href="https://github.com/stilinsk"><strong>Github account</strong></a><strong> and to this </strong><a href="https://github.com/stilinsk/amazon-books-webscrapping-using-selenium"><strong>project</strong></a><strong> . See you in the nextbook reccommendation article</strong></blockquote><blockquote>follow for more</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ef04d731d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>