<?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 Adekolu Peter on Medium]]></title>
        <description><![CDATA[Stories by Adekolu Peter on Medium]]></description>
        <link>https://medium.com/@peteradekolu?source=rss-24e291fa00a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CvkOcoaukZGUTtbj9u39nw.jpeg</url>
            <title>Stories by Adekolu Peter on Medium</title>
            <link>https://medium.com/@peteradekolu?source=rss-24e291fa00a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:18:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peteradekolu/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[Mastering Complex SQL Challenges: Solving LinkedIn’s Budget Risk Assessment Problem]]></title>
            <link>https://peteradekolu.medium.com/mastering-complex-sql-challenges-solving-linkedins-budget-risk-assessment-problem-21f0abfaeecc?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/21f0abfaeecc</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[complex-sql]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 09:29:43 GMT</pubDate>
            <atom:updated>2023-08-07T09:29:43.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjof22tzUDZRNhe6Ho6N9A.png" /><figcaption>Image Source: LinkedinLearn</figcaption></figure><p>Hello everyone,</p><p>It’s been a while, but I’ll like to share an interesting problem statement with you. This particular challenge stems from a Linkedin SQL interview question as presented by <a href="https://platform.stratascratch.com/coding?code_type=5">Stratascratch</a>.</p><p><strong>Problem Statement:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAU-DevUAHfa5yZcM_-G1w.png" /></figure><p>Now, imagine your boss assigns you a task: identify projects that are at risk of exceeding their budgets. In essence, a project is considered at risk if the total expense incurred for the project surpasses the allocated budget. To calculate this, we consider the expense to be the total salaries disbursed to employees relative to the project’s duration.</p><p>For instance, if a project has a budget of $10,000 and takes six months to complete, the combined salaries of all employees on the project over that six-month period should not exceed $10,000. If it does, the project is flagged as being at risk of going over budget.</p><p><strong>Implementation:</strong></p><p>To tackle this challenge, we have a set of tables : “Linkedin_projects,” “linkedin_emp_projects,” and “linkedin_employee.” These tables hold information such as project IDs, project names (titles), budgets, start and end dates, employee IDs, and salaries.</p><p>Given these tables and their relationships, we need to join them to create a merged table that provides details about each project’s total expense, budget, and duration. To achieve this, we perform a series of table joins.</p><p>We start by joining the “linkedin_projects” and “linkedin_emp_projects” tables based on the “project_id” foreign key. Next, we join the “linkedin_emp_projects” table with the “linkedin_employee” table using the “emp_id” foreign key.</p><p>Here’s the initial SQL code for these joins:</p><pre>SELECT<br>    lp.id AS project_id,<br>    lp.title AS project_name,<br>    SUM(le.salary) AS total_salary,<br>    lp.budget AS budget,<br>    DATEDIFF(&quot;day&quot;, lp.start_date, lp.end_date) AS project_duration<br>FROM<br>    linkedin_projects lp<br>JOIN<br>    linkedin_emp_projects lep ON lp.id = lep.project_id<br>JOIN<br>    linkedin_employees le ON lep.emp_id = le.id<br>GROUP BY<br>    lp.id, lp.title, lp.budget, lp.start_date, lp.end_date;</pre><p>In this code, we use the SUM() function to aggregate employee salaries for each project. However, we don&#39;t aggregate the project budget, as it is fixed.</p><p>Executing the above code yields a result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWupH5gExF2nVHx-0NcVaw.png" /><figcaption>Sample Output</figcaption></figure><p>At this point, the “total_salary” column in the result represents the combined yearly salaries of all employees on each project. To determine the project’s expense, which is the total employee salary relative to the project’s duration, we introduce a subquery. For instance, the expense for “project1” is calculated as (total_salary * project_duration) / 365.</p><p>Here’s the code for the subquery:</p><pre>select project_name, budget, <br>ROUND((CAST(total_salary as float) * <br>CAST(project_duration as float))/365, 0) as prorated_employee_expense<br>FROM (<br>    -- Previous code for joining tables and calculating total_salary and project_duration<br>) AS ProjectDetails;</pre><p>Within the subquery, we cast the total salary and project duration as float data types to ensure precision. We also use the ROUND() function to round the prorated employee expense to the nearest dollar as it was required in the problem statement.</p><p>Executing the subquery provides a result similar to the previous output, now including the prorated employee expense alongside the project budget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB3qqTlJOUqiB6kw96b75Q.png" /><figcaption>Sample Output</figcaption></figure><p>With this progress, we’re 90% closer to solving the problem. To identify projects where the prorated employee expense exceeds the budget, we encapsulate the subquery within a Common Table Expression (CTE) and filter the results using a WHERE clause which led to this whole query and output:</p><pre>with risky_projects_cte  as (<br>select project_name, budget,<br>    ROUND((CAST(total_salary as float) * <br>    CAST(project_duration as float))/365, 0) as prorated_employee_expense<br>from<br>(<br>select lp.id as project_id, <br>lp.title as project_name, <br>sum(le.salary) as total_salary, <br>lp.budget as budget, <br>datediff(&quot;day&quot;, lp.start_date, lp.end_date) as project_duration<br><br>from linkedin_projects lp<br>join linkedin_emp_projects lep<br>on lp.id = lep.project_id<br>join linkedin_employees le<br>on lep.emp_id = le.id<br>group by lp.id, lp.title, lp.budget, lp.start_date, lp.end_date) project_details<br><br>)<br><br>select * from risky_projects_cte <br>where prorated_employee_expense &gt; budget<br>order by project_name</pre><p>Sample Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffscjB5R4ZtRHI6_uzOB5w.png" /></figure><p>And voilà — the problem is solved! Kudos to <a href="https://platform.stratascratch.com/coding?code_type=5">Stratascratch</a> platform for providing intriguing SQL challenges particularly from top companies. They also offer Python problems, which I’m eager to explore soon. Feel free to reach out to me on <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/">LinkedIn</a> if you have questions or suggestions for solving this problem or general questions. You can also reach out to me via <a href="http://peteradekolu@gmail.com/">email</a>. I hope you’ve gained a grasp of the entire approach. You can explore my other solutions to SQL problems <a href="https://medium.com/me/stories/public">here</a>. Stay tuned for more exciting problems we’ll explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21f0abfaeecc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JOIN ME IN SOLVING A META/FACEBOOK SQL INTERVIEW QUESTION]]></title>
            <link>https://peteradekolu.medium.com/join-me-in-solving-a-meta-sql-interview-question-27d715a061fc?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d715a061fc</guid>
            <category><![CDATA[hackerrank-solution]]></category>
            <category><![CDATA[facebook-interview]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[subquery]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 15:44:27 GMT</pubDate>
            <atom:updated>2023-07-25T15:45:09.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings, my fellow SQLNinjas! Once again, I’m thrilled to join you on another exciting journey to tackle an intriguing problem, this time with T-SQL. Oh, but there’s a twist! We’re diving into a challenge from the big leagues — <a href="https://en.wikipedia.org/wiki/Meta_Platforms">Meta/Facebook,</a> as presented by <a href="https://platform.stratascratch.com/coding?code_type=5">Stratascratch.</a></p><p>Our problem is to calculate each user’s average session time, defined as the time difference between a page_load and page_exit. Don’t fret; we’ll break it down into manageable steps, and soon it’ll all make perfect sense. Imagine yourself as a user loading a webpage for the first time, spending a few moments reading the content, and then gracefully exiting the page.</p><p>Now, picture this: you loaded the page at a specific time, right? Later, you exited the page at another time. In this problem, a session is precisely the time difference between your exit and load events. Simple enough! But hold on, there’s more. A user can only have one session per day, even if they visit the page multiple times. So, we’ll consider only the earliest load time and the latest exit time for each day as the user’s session.</p><p>With that understanding, let’s move on to the exciting part — solving the problem! We’ll be working with a table called facebook_web_log, containing user_id, timestamp, and action columns that indicate page_load and page_exit events. Our goal is to find the average session time for each user.</p><p>Sample Table Preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W471KA450-zdjN3KtecA1Q.png" /></figure><p>Imagine our output sample showcasing the user_id and their average session time in seconds:</p><pre>user_id | Average_Session_Time (seconds)<br>------- | ------------------------<br>0       | 750<br>1       | 40</pre><p>To get here, we’ll follow a logical flow, breaking the problem down step-by-step:</p><ol><li>Find the user’s session time for each day.</li><li>Calculate the average session time for each user.</li></ol><p>In our facebook_web_log table, we&#39;ll create two separate tables using common table expressions (CTEs) to help us along the way. The first one, PAGE_LOAD_TABLE,will store the maximum page_load time for each user per day using the MAX() function. Similarly, PAGE_EXIT_TABLE will hold the earliest page_exit time for each user per day using the MIN() function.</p><p>We can create these tables using the following T-SQL code:</p><pre>    --FOR THE PAGE LOAD TABLE<br><br>    WITH PAGE_LOAD_TABLE AS (<br><br>    SELECT user_id, part_date, max(timestamp) as max_page_load<br>    from<br>    (SELECT user_id , CAST(timestamp as DATE) as part_date, timestamp <br>    from facebook_web_log <br>    where action = &#39;page_load&#39;<br>    group by user_id, timestamp) pl_table<br>    group by user_id, part_date<br><br>    ), <br><br>    --FOR THE PAGE EXIT TABLE<br><br>    PAGE_EXIT_TABLE AS (<br>    (SELECT user_id, part_date, min(timestamp) as min_page_exit<br>    from<br>    (SELECT user_id, CAST(timestamp as date) as part_date, <br>            timestamp <br>    from facebook_web_log<br>    where action = &#39;page_exit&#39;<br>    group by user_id, timestamp ) pe_table<br>    group by user_id, part_date )<br>    )</pre><p>Finally, to obtain the user’s session time for each day, we’ll combine these derived tables using a join on user_id and part_date. This allows us to access all necessary columns in one table and easily find the time difference between the min_page_exit column and max_page_loadcolumn.</p><p>As we’re almost done, we’ll make use of the AVG() function to calculate the average session time for each user, which can be created using the codes below:</p><pre>--CALCULATING THE USER-AVERAGE SESSION(DIFFERENCE OF page_load and page_exit) <br><br>SELECT pl.user_id,AVG(CAST(DATEDIFF(second, pl.max_page_load, pe.min_page_exit) AS FLOAT))<br>FROM page_load_table pl<br>join page_exit_table pe<br>on pl.user_id = pe.user_id<br>and pl.part_date = pe.part_date<br>group by pl.user_id<br></pre><p>Here’s the final code snippet that brings it all together and there you have it the final solution to our problem — the average session time per user.</p><pre>--FOR THE PAGE LOAD TABLE<br><br>WITH PAGE_LOAD_TABLE AS (<br><br>SELECT user_id, part_date, max(timestamp) as max_page_load<br>from<br>(SELECT user_id , CAST(timestamp as DATE) as part_date, timestamp <br>from facebook_web_log <br>where action = &#39;page_load&#39;<br>group by user_id, timestamp) pl_table<br>group by user_id, part_date<br>    ), <br><br>--FOR THE PAGE EXIT TABLE<br><br>PAGE_EXIT_TABLE AS (<br>(SELECT user_id, part_date, min(timestamp) as min_page_exit<br>from<br>(SELECT user_id, CAST(timestamp as date) as part_date, timestamp <br>from facebook_web_log<br>where action = &#39;page_exit&#39;<br>group by user_id, timestamp ) pe_table<br>group by user_id, part_date )<br> )<br>    <br>--CALCULATING THE USER-AVERAGE SESSION(DIFFERENCE OF page_load and page_exit) <br><br>SELECT pl.user_id,AVG(CAST(DATEDIFF(second, pl.max_page_load, pe.min_page_exit) AS FLOAT))<br>FROM page_load_table pl<br>join page_exit_table pe<br>on pl.user_id = pe.user_id<br>and pl.part_date = pe.part_date<br>group by pl.user_id</pre><p>I hope you enjoyed our problem-solving approach as much as I did share it with you. But wait, I’m eager to hear what you think! Feel free to access the question <a href="https://platform.stratascratch.com/coding/10352-users-by-avg-session-time?code_type=5">here</a> (if you already have a <a href="https://www.stratascratch.com/blog/categories/sql/">Stratascratch</a> account) and give it a try yourself.<br>If you have any questions, suggestions, or tips to share, I’d be delighted to connect with you on <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/"><em>LinkedIn</em></a><em> </em>or <a href="http://peteradekolu@gmail.com/"><em>Gmail</em></a>. Your feedback means a lot to me, and together, we can learn and grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d715a061fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving a Tricky HackerRank SQL Problem — Combining Queries with ORDER BY]]></title>
            <link>https://peteradekolu.medium.com/solving-a-tricky-hackerrank-sql-problem-combining-queries-with-order-by-fea42d7bc085?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea42d7bc085</guid>
            <category><![CDATA[subquery]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[order-by-in-sql]]></category>
            <category><![CDATA[hackerrank-solutions-sql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 17:00:01 GMT</pubDate>
            <atom:updated>2023-07-20T18:38:09.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving a Tricky HackerRank SQL Problem — Combining Queries with ORDER BY</h3><p>Hey there, fellow Data Folks and SQL Ninjas! Today, I want to share a simple solution to a challenging <a href="https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true">Hackerrank</a> problem using MySQL.</p><p>The problem involves querying a list of all names in the “OCCUPATIONS” table, along with the first letter of each profession in parentheses. <br>For instance, “AnactorName(A)”, “ADoctorName(D)”, and so on.</p><p>Additionally, we need to find the number of occurrences of each occupation in the “OCCUPATIONS” table and display the results in this format: “There are a total of 2 doctors” or “There are a total of 2 singers.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix6va6GbSBvYHnikxgck_A.png" /><figcaption>Snapshot of the problem statement and SQL code.</figcaption></figure><p>To achieve this, we must create two separate queries and then combine them. I immediately knew the UNION keyword would come in handy for merging the results. So, let’s dive into the step-by-step process:</p><p>Step 1: Crafting the First Query To start, we focus on the first query. It requires extracting both the name and the first letter of each occupation. Here’s how I achieved that:</p><pre>SELECT CONCAT(NAME, &quot;(&quot;, LEFT(OCCUPATION, 1), &quot;)&quot;) AS NAMEOCC<br>FROM OCCUPATIONS;</pre><p>The “ LEFT(OCCUPATION, 1) ” function extracts the first letter from the OCCUPATION column, while the “ CONCAT()” function beautifully joins the name, the opening parenthesis, the first occupation letter, and the closing parenthesis into a single string.</p><p>Step 2: Joining with the Second Query Next, we combine the first query with the second one using “ UNION “. Here’s what the second query looks like:</p><pre>SELECT CONCAT(&quot;There are a total of &quot;, COUNT(OCCUPATION), &quot; &quot;, LOWER(OCCUPATION), &quot;s.&quot;) AS NAMEOCC<br>FROM OCCUPATIONS<br>GROUP BY OCCUPATION;</pre><p>This query skillfully enables us to achieve the desired output format, such as “There are a total of 2 doctors.”</p><p><strong>The Tricky Part:</strong> Sorting! Now comes the tricky part. The first query should be sorted alphabetically, and the second query must be ordered by occupation count in ascending order. But what if multiple occupations have the same count? They should be sorted alphabetically as well.</p><p>At first, using “ ORDER BY “ in both queries might seem like the obvious solution, but it wouldn’t yield the expected result. This is because ORDER BY in SQL is executed after the whole query result is retrieved, meaning it won’t work correctly in <a href="https://www.tutorialspoint.com/sql/sql-sub-queries.htm">subqueries</a> or <a href="https://learnsql.com/blog/what-is-common-table-expression/">CTEs</a>. Using ORDER BY in a derived table can even cause an error in <a href="https://www.sqlservertutorial.net/">SQL SERVER.</a></p><p>To overcome this challenge, I gave both queries the same alias, “NAMEOCC ”, in the subquery. By doing so, I merged the results horizontally into a single row. Now, querying the alias “ (NAMEOCC) “ in the subquery returns both queries’ results merged together. Finally, we can order our merged query results in ascending order, achieving both alphabetical sorting and ascending occupation count sorting.</p><p>Here’s the combined query with ORDER BY:</p><pre>SELECT NAMEOCC FROM<br>(<br>(SELECT CONCAT(NAME,&quot;(&quot;, LEFT(OCCUPATION, 1), &quot;)&quot;) AS NAMEOCC<br>FROM OCCUPATIONS)<br>UNION <br>(SELECT CONCAT(&quot;There are a total of &quot;, COUNT(OCCUPATION), &quot; &quot;,<br>LOWER(OCCUPATION), &quot;s.&quot;) AS NAMEOCC<br>FROM OCCUPATIONS<br>GROUP BY OCCUPATION)<br>) SUB_1<br>ORDER BY 1;</pre><p>I admit, it took some clever thinking to solve this puzzle, and I’m sure there are other fantastic ways to approach it using SQL. So, if you have any suggestions or tips, I’d be thrilled to learn from you!</p><p>In conclusion, I hope you enjoyed following my journey in solving this tricky HackerRank SQL problem. You can access the problem on <a href="https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true">Hackerrank</a> if you already have an account. Stay tuned as I’ll share more of my approaches to SQL problems on <a href="http://hackerrank.com/">Hackerrank</a> and <a href="https://www.stratascratch.com/">Stratascratch</a> soon.</p><p>Thank you for joining me on this adventure, and happy coding! You can connect with me on <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/">Linkedin</a> or reach out to me through <a href="http://peteradekolu@gmail.com/">Gmail</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea42d7bc085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tackling Health Crisis In Africa]]></title>
            <link>https://peteradekolu.medium.com/tackling-health-crisis-in-africa-d0e0f0e375b2?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0e0f0e375b2</guid>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 16:07:30 GMT</pubDate>
            <atom:updated>2023-03-30T16:44:58.003Z</atom:updated>
            <content:encoded><![CDATA[<p>I decided to present a solution on a hackathon organized earlier this year by <a href="http://10alytics.io/">10Alytics</a>, a data and strategy company, and the hackathon was focused on the theme “Tackling the health crisis in Africa”. My contribution to the project involved conducting a comprehensive analysis to derive insights and findings on the factors affecting the health crisis in Africa. The aim was to provide the right solutions and recommendations to address the crisis.</p><p>To carry out the analysis, I utilized Microsoft Power BI for the entire project, including data cleaning, modeling, analysis, and visualization. The dashboard images below showcase the results of my analysis. You can also interact with the dashboard by clicking the link provided:</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiOGUzMjc3Y2UtNDU1OC00YTIxLThlZTYtOGJkNWNkMzlmNWVhIiwidCI6IjI4ZDQ3YTZjLWE2NmQtNDk1Ni1iYTdlLTU0MDg0Mjk0NzNmOSJ9">Power BI Report</a></p><figure><img alt="Overview Report" src="https://cdn-images-1.medium.com/max/1024/1*GhKd3cnvZa2Tu_qz62Lluw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AslmAPEKNc2IStCb5yXIog.png" /></figure><p><strong>N.B:</strong> Please note that all visuals related to the Crude Mortality Rate and Medical Personnel are measured per 100,000 population. Specifically, the Crude Mortality Rate represents the number of deaths per 100,000 people, while Medical Personnel refers to the number of healthcare workers per 100,000 of the country’s population.</p><p><strong>Dataset Overview</strong></p><p>There were six datasets provided for this project. They are as follows: <br>1. Causes of Deaths : This indicates the number of deaths and the causes across different countries from 1990 to 2019<br>2. Number of Deaths by Age Group: This indicates the number of deaths by Age Group across different countries from 1990 to 2019. <br>3. Medical Doctors per 10,000 population : This indicates the number of medical doctors per 10,000 population in Africa. <br>4. ISO 3166_Country-and-continent-codes-list-csv: This contains the list of sovereign states and dependent territories by continent describing the list of countries by continent. <br>5. World Population: This indicates the data from United Nation Population Division across countries over the last century. <br>6. Health Expenditure (% of GDP) : This data contains countries expenditure on health as a percentage of GDP</p><p><strong>Data Preparation</strong></p><p>I imported all the datasets into power query, where I cleaned all the data. These were common steps I took in cleaning each of the dataset.</p><ol><li>As some datasets contained information on countries outside of Africa, I filtered out those rows and kept only the rows that pertain to African countries. This was done to avoid redundancy in the data.</li><li>After filtering out non-African countries, I noticed that some entries in the numerical datatype column contained null values. Since these null values are known to represent empty data, I replaced them with 0, rather than removing those rows entirely and losing valuable data.</li><li>To ensure clarity when creating measures, I renamed necessary columns.</li><li>I removed duplicates from all the tables.</li><li>I filtered the tables to display data from the years 2000 to 2019, as this time range is the most consistently shared range among all the tables.</li><li>I merged the tables with the “ISO 3166_Country-and-continent-codes-list-csv” table on the 3-letter country code- (A column that contains unique code for each country name) in order to have only African countries in the tables and to ensure the tables have the same country names. This step will also help in the data modeling because the “ISO 3166_Country-and-continent-codes-list-csv” will server as a dimension table as it contains all African unique country names and codes.</li><li>To avoid having excessively long table names that occupy too much space when creating DAX measures, I renamed some of the tables. For instance, the original name of the “ISO 3166_Country-and-continent-codes-list-csv” table seemed too long, so I changed it to “Dim_Country”.</li></ol><p>N.B: These are few cleaning steps common in each of the tables, These are not entirely all the steps I took in cleaning the data.</p><p><strong>DATA MODELING</strong></p><p>I created a calendar table in Power Query that ranges from the year 2000 to 2019, as I mentioned earlier. I used this year range because it is the most consistent range in each of the tables. I would like to have a date/calendar table and a dimension country table that will have a one-to-many relationship with the remaining tables, as all the remaining tables are fact tables and they all have a date column and a country code. Therefore, when writing DAX measures and creating visualizations, I can use a table from which to pull date columns and country columns. Below is a screenshot of the data model, which has a star schema structure. The screenshot below shows the data model in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nw0avNuu_69UTHEU2r_ng.png" /></figure><p><strong>FINDINGS</strong></p><ol><li>Lesotho, Eritrea, and Somalia had the highest crude mortality rates among all countries, with approximately 1437, 1217, and 1035 deaths per 100,000 population, respectively. In contrast, Mauritania, Algeria, and Sudan had the lowest crude mortality rates, with approximately 460, 450, and 424 deaths per 100,000 population, respectively.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*UBJ7tPjn0x1urNJeQdjZ3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*6C2VKyhPqS3iGJf2F0Tybw.png" /></figure><p>2. I observed that Sierra Leone, Namibia, South Africa, Burundi, and Lesotho were the top five countries that spent the highest percentage of their GDP on healthcare. Interestingly, none of these countries were among the countries with the lowest mortality rates. In fact, Lesotho, which was one of the top countries for healthcare spending, had the highest mortality rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Ps-ZvlbYOXVY1L-1bQ-cMQ.png" /></figure><p>3. The top 5 Countries with the highest population are Nigeria, Ethiopia, Egypt, Tanzania and Kenya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*VzPHFK2tpZWtZ34fevs7PA.png" /></figure><p>4. After exploring the crude mortality rate by age group, it was found that the “Under 5” age group had the highest rate. This may be attributed to the weaker immune systems in young children, which make them more susceptible to neonatal disorders, lower respiratory infections, and diarrheal diseases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*6mQazXCvgNs0fodfKL3nQg.png" /></figure><p>5. Cardiovascular diseases, neonatal disorders, and lower respiratory infections are the three leading causes of death, with crude mortality rates of approximately 145, 73, and 65 deaths per 100,000 population, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*obKe7v9dKt5s-D7tOYP4jg.png" /></figure><p>6. Out of the countries included in the study, Mauritius, Seychelles, and Algeria had the highest number of medical doctors per 100,000 population, with 2806, 1463, and 603 doctors respectively. On the other hand, Ethiopia, Tanzania, and Liberia had the lowest number of medical doctors per 100,000 population, with only 20, 14, and 15 doctors respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*RwFR9mD0E8DAjor8BqDvpg.png" /></figure><p><strong>KEY INSIGHTS</strong></p><ol><li>The crude mortality rate has steadily declined from 2000 to 2019, and this indicates an increase in preventive measures to reduce mortality.</li><li>Between 2000 and 2019, there was a gradual decrease in crude mortality rates across all age groups.</li><li>The African population has steadily increased over the years, reaching its highest recorded level of 1.11 billion in 2019.</li><li>The trend of health GDP was erratic, with the highest growth rate occurring in 2009. However, it experienced a slow decline from 2015 until the end of the year.</li><li><strong>.</strong> Between 2001 and 2002, medical personnel saw a massive increase in numbers, with a growth rate of 2202.24% compared to the previous year.<br><strong>.</strong> The trend continued in an irregular manner until another sharp increase of 779.4% was observed between 2015 and 2016.<br><strong>.</strong> However, between 2018 and 2019, there was a significant decline in the number of medical personnel, with a growth rate of -79.29% compared to the previous year.</li></ol><p><strong>RECOMMENDATIONS</strong></p><ol><li>We observed that children under the age of five have the highest mortality rates, often due to inadequate healthcare. It’s clear that we need more pediatricians to take care of these children, especially in rural areas where diseases are more prevalent. We urge the government to provide more free healthcare services to these areas and raise awareness among mothers about preventative measures they can take to protect their children from contracting these diseases. By investing in these measures, we can significantly reduce the suffering and mortality rates of young children.</li><li>Countries with high mortality rates such as Lesotho, Eritrea and Somalia need to invest more in their healthcare and healthcare facilities, increasing the number of medical professionals. Also, support from international organizations such as the World Health Organization (WHO) can be requested.</li><li>While healthcare spending serve as a major factor, it’s not always directly related to lower mortality rates. Countries like Lesotho, as we observed earlier spend a high percentage of their GDP on health care, but still experience high mortality rates, should reevaluate their health care systems to detect inefficiencies and areas that require support.</li><li>Countries with low numbers of medical doctors such as Ethiopia, Tanzania, and Liberia should invest in training and educationg more medical professionals to help this shortage. <br>Measures such as offering incentives to encourage more individuals study medicine can be implemented, and international organizations can provide support in terms of resources and training programs.</li><li>Efforts to reduce the mortality rates such as vaccination programs, seminars to increase awareness of risk factors should be focused on addressing the leading causes of death such as cardiovascular diseases, neonatal disorders and lower respirator infections.</li><li>Top populous countries such as Nigeria, Ethiopia, Egypt, Tanzania and Kenya should review their health systems to ensure they are capable of meeting the demands of their population.</li></ol><p>I thoroughly enjoyed working on this challenging project, particularly when writing complex DAX measures. It was all worth it in the end, as we were able to generate valuable insights. Once again, You can interact with the dashboard <a href="https://app.powerbi.com/view?r=eyJrIjoiOGUzMjc3Y2UtNDU1OC00YTIxLThlZTYtOGJkNWNkMzlmNWVhIiwidCI6IjI4ZDQ3YTZjLWE2NmQtNDk1Ni1iYTdlLTU0MDg0Mjk0NzNmOSJ9">here</a>. I’d like to extend my appreciation to 10alytics for hosting this exciting hackathon.<br>Also, If you enjoyed this article and would like to share suggestions, you can connect with me on <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/">Linkedin</a> and <a href="https://twitter.com/savepeter2">Twitter</a> 😅. You can also check out my other projects on my <a href="https://github.com/savepeter2">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0e0f0e375b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of Gender Classification Project With Tensorflow Serving]]></title>
            <link>https://peteradekolu.medium.com/deployment-of-gender-classification-project-with-tensorflow-serving-c1b77ba51625?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1b77ba51625</guid>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 11:39:24 GMT</pubDate>
            <atom:updated>2021-03-22T11:39:24.304Z</atom:updated>
            <content:encoded><![CDATA[<p>Initially, I knew nothing about Tensorflow Serving, probably because it isn’t so popular as the other tools used in deploying like Heroku, Flask e.t.c, I haven’t even heard of it or seen it before in the first six months I’ve gotten into machine learning. One night, my friend just hit me up asking if I’ve heard of it or have made use of it before when deploying, I was like “Noo..at all, I’ve not even heard of it” and told him he can always google search, make researches and all.</p><p>About a week later, he landed his first paid job as an intern DevOps Engineer through deploying one of his latest project using Tensorflow Serving and he also wrote an article on it. I was so thrilled and excited for him, which led to my interest in Tensorflow serving. Well, I suggest our minds should always be prepared for inspiration from a lot of ways, Now let’s explore what this Tensorflow Serving really does.</p><p>We successfully trained our model in the previous article and this time, we are bringing the model into production and making it available for real-life applications because a model without deployment is like keeping a portion of food on the table without eating it. The food solves your problem of being hungry same as the way the model solves real-life cases. There are several tools used in deploying, you can use Docker, Flask, Heroku e.t.c. which you can also explore and apply in various use cases. Each of them has its uniqueness and usefulness as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*1-A9SK7xY2wN5t1CsRDp3A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhQo1Q8paxXYdQkhsWH7nw.jpeg" /></figure><p>Serving is how you apply a machine learning model after you’ve trained.</p><p><strong>Tensorflow Serving</strong></p><p>Tensorflow serving makes the process of taking the model into production easier and faster. It allows you to safely deploy the models and run experiments while keeping the same architecture and APIs. Out of the box, it provides integration with Tensorflow and can serve other types of models also. Tensorflow Serving is also part of TFX Extended, Simply, TFX Extended is an API designed to make production-ready and build machine learning systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7YhftpytRlg0wslxy_yqQ.png" /></figure><p>This is a sample preview of all the processes required for a successful machine learning system, so let’s say we want to run our models on a mobile phone, embedded systems, or on the web, we could simply use TF lite for the mobile or create javascript version of the model and run it on the web, It is actually a better idea to have a centralized model where you can simply send a response on a device, the server will then execute and return back to the device. The diagram is as shown below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTjTOeQRj_D1yjBj5q_YOQ.jpeg" /></figure><p>Tensorflow serving also provides an easy and friendly customer experience to the systems/apps because once the model is updated, the server and the device get instant access to it efficiently without crashing or damaging the server. This creates an automated process between the model, serving device and most importantly avoids an absurd customer experience. For instance, sending app updates when the user is using the outdated version of the app compared to when the app automatically updates and gets immediate access to the server. So let’s see how we successfully deployed this project with tensorflow serving below: In order to load a trained model into the tensorflow server, we need to save our model to a “savedmodel” format which will create a “protubuf” file in a well-defined directory heierachy, and will include a version number. Tensorflow Serving allows us to select a version of a model “servable”, which we’ll make inference requests. Each version of the model will later be saved into a different sub-directory under the given directory. The code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href">https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href</a></iframe><p>We can now check the MetaGraphDefs i.e the models and the SignatureDefs(the method you can call in our saved model) by executing this command code, it is like showing the entire history of the saved model :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6b8467a63dc4af36aa6afebf91d73b/href">https://medium.com/media/0d6b8467a63dc4af36aa6afebf91d73b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XY2fdCdK9G8v-vjfyf76Yg.jpeg" /></figure><p><strong>Serve The Model With Tensorflow Serving :</strong></p><p>First we start by adding the tensorflow serving distribution source as a package URL : We’re preparing to install TensorFlow Serving using Aptitude since this Colab runs in a Debian environment. We’ll add the tensorflow-model-server package to the list of packages that Aptitude knows about. Note that we’re running as root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f93e97687132c9c73801c624d31b979/href">https://medium.com/media/0f93e97687132c9c73801c624d31b979/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVVpuLcifAkLK4N82WVQ-Q.jpeg" /></figure><p>Then we install the tensorflow server :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35d98b188e27ecd42fd6d5e8c1b7c681/href">https://medium.com/media/35d98b188e27ecd42fd6d5e8c1b7c681/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHBRFlB5SJHh2trQR_E8Tg.jpeg" /></figure><p>Now let’s load the tensorflow serving below, we’ll break down the lines of code and the parameters used here :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aae13bb1e5968f8bb521ac4f4bc5c4c/href">https://medium.com/media/6aae13bb1e5968f8bb521ac4f4bc5c4c/href</a></iframe><p>This is where we’ll load the model, run our TensorFlow serving, make inference requests using REST. So the third line of the codes above tells it to use tensorflow serving, and I included the bash magic cell at line 2 because I made use of google colab during the project N.B if you’re using a different IDE e.g jupyter notebook, spyder e.t.c. you don’t need to include line 2 because colab doesn’t provide a direct terminal while these IDE’S does.</p><p>The third line tells it to use the tensorflow model server, and the required paremeters are stated in the fourth, fifth, sixth line respectively as explained below:</p><ol><li>rest_api_port: This is the port we’ll use in making our inference requests to run the tensorflow model server. Pretty direct yeah?</li><li>model_name: This the URL we’ll set at the inference requests, you can choose any name for it. A thing to note is that the — model_name will also appear in the URL on which you will be serving your models, so if you have multiple models at action managing your serving model URLs also becomes a lot easier.</li><li>model_path: This is the path to the directory/location where the model is saved. The last line here specifies that you want to enable logging and sometimes logs are just so helpful while debugging. I have personally used them quite a lot to figure out errors easily.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/600fcb1974333a95293c7e7cd1af6528/href">https://medium.com/media/600fcb1974333a95293c7e7cd1af6528/href</a></iframe><p>Now we’ve successfully loaded the TensorFlow serving and we’re getting to a very interesting part which is performing inference requests. Now we make a request to our Model In Tensorflow Serving: First, let’s quickly get a sample of an image in the test data :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e5f6cc3e01b68d0fecf75b0860b3ea/href">https://medium.com/media/50e5f6cc3e01b68d0fecf75b0860b3ea/href</a></iframe><p>Output Image :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*acWZ8kltQoCTDsDMv4wC0Q.jpeg" /></figure><p>He is so cute yeah *winks*? , Let’s move on to the next step where we’ll create JSON object for a batch of three inference requests and let’s see how our model recognizes things.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae35a4c24295fe71420e2f14bfb353c4/href">https://medium.com/media/ae35a4c24295fe71420e2f14bfb353c4/href</a></iframe><p>Now we have gotten to the final part of the deployment, which is invariably the testing part of our model i.e how well our model will perform and recognize the objects. We’ll send a predict request as a POST to our server’s REST endpoint, and pass it three examples. We’ll ask our server to give us the latest version of our servable by not specifying the version :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3303cf5f54f92ef3e8ed1eb1cdeefc27/href">https://medium.com/media/3303cf5f54f92ef3e8ed1eb1cdeefc27/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Uu7pwarlGmj_TKx-PsrAQ.jpeg" /></figure><p>Now let’s specify a particular version of our servable. Since we only have one, let’s select version 1. We’ll also look at all three results below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3303cf5f54f92ef3e8ed1eb1cdeefc27/href">https://medium.com/media/3303cf5f54f92ef3e8ed1eb1cdeefc27/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nolWBqr9M0quTHPcBiQmhw.jpeg" /></figure><p>I guess the model didn’t classify Baby’s image correctly because,when we even consider real-life events, it’s not straightforward to tell whether a baby is a male or female from his/her facial look.But since it classified the remaining images correctly we’re good to go .</p><p>So we successfully built a model and deployed it using TensorFlow serving, You can still try out other techniques e.g vgg16, resnet50 or build your model from scratch as we did and I suggest you also try out various methods of improving the model for either binary or multi-label classification using CNN. We can also integrate this deployed model on a website, an application that will be user-friendly of course one will need to have a vast knowledge about the tools used in building the website or an application.</p><p><strong>CONCLUSION</strong></p><p>This article covers the deployment of the project on my previous article, Trust me it wasn’t easy coming up with this article, I hope you enjoyed this and could also gain some information. All the codes and files for this project are available here on my github repo: <a href="https://github.com/Savepeter2/Gender-Classification-Using-Keras-Tuner">Github</a> . If you found this article helpful, please do share it with your friends and leave a clap :-). If you have any queries, feedback or suggestions do let me know in the comments. Also, you can connect with me on <a href="https://twitter.com/SavePeter2">Twitter</a>, <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/">Linkedin</a>.There are also available resources online you can always read, watch and learn for you to understand better based on concepts like this. There is so much to share with all of you and I’m just getting started. Stay tuned for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1b77ba51625" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gender Classification Of Facial Images Using CNN In Python.]]></title>
            <link>https://peteradekolu.medium.com/gender-classification-of-facial-images-using-cnn-in-python-19fff3e986a?source=rss-24e291fa00a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/19fff3e986a</guid>
            <dc:creator><![CDATA[Adekolu Peter]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 09:33:34 GMT</pubDate>
            <atom:updated>2021-02-22T09:33:34.421Z</atom:updated>
            <content:encoded><![CDATA[<p>I was influenced in building this particular gender classification through facial image project because most times I find it very hard to tell a baby’s gender through their facial look and it really interests me , In fact not only a baby, Asian’s Male also , excluding their physical appearance , at times it might be quite difficult to tell whether he is a male or female from their look because they have this female-like look on their face . So i thought if i could build a model that will learn from thousands of images and efficiently predict gender , perhaps mimick we humans real-life high predictions . So let’s get straight to the project and give a brief discussion on Convolutional Neural Network applied to gender classification .</p><p>An approach using a convolutional neural network (CNN) is proposed for real-time gender classification based on facial images . The proposed CNN architecture exhibits a very much less complexity in its design compared to other CNN solutions when applied to pattern recognition. The number of processing layers in this CNN is reduced to just four only by stacking convolution and the sub-sampling layers . Unlike the conventional CNN’s we replace the convolutional operation by cross-correlation, thereby reducing the computational load.</p><p>The convolutional neural network is a neural network variants that consists of fused convolutional and sub-sampling layers which ends with one or more fully-connected layer in the standard multilayer perceptron (MLP). It can extract features, reduce data dimensionality, and classify simultaneously in one network structure.</p><p>Mankind is a great example of neural machine- in fact , We use our human brain as a the simplest lay man example when explaining how neural networks work. The fun of mankind nature is its ability of looking at multiple images simultaneously and processing them without knowing how the processing was done “God is the greatest” , But it is different with machines. Every image is a cummulative arrangement of dots(A pixel) in a special order , so a change in the order of the pixel leads to a change in the image.</p><p>There are three basic components of a convolutional layer :<br>1. Convolution layer<br>2. Pooling layer<br>3. Fully connected layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POkxbZDUEPT275z-j48rog.png" /></figure><p>So that’s a brief introduction on Gender Classification using convolutional neural network. Let’s get straight to our project.</p><p><strong>IMPORTING LIBRARIES</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c83a3f29b9ed91934a98d701e0b0ee67/href">https://medium.com/media/c83a3f29b9ed91934a98d701e0b0ee67/href</a></iframe><p><strong>Keras Tuner</strong> is a hyperparameter tuning technique which helps in determining the right no. of filters, filter size, learning rate, dropout e.t.c that helps the model and saves manually tuning of hyperparameters. Keras Tuner can also be integrated in ANN, CNN, RNN. it is not subjected to CNN alone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33bd3ca5c152dbf9bc946567165986c/href">https://medium.com/media/e33bd3ca5c152dbf9bc946567165986c/href</a></iframe><p>These are all the necessary libraries which will be required to successfully run all the codes that we we’ll be using in this project.</p><p><strong>IMPORTING DATASET</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8a840ee5148334832a4604bf244995/href">https://medium.com/media/8e8a840ee5148334832a4604bf244995/href</a></iframe><p>We have successfully imported our dataset to our colab notebook which was initially uploaded to google drive , So we mounted the drive on colab in order for colab to read and locate the dataset. The dataset can be gotten from Kaggle. This dataset resulted from various preprocessing and cleaning from the UTK dataset and many other datasets full of images. This dataset consists of 23, 705 grayscale facial images of humans based on age gender and ethnicity with each image having a resolution of 32 by 32 pixels. <br>Note : They are although images , they’re just loaded as numpy arrays and not binary image objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zv55xq2lqoX-RtmkT3a4w.jpeg" /></figure><p>Now we can see our dataset, we’re mainly interested in the third and last column for this project as they’ll serve as the label and image column respectively.</p><p><strong>EXPLORING THE DATA</strong></p><p>The pixels column in the dataset will serve as our main image column which should contain numpy arrays of pixels having 4-dimension resolution but each row pixels in this column are strings, So we are to convert each row to a numpy array and reshape into a four dimensional array. I created a function to convert each row to a numpy array and reshape the column into a four dimensional array (total length of rows, 32, 32, 1) : the length of rows implies the total number of the data of which in this scenario is 23,705 , 32 by 32 implies the height and width pixels, 1 indicates that it is a gray-scale image and it has only one channel, if it were an rgb image , it will have three channels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538ef34b0c30cddc35fa9a4ccc0be333/href">https://medium.com/media/538ef34b0c30cddc35fa9a4ccc0be333/href</a></iframe><p>So we further explored the data by visualizing the frequency of the two genders available in the data , we could infer that there are more male than female in the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad04f522f19b2001542e17b4f5f000c3/href">https://medium.com/media/ad04f522f19b2001542e17b4f5f000c3/href</a></iframe><p>Output is below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*VTt1lPJPLH898p2-goEC_A.png" /></figure><p>So now let’s split the dataset into X and Y ,which is our image data and label data respectively</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ab5815b2d0a38d26feaceb217701fd/href">https://medium.com/media/42ab5815b2d0a38d26feaceb217701fd/href</a></iframe><p>We proceed by splitting our data into training and testing sets , we also split the testing data with the cut size to get our validation sets, this will be achieved by using our train_test_split method as we choose a constant cut size (test size) in both cases from our sklearn library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b50eb91ec9300d0d0116d93d99944162/href">https://medium.com/media/b50eb91ec9300d0d0116d93d99944162/href</a></iframe><p>We need to be aware that in neural networks, Our labels have to be in vectorized form for us to get a better efficiency, that is the reason why we are using the to_categorical method from keras.utils library to change the labeled data to a categorical form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f334955d463054cb1b2e4f29023807a3/href">https://medium.com/media/f334955d463054cb1b2e4f29023807a3/href</a></iframe><p>So we continue our data preprocessing by now passing the trained,test,validation images set into the function I created previously.. As it will convert each row of the each of the three images sets data into an image representation of pixel data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be2da3713e6b5a62448a1be1151d341/href">https://medium.com/media/9be2da3713e6b5a62448a1be1151d341/href</a></iframe><p>Since the image data in train_images, test_images and val_images is from 0 to 255 , we need to rescale this from 0 to 1 . To do this, we need to divide the all the three sets of images by 255 . It’s important that the training set and the testing set be preprocessed in the same way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0fa0a46d0f2746cfef8bfcb28220e8a/href">https://medium.com/media/b0fa0a46d0f2746cfef8bfcb28220e8a/href</a></iframe><p>Let’s visualize few samples of the image data , which we’ll clearly see the real images we are talking about ,the images are in gray-scale form-Black and white .It is also a way to show and confirm that the data is ready to be trained .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7c8668f0b7d8c6af0529ba1842c228a/href">https://medium.com/media/b7c8668f0b7d8c6af0529ba1842c228a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*xz8_Vsnul2ewNzOdU5XPUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UitGuYIe23YrTWpDgLIlVg.jpeg" /><figcaption>Labeled Facial Images</figcaption></figure><p>Here are facial images wrangled, gotten from different data sources, featuring some celebrities that we’re familiar with e.g Will Smith, Kevin Hart. e.t.c</p><p><strong>DEFINE THE MODEL</strong></p><p>As you can observe from above that the images are in a Black and White format. Now the we just completed the preprocessing section and we’ll move on to our model training which requires it to be trained with CNN, and with the help of keras tuner, as I mentioned initially it will save us time in tuning our hyperparameters manually.. Here’s the link to the official documentation of the for further understanding on how it works <a href="https://keras-team.github.io/keras-tuner/">https://keras-team.github.io/keras-tuner/</a> . Here’s how to perform hyperparameter tuning for a single-layer dense neural network using random search:</p><p>First, we define a model-building function. It takes an argument hp from which you can sample hyperparameters, such as <a href="http://hp.int/">hp.Int</a>(‘units’, min_value=32, max_value=512, step=32) (an integer from a certain range).This function returns a compiled model.</p><p>This helps in selecting the best no. of filters from a range of values passed representing no. of filters. The same method also applies to the kernel size /filter size. We added another convolution layer to the network , followed by the keras.layers.Flatten layer which transform the 2-Dimensional images in a shape of 32 by 32 pixels into a 1-D array which will result to (32 * 32) 1024 pixels. The layer unstacks rows of pixels of images and lining them up as one single array. After the pixels are flattened, the network consists of a sequence of two keras.layers.Dense layers. These are densely connected, or fully connected, neural layers. Again, The dense layer nodes are determined by the hyperparameter passed in the RandomSearch library from the keras-tuner and relu activation function was used . The last dense layer is the output layer , since we’re predicting two classes, I used two nodes and sigmoid activation function which is used for binary classification.</p><p><strong>COMPILE THE MODEL</strong></p><p>Before the model is ready for training, it needs a few more settings. These are added during the model’s compile step:</p><p>Loss function — This measures how accurate the model is during training. You want to minimize this function to “steer” the model in the right direction. Here we will use “binary_categorical_crossentropy” Optimizer — This is how the model is updated based on the data it sees and its loss function. Metrics — Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe64345c953dd27d088df639d720b1bf/href">https://medium.com/media/fe64345c953dd27d088df639d720b1bf/href</a></iframe><p>Next,we instantiate a tuner. We specified the model-building function, the name of the objective to optimize (whether to minimize or maximize is automatically inferred for built-in metrics), the total number of trials (max_trials) to test, and the number of models that should be built and fit for each trial (executions_per_trial).</p><p>Available tuners are RandomSearch and Hyperband.</p><p>Note: the purpose of having multiple executions per trial is to reduce results variance and therefore be able to more accurately assess the performance of a model. If you want to get results faster, you could set executions_per_trial=1 (single round of training for each model configuration).In our case it was set to default (executions_per_trial = 1) .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a9a51dba1c448199078519aad9d8e7/href">https://medium.com/media/c3a9a51dba1c448199078519aad9d8e7/href</a></iframe><p>Then we start the search to pick the best hyperparameter configuration, the call to search has the same configuration as model.fit , Here’s what happens in search: models are built iteratively by calling the model-building function, which populates the hyperparameter space (search space) tracked by the hp object. The tuner progressively explores the space, recording metrics for each configuration. When search is over, we then retrieved the best model(s):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddc424ace0230157461b048a2005a25f/href">https://medium.com/media/ddc424ace0230157461b048a2005a25f/href</a></iframe><p>Thus , We already got our best model, This model will be used to train our images and labels, we can also concatenate the validation data to the images and labels in order to train our model on a larger dataset which will yield a better performance .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e057955fdd91ae242ce735dc27830c0e/href">https://medium.com/media/e057955fdd91ae242ce735dc27830c0e/href</a></iframe><p>Now we train our model on our final images and labels, and also specifying the initial and final epochs, the initial epochs was referenced during our search to pick the best hyperparameter configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b685040b5004a2a3f1046168247107/href">https://medium.com/media/31b685040b5004a2a3f1046168247107/href</a></iframe><p>Now i’ll like to show you the training process i got in order for you to confirm that the model is and acceptable there’s no underfitting or overfitting during the training process :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhZZvWHzEA7dRAI_RUwMsA.jpeg" /></figure><p>The model has finished training, and from final metrics we got ,it can be accepted because there’s no concept of overfitting or underfitting from the model training because the convergence difference in both pairs(accuracies and lossies) of metrics is not so large. We proceed to make predictions, accuracy, classification reports and save the model as an h5 file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4024d980e53022f1bce1963f1f0421f/href">https://medium.com/media/e4024d980e53022f1bce1963f1f0421f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e0f99d9704b82b8c7ea759d47617dd1/href">https://medium.com/media/9e0f99d9704b82b8c7ea759d47617dd1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21f739177816059456617365396d243/href">https://medium.com/media/c21f739177816059456617365396d243/href</a></iframe><p>The classification report below shows that i got a pretty good accuracy on the testing set , which was about 97%, i.e our model should perform very well when giving us back our response during deployment using tensorflow serving .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phYdo7S-s9p7onYml_gdmQ.jpeg" /></figure><p><strong>ERROR ANALYSIS</strong></p><p>Analyzing error visually helps in tuning image augmentation although we didn’t make use image augmentation , It gives insights on how the model may perform in the future and makes us know if the model matches human level performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21f739177816059456617365396d243/href">https://medium.com/media/c21f739177816059456617365396d243/href</a></iframe><p>The code above compresses the predictions and test labels we got initially to a 1-D array picking the maximum value in order for us to compute the error on both the test images, labels, predictions so we can visually see the minimum error our model made below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href">https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*VmAuS6Ucsmk-i8rk5zZFiw.png" /></figure><p>We have done the error analysis visually , and we saw clearly the errors the model made during the prediction, labeling the actual class, and predicted class , I further made an analysis to show the countplot between the two genders for us to know which gender was predicted more wrongly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href">https://medium.com/media/745ec487bebd559f13a920c00b7fd41d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*G-nmAwn_3MEOx9MW5zfU7w.png" /></figure><p>We can always update our model, by including some features which should help the model efficiently, examples are : Data Augmentation, adding batch normalization, dropout layers perhaps might not really have great effects in the model , and we can decide to add model checkpoints from keras.callbacks library if we’re working with a large amount of data in order to save the model at designated checkpoints when training. In this case we’re dealing with thousands of datasets so we can obviously add it to the model. So we have successfully trained the model in this project and we will deploy it in order to make it available for production and to be applied in real life cases, I will be running the tensorflow serving natively. and this deployment will be published in my next article .</p><p><strong>CONCLUSION</strong></p><p>This is my First Article on my latest project , All the codes and files to this project are available here on my github repo : <a href="https://github.com/Savepeter2/Gender-Classification-Using-Keras-Tuner">Github</a> . The second part (Deployment) will be available on my next article, I hope you enjoyed this write-up . If you found this article helpful, please do share it with your friends and leave a clap :-). If you have any queries, feedback or suggestions do let me know in the comments. Also, you can connect with me on <a href="https://twitter.com/SavePeter2">Twitter</a>, <a href="https://www.linkedin.com/in/peter-adekolu-593a001a1/">Linkedin</a> and <a href="/service/mailto:peteradekolu@gmail.com">peteradekolu@gmail.com</a> .There are also available resources online you can always read, watch and learn for you to understand better in various concepts like this. There are so much to share with all of you and I’m just getting started. Stay tuned for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19fff3e986a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>