<?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 Regan Muthomi on Medium]]></title>
        <description><![CDATA[Stories by Regan Muthomi on Medium]]></description>
        <link>https://medium.com/@regansomi?source=rss-a2c76cabe581------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lec6YVJUylRFEs1cPmKQnw.png</url>
            <title>Stories by Regan Muthomi on Medium</title>
            <link>https://medium.com/@regansomi?source=rss-a2c76cabe581------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:59:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@regansomi/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[4 Easy Docker Best Practices for Node.js: Build Faster, Smaller, and More Secure Containers]]></title>
            <link>https://medium.com/@regansomi/4-easy-docker-best-practices-for-node-js-build-faster-smaller-and-more-secure-containers-151474129ac0?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/151474129ac0</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 22:27:03 GMT</pubDate>
            <atom:updated>2026-04-24T18:12:16.799Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>Practical yet easy strategies to reduce image size, speed up builds, reduce attack surface, and cut infrastructure costs for your Node.Js projects.</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hwskLN4lVTOgFGH0" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your Docker images are probably too large. Like, way too large.</p><p>The average Node.js Docker image weighs in at 900MB+. A typical Python app? 800MB. And those bloated images are costing you real money — in cloud storage, transfer fees, and slow deployment times while increasing you application’s attack surface.</p><p>But here’s the thing: that same Node.js app can run in a 150MB container. That Python app? 100MB.</p><p>In this guide, we’ll walk through 4 battle-tested Docker optimization techniques for Node.Js with practical examples that will help you:</p><ol><li><strong>Reduce image sizes by 70–90%.</strong></li><li><strong>Cut build times in half.</strong></li><li><strong>Slash your cloud infrastructure costs.</strong></li><li><strong>Improve security with minimal attack surface.</strong></li><li><strong>Speed up deployments and CI/CD pipelines</strong></li></ol><p>Whether you’re running a startup or managing enterprise infrastructure, these practices will save you time, money, and headaches.</p><p>Let’s dive in.</p><h3>1. Choose the right base image</h3><p>The foundation of an optimized container is selecting the right base image. When evaluating options, consider two critical factors:</p><p><strong>Trust</strong>: Use images from verified sources.</p><p><strong>Size</strong>: Smaller images mean faster builds, quicker deployments, and reduced attack surface.</p><p><strong>Trusted sources include:</strong></p><ul><li><em>Docker Official Images: Maintained by Docker and the community</em></li><li><em>Verified Publishers : Vetted organizations like Microsoft, RedHat, AWS</em></li><li><em>Docker-Sponsored Open Source — Popular OSS projects with official support</em></li></ul><p><strong>Optimize for size:</strong> Choose the smallest base image that meets your needs. For Node.js: <strong>`node:alpine` (40MB)</strong> vs <strong>`node:latest` (350MB+)</strong></p><h3>2. Leverage the build cache</h3><p>Docker’s caching mechanism can drastically reduce build times from minutes to seconds for unchanged code.</p><h4><strong>How Docker caching works:</strong></h4><p>Each instruction in your Dockerfile creates a layer in your final image. Think of these layers as a stack, where each layer builds on top of the previous ones. Docker caches these layers and reuses them in subsequent builds if nothing has changed.</p><p><strong>The golden rule:</strong> Place instructions that change infrequently at the top of your Dockerfile, and frequently changing instructions toward the bottom.</p><p><strong>Why this matters:</strong> When Docker detects a change in any layer, it invalidates the cache for that layer and all subsequent layers. By ordering instructions strategically, you maximize cache hits.</p><p>Let’s compare a poor to optimized cache utilization on a Dockerfile.</p><h4><strong>Poor Cache Utilization.</strong></h4><pre>FROM node:20-alpine<br>WORKDIR /app<br>COPY . .<br>RUN npm install<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>The Dockerfile above copies everything in one go, then runs <strong>npm install</strong>. This means Docker will reinstall all npm packages every time there&#39;s even the smallest change in your codebase, even a single-character typo in a comment. This happens because Docker invalidates the cache for the <strong>COPY . .</strong> layer and all subsequent layers, forcing a complete reinstall of dependencies that haven&#39;t actually changed.</p><h4>Optimized Cache Utilization.</h4><pre>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci<br>COPY . .<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p><strong>Notice the difference?<br></strong>In the optimized approach, we copy only <strong>package*.json</strong> files first, then run <strong>npm ci</strong>. This strategic ordering means:</p><ul><li><strong>Dependency layer is cached</strong>: <strong>npm ci</strong> only runs when <strong>package.json</strong> or <strong>package-lock.json</strong> changes.</li><li><strong>Source code changes don’t trigger reinstalls.</strong></li><li><strong>Dramatically faster rebuilds</strong>: Subsequent builds skip dependency installation entirely.</li></ul><h4><strong>The impact</strong></h4><p>For a typical Express project with 50+ dependencies:</p><ul><li><strong>Without optimization</strong>: 2–3 minutes per build (reinstalls everything)</li><li><strong>With optimization</strong>: 5–10 seconds per build (reuses cached dependencies)</li></ul><p>This difference becomes even more significant for larger projects with hundreds of dependencies.</p><h3><strong>3. Use .dockerignore to Exclude Unnecessary Files.</strong></h3><p>The <strong>.dockerignore</strong> file works like <strong>.gitignore</strong>, but for Docker builds. It tells Docker which files and directories to exclude when copying your project into the container.</p><p><strong>Why this matters:<br></strong>When you use <strong>COPY . .</strong> in your Dockerfile, Docker sends your entire project directory to the build context. Without a <strong>.dockerignore</strong>, you&#39;re copying files that bloat your image and slow down builds, things like <strong>node_modules/</strong>, <strong>.git/</strong>, <strong>documentation</strong>, <strong>test files</strong>. Also for security include your <strong>.env </strong>files as well.</p><h4><strong>The impact:</strong></h4><p>For a typical Node.js Express project:</p><ul><li><strong>Without </strong><strong>.dockerignore</strong>: Sends ~200MB to build context (including node_modules/)</li><li><strong>With </strong><strong>.dockerignore</strong>: Sends ~5MB to build context</li><li><strong>Result</strong>: 40x faster context transfer, smaller final image</li></ul><p>Always create a <strong>.dockerignore</strong> file at the root of your project. <br>It’s a small step that delivers massive returns: faster builds, <br>smaller images, and lower costs.</p><h3>4. Use Multi-Stage Builds.</h3><p>Multi-stage builds are one of the most powerful Docker optimization techniques. They let you use one image for building your application and a different, smaller image for running it, while ensuring only necessary packages make it to production.</p><p><strong>How it works<br></strong>Split your Dockerfile into distinct stages. The first stage includes all build tools and dependencies, while the final stage contains only what’s needed to run the application.</p><p><strong>Why this matters<br></strong>Your build process needs compilers, build tools, and dev dependencies. Your production container doesn’t. Multi-stage builds let you separate these concerns cleanly and exclude everything unnecessary from the final image.</p><p>To understand why multi-stage builds matter, let’s first examine a typical single-stage Dockerfile and identify where it falls short.</p><pre>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci<br>COPY . .<br>RUN npm run build                   <br>CMD [&quot;node&quot;, &quot;dist/server.js&quot;]</pre><p>In the example above, the final image includes everything: dev dependencies (testing frameworks, linters, TypeScript compiler) and all source TypeScript files. This unnecessarily increases your image size and slows down both builds and deployments.</p><p>Now let look at an optimized Dockerfile:</p><pre># Stage 1: Build stage<br>FROM node:20-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci<br>COPY . .<br>RUN npm run build<br><br># Stage 2: Production stage<br>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci --only=production<br>COPY --from=builder /app/dist ./dist<br>CMD [&quot;node&quot;, &quot;dist/server.js&quot;]</pre><p><strong>Focus on Stage 2, this is what actually runs in production.<br></strong>Notice that we only install production dependencies with npm ci --only=production and copy just the compiled ./dist folder from the builder stage. Everything else: dev dependencies, TypeScript source files, test files, and build tools—gets left behind in the builder stage and never makes it to the final image.</p><h4>The Impact:</h4><p>For a typical Express + TypeScript project:</p><ul><li><strong>Single-stage build</strong>: 450MB (includes dev dependencies, TypeScript compiler, source files)</li><li><strong>Multi-stage build</strong>: 120MB (production dependencies and compiled code only)</li><li><strong>Result</strong>: 73% size reduction, faster deployments, lower registry costs</li></ul><p>Make multi-stage builds your standard practice for any compiled language or application with build steps. It’s the single most effective optimization for production Docker images.</p><p>The practices we’ve covered:</p><ol><li>Selecting minimal base images.</li><li>Optimizing build cache.</li><li>Excluding unnecessary files with .dockerignore.</li><li>Separating build from runtime with multi-stage builds .</li></ol><p>Represent the foundation of Docker optimization. They’re straightforward to implement, don’t require specialized expertise, yet consistently deliver the biggest wins: 70%+ size reductions, dramatically faster builds, and measurably lower infrastructure costs.</p><p>Master these four techniques, and you’ll have production-ready containers that are fast, lean, and secure.</p><p>Docker optimization is an evolving practice, and there’s always more to learn. If you’ve discovered other techniques that work well for Node.js containers, whether it’s layer ordering strategies, security hardening, or deployment optimizations, I would love to hear them.</p><p>Thank you very much for reading this article. I hope you had as much fun as I had writing it for you. I will appreciate all kinds of feedback on the comment section or my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a>.</p><p><em>Also feel free to say Hi✋ </em><a href="https://x.com/regan_codes"><em>X</em></a></p><p><em>Gracias!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151474129ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Fundamentals: Demystifying SQL Window Functions for Data Wizards.]]></title>
            <link>https://medium.com/@regansomi/beyond-the-fundamentals-demystifying-sql-window-functions-for-data-wizards-cfccd108e3ca?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfccd108e3ca</guid>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 23:32:44 GMT</pubDate>
            <atom:updated>2023-12-06T23:32:44.286Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL window functions are crucial in facilitating practical data analysis within SQL. Despite being powerful, SQL window functions are often overlooked and less understood by many. This article aims to demystify the intricacies surrounding SQL window functions. By the end of this piece, you will appreciate what window functions are, how they operate, and how to integrate them into your SQL workflows seamlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x06PuW0ml4fwU_l-" /><figcaption>Photo by <a href="https://unsplash.com/@robwingate?utm_source=medium&amp;utm_medium=referral">Rob Wingate</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Aggregate Functions</h4><p>We cannot talk about window functions without first understanding what <strong>aggregate functions</strong> are. Aggregate functions operate on a set of values and return a single output row that summarizes the information from the rows in a database table. They are used with the <strong>GROUP BY</strong> clause to perform operations on groups of rows. An example would be, say, you want to calculate the average salary of employees by department. In the rest of this article, we will show example queries based on an employee database table.</p><pre>SELECT AVG(salary) as departmentAverage<br>FROM employees<br>GROUP BY department;</pre><p>First, SQL will group the rows by departments and then calculate each department’s average salary.</p><figure><img alt="SQL aggregate functions" src="https://cdn-images-1.medium.com/max/1000/1*o1ZkOZ-Bn-I7lfkmStdf_A.png" /><figcaption>SQL Aggregation.</figcaption></figure><p>The number of rows in the result set should equal the number of distinct groups in the department field.</p><figure><img alt="SQL-aggregate-functions" src="https://cdn-images-1.medium.com/max/1000/1*K0VzCjaHdmMu2b030c3Czg.png" /><figcaption>Aggregated Results.</figcaption></figure><p>Other aggregate functions in SQL include: <strong>MIN(), MAX(), SUM(), COUNT().</strong></p><h4>SQL Window Functions</h4><p>Like aggregate functions, window functions perform aggregate operations on groups of rows. However, window operations do not collapse groups of rows into a single output row. Instead, they produce a result for EACH row in the data. The O<strong>VER()</strong> clause signifies an SQL window operation; it specifies how to partition query rows into groups for processing by the window function. This <strong>OVER()</strong> clause distinguishes window functions from the non-window aggregate functions.</p><pre>SELECT <br>  deparment,<br>  AVG(salary) OVER(PARTITION BY department) AS departmentAverage<br>FROM employees;</pre><figure><img alt="SQL window function results" src="https://cdn-images-1.medium.com/max/1000/1*vYPfFFWz9zZOd7bvfy4C6Q.png" /><figcaption>Window Function Result Table.</figcaption></figure><p>As you can see from the result table above, SQL calculated the average salary for each department but retained the original rows of data. The window operation did not collapse the groups of query rows to single output rows; it added a new field for the <strong>departmentAverage</strong> to the original data.</p><h4><strong>Syntax of a window function.</strong></h4><p>Now, let us explore the syntax of a window function in SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*KYFoK7eiy67fh_jqztzEvA.png" /><figcaption>Window Function Syntax</figcaption></figure><p><strong>1. WINDOW_FUNCTION_NAME</strong></p><p>The name of the window function. Some aggregate functions are permitted to be used as window function. They include:</p><blockquote><em>AVG()</em></blockquote><blockquote><em>BIT_AND()</em></blockquote><blockquote><em>BIT_OR()</em></blockquote><blockquote><em>BIT_XOR()</em></blockquote><blockquote><em>COUNT()</em></blockquote><blockquote><em>JSON_ARRAYAGG()</em></blockquote><blockquote><em>JSON_OBJECTAGG()</em></blockquote><blockquote><em>MAX()</em></blockquote><blockquote><em>MIN()</em></blockquote><blockquote><em>STDDEV_POP(),</em></blockquote><blockquote><em>STDDEV(),</em></blockquote><blockquote><em>STD()</em></blockquote><blockquote><em>STDDEV_SAMP()</em></blockquote><blockquote><em>SUM()</em></blockquote><blockquote><em>VAR_POP(),</em></blockquote><blockquote><em>VARIANCE()</em></blockquote><blockquote><em>VAR_SAMP()</em></blockquote><p>However, there are functions that we can only use as window functions; we cannot use them for non-window operations. They include:</p><ul><li>CUME_DIST()</li><li>DENSE_RANK()</li><li>FIRST_VALUE()</li><li>LAG()</li><li>LAST_VALUE()</li><li>LEAD()</li><li>NTH_VALUE()</li><li>NTILE()</li><li>PERCENT_RANK()</li><li>RANK()</li><li>ROW_NUMBER()</li></ul><p><strong>2. expression</strong></p><p>The operation or column upon which the window function operates.</p><p><strong>3. OVER()</strong></p><p>The over clause defines window partitions to form the groups of rows. It contains the three clauses: <em>partition_clause</em>, <em>order_clause</em>, and <em>frame_clause</em>. If the OVER clause is empty, all rows are treated as one single partition.</p><pre>SELECT <br>  department,<br>  salary,<br>  AVG(salary) OVER() AS averageSalary<br>FROM employees;</pre><blockquote>The query above contains an empty OVER clause. Therefore, SQL will treat all the rows like a single partition and calculate the average for the <strong>salary</strong> column into a new column called <strong>averageSalary</strong>.</blockquote><figure><img alt="SQL window function with empty OVER clause" src="https://cdn-images-1.medium.com/max/893/1*srT5-h0Cv7J5UwcSyvhDYw.png" /><figcaption>Empty OVER clause.</figcaption></figure><p><strong>4. PARTITION BY<br></strong>Window queries often use the PARTITION BY clause to divide the result set into partitions to which the window function is applied separately. This allows for calculations within specific groups of rows.</p><pre>SELECT <br>  department,<br>  salary,<br>  AVG(salary) OVER(PARTITION BY department) AS departmentAverage<br>FROM employees;</pre><blockquote>With the PARTITION BY clause inside OVER, SQL will first group/partition the rows by the department and then calculate the average for each partition group in the <strong>departmentAverage</strong> column.</blockquote><figure><img alt="Partition clause in window functions" src="https://cdn-images-1.medium.com/max/1024/1*_dZxxQ0j6j2DSxNSAA65kQ.png" /></figure><p><strong>5. ORDER BY<br></strong>You use the ORDER BY clause to sort the rows within a partition and control the order in which the window function processes them. We can omit the ORDER BY clause if the ordering of rows is not important. It is essential for functions like <strong>ranking </strong>or calculating <strong>running totals</strong>.</p><pre>SELECT <br>  employee_id,<br>  department,<br>  salary,<br>  RANK() OVER(PARTITION BY department ORDER BY SALARY) AS departmentRank<br>FROM employees;</pre><p><em>The ORDER BY clause sorted the partitions by the salary column so that the </em><strong><em>departmentRank</em></strong><em> column is ordered in ascending order. To order each partition’s rows in descending order, add the DESC keyword after the ORDER BY clause.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYcRfKk1PWDVE2jImeiLng.png" /></figure><p><strong>6. WINDOW FRAME<br></strong>The <strong>window frame</strong> defines the UPPER and LOWER BOUND within a partition on which the window function should operate. It allows you to specify the range or set of rows relative to the current row that the function should consider. There are two methods of using a window frame:</p><ul><li><strong>ROWS BETWEEN:</strong> You should use this clause to define a range of rows relative to the current row based on the row position of the ordering column.</li><li><strong>RANGE BETWEEN: </strong>Like ROWS BETWEEN, it defines a range of rows relative to the current row, but unlike ROW BETWEEN, it operates on the actual values of the ordering column rather than the row position.</li></ul><pre>SELECT <br>   employee_id,<br>   department,<br>   salary,<br>   SUM(salary) OVER(<br>     PARTITION BY department ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>   ) AS departmentRank<br>FROM employees;</pre><p><em>In the query above, SQL calculates a running sum for all rows from the start of the partition up to and including the current row.</em></p><p>In conclusion, SQL window functions emerge as indispensable tools in the arsenal of any data analyst or SQL practitioner. Their ability to operate within specific partitions and window frames provides a level of granularity that goes beyond traditional aggregate functions. I hope this article helps you understand the intricacies of SQL window functions. As always, writing this article has been an absolute joy for me; I hope you find as much pleasure in reading it.</p><p>I will appreciate all kinds of feedback on the comment section or my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a>.</p><p><em>Also feel free to say Hi✋ </em><a href="https://twitter.com/regan_codes"><em>twitter</em></a></p><p><strong>References:</strong></p><ol><li><a href="https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html">https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html</a></li><li><a href="https://www.postgresql.org/docs/current/tutorial-window.html">https://www.postgresql.org/docs/current/tutorial-window.html</a></li><li><a href="https://learnsql.com/blog/define-window-frame-sql-window-functions/">https://learnsql.com/blog/define-window-frame-sql-window-functions</a></li><li><a href="https://www.sqltutorial.org/sql-window-functions/">https://www.sqltutorial.org/sql-window-functions/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfccd108e3ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate SQL Cheatsheet]]></title>
            <link>https://medium.com/@regansomi/the-ultimate-sql-cheatsheet-61480a5baabc?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/61480a5baabc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 11:41:28 GMT</pubDate>
            <atom:updated>2023-11-01T15:22:47.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t31QR80_buSVT-Fr" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A few months ago, I hosted SQL learning sessions with a tech community in Nairobi, Kenya. In this article, I will share everything we learned during those sessions. My aim is to help newcomers to SQL and those looking to enhance their SQL skills. So, please, sit back, relax, and let’s get started.</p><p>So, what is SQL? SQL stands for Structured Query Language, and it’s a programming language used for managing and manipulating relational databases. SQL is employed to define the structure of a database, create and modify database objects such as tables and views, and retrieve information from databases.</p><h4><strong>SQL Commands</strong></h4><p>A SQL command is a specific instruction or statement used to perform a specific operations on a database. SQL commands can be grouped into 4 broad categories.</p><p><strong>Types of SQL commands</strong></p><ol><li><strong><em>Data Manipulation Language (DML) commands</em></strong>: Used to manipulate data within a table. They include: <em>SELECT</em>,<em> INSERT, UPDATE, DELETE</em></li><li><strong><em>Data Definition Language (DDL) commands:</em></strong> Used to define the structure of database objects. They include: <em>CREATE, ALTER, DROP</em></li><li><strong><em>Data Control Language (DCL) commands:</em></strong> Used to control access to the database, such as granting and revoking permissions. They include: <em>GRANT, REVOKE</em></li><li><strong><em>Transaction Control Language (TCL) commands:</em></strong> Used to manage transactions in a database. They include: <em>ROLLBACK, SAVEPOINT, COMMIT, SET TRANSACTION</em></li></ol><p>Let’s go ahead and look at individual SQL clauses. Wait, before we do that, let’s take care of a few basics first.</p><ul><li><strong><em>SQL is not case sensitive.</em></strong></li><li><strong><em>-- This is a SQL comment.</em></strong></li><li><strong><em>End your SQL statements with semi-colon especially for MySQL.</em></strong></li></ul><p>Let’s focus on SQL clauses and operators used for Data Analysis and Manipulation (DML) for now.</p><h4><strong>1. SELECT</strong></h4><p>The SELECT clause is used to retrieve data from one or more tables.</p><pre>SELECT customer_id, points<br>FROM customers;</pre><p><em>The statement above retrieves </em><strong><em>customer_id</em></strong><em> and </em><strong><em>points</em></strong><em> columns from the the table called </em><strong><em>customers</em></strong><em>.</em></p><h4>2. <strong>DISTINCT</strong></h4><p>Used with SELECT to retrieve the unique values or remove duplicates from a certain field.</p><pre>SELECT DISTINCT city<br>FROM customers;</pre><p><em>Returns only the unique </em><strong><em>cities</em></strong><em> in the customers table.</em></p><h4>3. <strong>WHERE</strong></h4><p>The clause WHERE is used to filter data based on one or more conditions. By using comparison operators, we can retrieve data that meets specific criteria.</p><blockquote><strong><em>Comparison Operators</em></strong></blockquote><blockquote><em>Greater than: </em><strong><em>&gt;</em></strong></blockquote><blockquote>Greater than or equal to: <strong>&gt;=</strong></blockquote><blockquote>Less than: <strong>&lt;</strong></blockquote><blockquote>Less than or equal to: <strong>&lt;=</strong></blockquote><blockquote>Equal: <strong>=</strong></blockquote><blockquote>Not equal: <strong>&lt;&gt;</strong></blockquote><blockquote>Not equal: <strong>!=</strong></blockquote><pre>SELECT customer_id, points<br>FROM customers<br>WHERE points &gt; 1000;</pre><p><em>Returns </em><strong><em>customer_id</em></strong><em>s and </em><strong><em>points</em></strong><em> but only for customers with more than 1000 points.</em></p><p>Sometimes you can combine multiple conditions in a where clause using <strong>logical operators</strong>.</p><blockquote><strong>Logical Operators</strong></blockquote><blockquote><strong>1. AND:</strong> All conditions must be True.</blockquote><blockquote><strong>2. OR:</strong> At least one condition must be True.</blockquote><blockquote><strong>3. NOT:</strong> To negate a condition.</blockquote><pre>SELECT customer_id, points<br>FROM customers<br>WHERE points &gt; 1000 AND points &lt; 2000;</pre><p><em>Returns customers with points between </em><strong><em>1000</em></strong><em> and </em><strong><em>2000</em></strong><em>.</em></p><pre>SELECT customer_id, points<br>FROM customers<br>WHERE city = &quot;Nairobi&quot; OR city = &quot;Lagos&quot;;</pre><p><em>Returns customers from </em><strong><em>Nairobi</em></strong><em> or </em><strong><em>Lagos</em></strong><em>.</em></p><h4>4. LIMIT</h4><p>LIMIT restricts the number of rows displayed in the result set, saves space on the screen and makes queries run faster.</p><pre>SELECT *<br>FROM customers<br>LIMIT 5;</pre><p><em>Returns the first 5 rows in the customers table.</em></p><h4>5. IN Operator</h4><p>Used in a <strong>WHERE</strong> clause to filter data based on a specified list of values. It allows you to select rows from a table where a column&#39;s value matches any value in the list provided.</p><pre>SELECT customer_id, points<br>FROM customers<br>WHERE city IN (&quot;Nairobi&quot;, &quot;Lagos&quot;);</pre><p><em>Returns data for customers from Nairobi and Lagos only.</em></p><h4>6. BETWEEN Operator.</h4><p>Used with the <strong>WHERE</strong> clause to filter data based on a range of values for a particular column/field.</p><pre>SELECT customer_id, points<br>FROM customers<br>WHERE points BETWEEN 1000 AND 2000;</pre><p><em>Returns customers with points between </em><strong><em>1000</em></strong><em> and </em><strong><em>2000</em></strong><em>.</em></p><h4>7. LIKE Operator</h4><p>Used with <strong>WHERE</strong> when you want to filter data based on a specified pattern.</p><pre>SELECT customer_is, points<br>FROM customers<br>WHERE email LIKE &quot;%@gmail.com&quot;;</pre><p><em>Returns customers who have the gmail email address.</em></p><ul><li><strong>%</strong> - means match any number of characters.</li><li><strong>_</strong> - means match exactly one character.</li></ul><h4>8. IS NULL Operator</h4><p>Used with WHERE clause to filter rows of data that have missing values for a particular column.</p><pre>SELECT customer_id, points<br>FROM customers<br>WHERE email IS NULL;</pre><p><em>Returns customers with missing emails.</em></p><h4><strong>9. ORDER BY</strong></h4><p>Used to sort results of a <strong>SELECT</strong> statement in a specific order based on one or more columns. The results are by default sorted in <strong>Ascending Order</strong>.</p><pre>SELECT customer_id, points<br>FROM customers<br>ORDER BY points;</pre><p><em>Returns the result set sorted on ascending based on the points column.</em></p><p>To sort in descending order you use the <strong>DESC</strong> keyword with ORDER BY clause.</p><pre>SELECT customer_id, points<br>FROM customers<br>ORDER BY points DESC;</pre><p>Sometimes you can also sort your result by multiple columns.</p><pre>SELECT customer_id, points<br>FROM customers<br>ORDER BY points DESC, customer_id;</pre><p>Sorts the result by points for (<strong><em>in descending</em></strong>) then by customer_id (<strong><em>in ascending</em></strong>).</p><h4><strong>10. CASE</strong></h4><p><strong>CASE</strong> is an expression used to perform conditional logic within a query. It allows you to define conditional statements and specify different actions or values to return based on the evaluation of those conditions.</p><pre>SELECT customer_id, points<br>  CASE<br>    WHEN points &gt; 5000 THEN &#39;High&#39;<br>    WHEN points &gt; 2000 THEN &#39;Moderate&#39;<br>    ELSE &#39;Low&#39;<br>  END AS points_group<br>FROM customers;</pre><p>The statement above creates a new column called ‘<strong>points_group’</strong> in the result set and applies the logic defined in the <strong>CASE</strong> expression to assign values to that column.</p><p><strong>11. SQL JOINS</strong></p><p>A SQL JOIN is an operation used to combine rows from two or more tables based on a related column between them.</p><p>Joins allow us to retrieve data from multiple tables in a database and build complex queries to extract meaningful insights.</p><p><strong>Types of Joins</strong></p><ol><li>INNER Join.</li><li>LEFT Join.</li><li>Right Join.</li><li>Full Outer Join.</li><li>CROSS Join.</li></ol><p><strong>INNER JOIN</strong></p><p>INNER JOIN is used to retrieve data from two or more related tables based on a specified condition. It returns only the rows for which there is a match in both the left and right tables, dropping rows that do not have matching values in the specified columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCFvt6AwP11cMYSx2uDm_g.png" /><figcaption>INNER SQL Join</figcaption></figure><pre>SELECT customers.customer_id, order_id<br>FROM customers<br>INNER JOIN orders <br>ON customers.customer_id = orders.customer_id;</pre><p><em>Returns only the rows where the </em><strong><em>customer_id</em></strong><em> in the </em><strong><em>customers</em></strong><em> table equals the </em><strong><em>customer_id</em></strong><em> in the </em><strong><em>orders_table</em></strong><em>.</em></p><p><strong>LEFT JOIN</strong></p><p>LEFT Join is used to retrieve data from two or more tables based on a specified condition while including all rows from the left table, even if there is no match in the right table. If there are no matching rows in the right table, <strong>NULL</strong> values are returned for the columns from the right table.</p><p>It’s also referred to as <strong>LEFT OUTER JOIN</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1qLHl_KRLjB39IsyeWv7g.png" /><figcaption>Left SQL Join</figcaption></figure><pre>SELECT customers.customer_id, order_id<br>FROM customers<br>LEFT JOIN orders<br>ON customers.customer_id = orders.customer_id;</pre><p><em>It returns all rows from the customers table (left) and only the rows from the orders table (right) where the joining condition </em><strong><em>(customers.customer_id = orders.customer_id)</em></strong><em> is satisfied.</em></p><p><strong>RIGHT JOIN</strong></p><p>A RIGHT JOIN is the reverse of a LEFT JOIN. It includes all rows of data from the right table and, for the left table, only the rows that have a matching entry in the right table based on the joining condition.</p><p>It’s also known as <strong>RIGHT OUTER JOIN.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93i2Bzd8jKiChn7IOkzC8Q.png" /></figure><pre>SELECT customers.customer_id, order_id<br>FROM customers<br>RIGHT JOIN orders<br>ON customers.customer_id = orders.customer_id</pre><p><em>It returns all rows from the orders table (right) and only the rows from the customers table (left) where the joining condition </em><strong><em>(customers.customer_id = orders.customer_id)</em></strong><em> is satisfied.</em></p><p><strong>FULL OUTER JOIN</strong></p><p>FULL OUTER JOIN is used to retrieve data from two or more tables based on a specified condition while including all rows from both tables, even if there are no matches in one or both tables. If there are no matching rows in one of the tables, NULL values are returned for the columns from the table without a match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJu1W96srNzuwSz-rnXAXQ.png" /><figcaption>Full Outer Join</figcaption></figure><pre>SELECT customers.customer_name, orders.order_id<br>FROM customers<br>FULL OUTER JOIN orders ON customers.customer_id = orders.customer_id;</pre><p><em>Full Outer Join returns all the rows both the </em><strong><em>customers</em></strong><em> and </em><strong><em>orders</em></strong><em> table, including those that don’t have corresponding matches in the other table.</em></p><h4>12. UNIONS</h4><p>Union is used when you need to merge data from multiple tables or queries that have the same structure. It eliminates duplicate rows from the combined result set, ensuring that each row is unique.</p><pre>SELECT name, email<br>FROM employees<br>UNION<br>SELECT name, email<br>FROM contractors;</pre><p><em>The statement above returns a combined result set of data from </em><strong><em>contractors</em></strong><em> and </em><strong><em>employees</em></strong><em> tables.</em></p><p>Generally, UNIONS are used for combining data from multiple sources in SQL queries and can be used in various scenarios where you need to consolidate information with matching structures.</p><h4><strong>13. GROUP BY</strong></h4><p><strong>Group By</strong> clause is used to group rows that have the based on values in one or more columns.</p><p>When we use this clause, SQL creates a group for every unique value in the column or set of columns you are grouping by, the aggregates the summary statistics for each group.</p><p>Summary statistics include:</p><ol><li><strong>SUM</strong> — Total sum of values in a numeric column.</li><li><strong>AVG</strong> — Average for values in a numeric column.</li><li><strong>COUNT</strong>— Total number of non-null values in a column.</li><li><strong>MAX/MIN </strong>— Maximum/minimum value in a column.</li><li><strong>STDEV</strong> — Standard deviation of values in a numeric column.</li></ol><pre>SELECT customer_id, MAX(points), MIN(points)<br>FROM customers<br>GROUP BY country;</pre><p><em>Aggregates the </em><strong><em>customers table</em></strong><em> by </em><strong><em>country</em></strong><em> and selects the customers with </em><strong><em>maximum</em></strong><em> and </em><strong><em>minimum points</em></strong><em> for each country.</em></p><h4>14. HAVING</h4><p><strong>HAVING</strong> clause is used with <strong>GROUP BY</strong> to filter data based on the results of aggregate functions. While the <strong>WHERE</strong> clause is used to filter rows before aggregation, the <strong>HAVING</strong> clause is used to filter the results after aggregation.</p><pre>SELECT product_category, SUM(order_amount) AS total_sales<br>FROM orders<br>GROUP BY product_category<br>HAVING SUM(order_amount) &gt; 10000;</pre><p><em>Aggregates the orders by </em><strong><em>product_category </em></strong><em>and filters only those categories where the </em><strong><em>sum of orders</em></strong><em> is greater than </em><strong><em>10000</em></strong><em>.</em></p><p>In this article, we’ve discussed many SQL clauses and operators and their applications in depth. Therefore, this article should serve as an invaluable resource for both beginners and experienced SQL practitioners, providing a comprehensive and user-friendly guide to mastering the language. While this cheat-sheet covers the fundamental aspects of SQL, the journey to SQL mastery is ongoing, offering endless opportunities for growth and exploration in the world of structured data.</p><p>Thank you very much for reading this article. I hope you had as much fun as I had writing it for you. I will appreciate all kinds of feedback on the comment section or my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a>.</p><p><em>Also feel free to say Hi✋ </em><a href="https://twitter.com/regan_codes"><em>twitter</em></a></p><p><em>Gracias!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61480a5baabc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A KNN Algorithm from Scratch with Pandas and Numpy.]]></title>
            <link>https://medium.com/@regansomi/building-a-knn-algorithm-from-scratch-with-pandas-and-numpy-c8e4411bff5c?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e4411bff5c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Tue, 30 May 2023 10:34:38 GMT</pubDate>
            <atom:updated>2023-05-30T18:20:19.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clWmyP_y6wu0c7O213moBQ.jpeg" /><figcaption>Image credits: <a href="https://unsplash.com/@kellysikkema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a> on <a href="https://unsplash.com/photos/8jjQ4hmCOcM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>While there are numerous high-level libraries available that provide ready-to-use implementations of machine learning algorithms, having a solid understanding of the underlying principles enables us to make informed decisions and tackle real-world challenges effectively. It allows us to optimize and fine-tune these algorithms to suit specific use cases and interpret their results better.<br>In this blog post, we will delve into the realm of machine learning algorithms and embark on a fascinating journey of building a K-Nearest Neighbors (KNN) algorithm from scratch with only Pandas and Numpy. KNN is a versatile and intuitive algorithm that forms the basis of many classification tasks.</p><p>I have broken down this blog into 2 sections:</p><ol><li><strong>Understanding how the KNN works.</strong></li><li><strong>Coding the KNN from scratch.</strong></li></ol><h4><strong>1. Understanding KNN and how it works.</strong></h4><p>A KNN is a non-parametric classification algorithm, this means that it uses the training data when making predictions. Given an unseen observation, this is how the KNN works:</p><ol><li>Distance between that observation and every other observation in the training data is calculated.</li><li>Select <strong>K</strong> number of observations that have the smallest distance from the unseen observation.</li><li>The most frequent label from the nearest neighbors is assigned as the label/prediction to the unseen observation.</li></ol><p>Distance in KNNs is calculated using these measurements:</p><ol><li>Euclidean Distance.</li><li>Manhattan Distance.</li><li>Minkowski Distance.</li></ol><p>We’ll not get into how these distances are calculated, but this article by <a href="https://towardsdatascience.com/importance-of-distance-metrics-in-machine-learning-modelling-e51395ffe60d">Natasha Sharma</a> goes into the depths of that.</p><h4>2. Coding the KNN.</h4><p>Assume the training data is given as <strong>X_train</strong>, <strong>y_train </strong>where X_train are the independent variables and y_train is the target variable. The unseen observation is also given as <strong>test_0</strong>, we can also assume the test_0 has the same number of features as the X_train and that they are all pandas objects.</p><ol><li><strong>Calculate the distance between test_0 and observations in X_train.</strong></li></ol><pre>import numpy as np<br><br>def calculate_distance(X_train, test_0):<br>  &quot;&quot;&quot;<br>    Calculate distance between test_0 and every observation in X_train.<br>    Using Euclidean distances in this example.<br>    Both X_train and test_0 should be pandas dataframe and series repectively.<br>    Returns distances in a pandas series. <br>  &quot;&quot;&quot;<br>  distance = 0<br>  for column in X_train.columns:<br>      distance += (X_train[column] - test_0[column]) ** 2<br>  return np.sqrt(distance)</pre><p>2. <strong>Select K nearest observations and predict.</strong></p><pre>def select_k(X_train, y_train, k):<br>  &quot;&quot;&quot;<br>    Select K observations nearest from test_0<br>    First call the previous functions to calculate distances<br>    Returns prediction.<br>  &quot;&quot;&quot;<br>  X_train[&quot;distance&quot;] = calculate_distance(X_train, test_0)<br>  prediction = y_train[train_data[&quot;distance&quot;].nsmallest(n=k).index].mode()[0]<br>  return prediction<br>  </pre><h4>Put everything together.</h4><pre>class KNN:<br>    &quot;&quot;&quot;<br>        A simple implementation of the KNN Algorithm.<br>    &quot;&quot;&quot;<br>    def __init__(self, x_train, y_train, k=5):<br>        self.x_train = x_train<br>        self.y_train = y_train<br>        self.k = k<br>    def single_pred(self, input_data):<br>        &quot;&quot;&quot;<br>            Generate a  prediction given a single row input.<br>        &quot;&quot;&quot;<br>        distance = 0<br>        if self.x_train.shape[-1] == input_data.shape[-1]:<br>            train_data = self.x_train.copy()<br>            for column in train_data.columns:<br>                distance += (train_data[column] - input_data[column]) ** 2<br>            train_data[&quot;distances&quot;] = distance ** 0.5<br>            prediction = self.y_train[train_data[&quot;distances&quot;].nsmallest(n=self.k).index].mode()[0]<br>            return prediction<br>        else:<br>            raise Exception(&quot;The training data and the input data have different number of columns&quot;)<br>    def predict(self, input_data):<br>        &quot;&quot;&quot;<br>            Generates predictions given multiple rows.<br>            Calls the prediction method of the provided dataframes.<br>        &quot;&quot;&quot;<br>        if len(input_data) == 1:<br>            return self.single_pred(input_data=input_data)<br>        else:<br>            predictions = input_data.apply(lambda x: self.single_pred(x), axis=1)<br>            return predictions.reset_index(drop=True)<br>    def accuracy(self, x_test, y_test):<br>        &quot;&quot;&quot;<br>            Calculates the accuracy on the test data.<br>            Compares how many predictions of the test set match the actual y_test.<br>        &quot;&quot;&quot;<br>        test_data = x_test.copy()<br>        test_data[&quot;predictions&quot;] = test_data.apply(lambda x: self.single_pred(x), axis=1)<br>        accurate_preds = test_data[&quot;predictions&quot;] == y_test<br>        pred_accuracy = accurate_preds.sum()/len(accurate_preds)<br>        return round(pred_accuracy, 4) * 100</pre><p>The K-Nearest Neighbor algorithm does not use trained parameters to generate predictions for unseen observations. Instead, it uses the training data during prediction which can be computationally expensive especially for large datasets. It’s for this reason that it’s not a very good fit when working with large datasets. Being a non-parametric algorithm, KNN is also bad when predicting observations that are outside the scope of the training data.</p><p>In this article, we looked at the KNN algorithm and built a naive implementation with only Pandas and Numpy. The source code can be found in this Github repository.</p><p>Thank you very much for reading this article. I hope you had as much fun as I had writing it for you. I will appreciate all kinds of feedback on the comment section or my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a>.</p><p><em>Also feel free to say Hi✋ </em><a href="https://twitter.com/regan_codes"><em>twitter</em></a></p><p><em>Gracias!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e4411bff5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Types of Categorical Encoding in Machine Learning]]></title>
            <link>https://medium.com/@regansomi/categorical-encoding-e2912725c012?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2912725c012</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[categorical-encoding]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 10:27:06 GMT</pubDate>
            <atom:updated>2023-12-04T22:22:50.521Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-world data comes in all shapes, forms, and types. However, most machine learning algorithms only accept numerical inputs. To build predictive machine models using these algorithms, we need to convert categorical variables in our data to numeric formats. This is achieved through <strong>categorical encoding</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4edDY6FMjp6WxyAQ" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Categorical encoding is the process of converting categorical variables into numerical format that can be processed by machine learning algorithms.</strong></p><p>In this article, we are going to discuss two of the most common encoding methods:</p><ol><li>Ordinal Encoding.</li><li>One-hot Encoding.</li></ol><p>Before discussing these encoding methods, let’s take a minute to understand the different types of categorical variables that we might encounter in a dataset. Generally, there are two types of categorical variables: <strong>nominal variables</strong> and <strong>ordinal variables</strong>.</p><p><em>What’s the difference between these types categories?</em></p><p>Well,<strong> Ordinal variables</strong> have a natural hierarchy or order. For example, <strong>income bracket </strong><em>(high, middle, low)</em> has a natural order because a person in the high income bracket earns more money than both medium and low, and medium income earners earn more than low income earners.</p><p><strong>Nominal variables</strong>, on the other hand, do not have a natural hierarchy and all categories are considered equal. Examples of nominal variables include gender (male, female), country (Nigeria, Kenya, Ghana), and so on.</p><figure><img alt="Nominal and Ordinal variables" src="https://cdn-images-1.medium.com/max/1024/1*XasVzvHnJH76bMpOjNBAhA.png" /><figcaption>In the example above <strong>Income_class</strong> is an <strong>ordinal</strong> variable while <strong>Gender</strong> is a <strong>nominal variable</strong>.</figcaption></figure><p>When encoding ordinal variables, it is important to retain the natural order between the categories. On the other hand, for nominal variables, we want to avoid introducing any hierarchy that would suggest unequal categories. Therefore, different encoding methods should be used for nominal and ordinal categorical variables.</p><p>Now let’s discuss encoding methods and when to use them.</p><ol><li><strong>Ordinal Encoding</strong></li></ol><p>As the name suggests, ordinal encoding is used for ordinal variable encoding. It retains the natural hierarchy in the variable’s categories by converting them into ordinal integers (from 0 to n_categories).</p><figure><img alt="Ordinal Encoding" src="https://cdn-images-1.medium.com/max/1024/1*rmkh4OexTHXcUahZEQeyTQ.png" /><figcaption><strong>Income_class</strong> variable has been ordinal encoded to <strong>Income_class(Encoded).</strong></figcaption></figure><p>The illustration above shows that the <em>income_class</em> variable has been encoded to produce the <em>Income_class(Encoded)</em> while maintaining the natural hierarchy between the categories.</p><p>2. <strong>One-Hot Encoding</strong></p><p>One-hot encoding, also referred to as <strong>dummy variable encoding</strong>, is a method used for encoding nominal variables. This method works by creating binary columns, or dummy variables, for each distinct category. If a variable has <strong>n</strong> distinct categories, the number of binary columns created will be <strong>n</strong>.<strong> </strong>(<em>Sometimes you can remove one of the dummy variable so you are left with n-1</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_D0zCyr7XY9kwaHZpdH1g.png" /><figcaption>Using a One-Hot Encoder the <strong>Gender</strong> variable produces two binary columns <strong>Gender_female</strong> and <strong>Gender_male.</strong></figcaption></figure><p>The Gender column has two distinct categories, <strong>male</strong> and <strong>female</strong>. Therefore, the one-hot encoder has created two binary columns: <strong>Gender_male</strong> and <strong>Gender_female</strong>, each with only two distinct values, <strong>0.0 </strong>or <strong>1.0</strong>.</p><p>Let’s focus on the the first row to understand what is really happening here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02h3g0BYRKGogop7UKL05w.png" /><figcaption>Row 1</figcaption></figure><p>In one-hot encoding, we check for the presence or absence of a category in each row. Since our first row has a value of ‘<strong>Male’</strong> for the <strong>‘Gender’</strong> column, it means that <strong>‘Female’</strong> is absent in that row. Therefore, the <strong>‘Gender_female’</strong> dummy variable will have a value of 0.0 <strong>(absent)</strong> and the <strong>‘Gender_male’</strong> variable will have a value of 1.0 <strong>(present)</strong>.</p><p>However, it is important to be careful when using one-hot encoding on variables with many distinct categories <em>(high cardinality)</em>, as it can significantly increase the dimensionality of your input variables, which could have adverse effects on downstream analysis.</p><p><strong>Conclusion</strong></p><p>In this article, we have looked at two of the most common categorical encoding methods and their use cases. Of course, there are several other encoding methods that we will discuss in a future blog.</p><p>In <a href="https://scikit-learn.org/stable/index.html">scikit-learn</a>, we can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html">Ordinal encoder</a> for ordinal encoding and the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html">One-Hot encoder</a> for one-hot encoding.</p><p>Thank you very much for reading this article. I hope you enjoyed reading it as much as I enjoyed writing it for you. I would appreciate any feedback you may have in the comments section or on my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a> page.</p><p><em>Also feel free to say Hi✋ </em><a href="https://twitter.com/regan_codes"><em>twitter</em></a></p><p><em>Gracias!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2912725c012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Machine Learning Workflow]]></title>
            <link>https://medium.com/@regansomi/a-guide-to-machine-learning-workflow-9a4302b8787e?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a4302b8787e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 17:08:16 GMT</pubDate>
            <atom:updated>2023-03-15T07:10:01.006Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Machine learning is a branch of artificial intelligence and computer science which focuses on the use of data and algorithms to imitate the way that humans learn, gradually improving its accuracy</strong> - <a href="https://www.ibm.com/topics/machine-learning">IBM</a></p><figure><img alt="An AI Bot" src="https://cdn-images-1.medium.com/max/1024/1*xjPczWGV1HJMfUSibFYczw.jpeg" /><figcaption>Machine Learning</figcaption></figure><p><em>Without big data, you are blind and deaf and in the middle of a freeway — </em>Geoffrey Moore.</p><p>In this article we will discuss the machine learning workflow and look into steps and processes involved in creating a proper machine learning solution. Let’s get to work.</p><figure><img alt="Machine Learning Workflow Summary" src="https://cdn-images-1.medium.com/max/1024/1*cHaIjtrh2D1tIiAS99N0Pw.png" /><figcaption>Machine Learning Workflow Summary</figcaption></figure><h3><strong>1. Project Preparation</strong></h3><p>Before you embark on any machine learning project, it’s important to understand the business problem your are trying to solve.</p><p>A deep understanding of the business problem will guide you on how to craft the best solution for the problem, understand the data needed for the project and generally make the project easier to work on.</p><p>Talk to stakeholders and other parties who can offer meaningful insights to the problem you trying to solve.</p><p>It helps also to set the objectives for the project before you start.</p><h3>2. Data Preparation</h3><p>Every machine learning project needs data, and a lot of data. So, after you’ve understood the business problem, the next step is retrieving, cleaning and preparing the data for your ML project.</p><p>This step can be broken down further into 4 sub steps.</p><ol><li><strong>Data Collection/Retrieval.</strong></li><li><strong>Exploratory Data Analysis.</strong></li><li><strong>Data Pre-processing.</strong></li><li><strong>Feature Engineering.</strong></li><li><strong>Feature Selection.</strong></li></ol><p>Let’s dive a little deeper into these sub-steps individually.</p><ol><li><strong>Data Collection/Retrieval</strong></li></ol><p>Data collection is the process of gathering the data relevant to your machine learning project. Having the right data is fundamental to building an excellent machine learning model because the quality of your model is heavily reliant on the data quality. As they say, <em>garbage in garbage out — bad data, bad model.</em></p><p>Data can be collected from a variety of sources, sometimes it’s easily accessible from the organization’s databases and other forms of storage. Other times you’ll need to get out there and collect you own data through <strong>surveys</strong> and <strong>questionnaires</strong>, <strong>web scraping</strong> e.t.c</p><p>You should then merge all the data into one single dataset.</p><p>2. <strong>Exploratory Data Analysis.</strong></p><p>In the exploratory data analysis step, we seek to gain a deeper understanding of the data we collected. Here you will conduct sanity tests on your data and flag any anomalies and inconsistencies in your data.</p><p>These checks often include: <strong>Missing Values, Outliers, Inconsistent Data values, Duplicated Data, Distributions, Variable Datatypes.</strong></p><p>The goal here is to improve our understanding of the dataset and formulate strategies to address any problems in it. You can use Data Visualizations to help with your analysis.</p><p>3. <strong>Data Pre-processing</strong></p><p>Data pre-processing involves transforming your data into a format that is acceptable by the ML algorithms that you’ll be using for your modelling.</p><p>But first you’ll need to address the problems flagged in the previous step. If there are missing values, you should deal with them either by <strong>imputation</strong> or just <strong>dropping</strong> them. Remove outliers and handle any other anomalies you might have discovered in the exploratory data analysis step.</p><p>Almost all ML algorithms accept only numeric inputs, so if your data contains any categorical variables, you should convert them to numerical values through <strong>Encoding</strong>. Encoding techniques can include <strong>One hot encoding</strong>, <strong>Label Encoding</strong>. (<em>We’ll discuss these encoding techniques in another article</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*VZAoCUM4zjceANOZCZwuyQ.png" /><figcaption>Categorical Encoding</figcaption></figure><p>In the example above, you can see the <strong>gender </strong>has been encoded to the <strong>gender_encoded</strong> column.</p><p>You might have variables with different scales in your dataset. The variable with bigger scale always dominates the one with smaller scale. A good example is weight of a person in kilograms and their height in metres. Weight can vary from 2 kilograms all the way to 100 kilograms or more. But height is always less than 3 metres. Therefore the weight variable is more dominant than the height which might not be the case in the real world.</p><p>We can ensure feature equality by placing all variables in one scale using <strong>Normalization. </strong>Normalization methods include <strong>Min-Max Normalization</strong>, <strong>Z-Score Normalization/Standardization.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*X92jAQ2cJMEFNGb42HobwA.png" /><figcaption>Data Normalization</figcaption></figure><p>You can also perform log transformation to bring your variables closer to normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQvtdYPwEdEGgVJjqsIu9A.png" /><figcaption>Log Transformation.</figcaption></figure><p>Another operation that might improve your model is <strong>Discretization/Binning</strong> — which involves converting continuous variables to fixed nominal variables or intervals.</p><p>Many machine learning algorithms prefer or perform better when numerical input variables have a standard probability distribution. If the distribution is wildly skewed, discretization can be performed to help improve the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*H1ctp6kYu2k0urjX3TZ64g.png" /><figcaption>Discretization/Binning</figcaption></figure><p>You can convert the binned variable back to numeric by <strong>encoding</strong>.</p><p><strong>4. Feature Engineering</strong></p><p>Feature engineering involves manipulating existing features in your dataset to create new features that are more relevant to the problem at hand. Feature engineering improves your model’s predictive efficiency.</p><p>Quite often, feature engineering requires Domain knowledge of the topic you are modelling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*CUM2GbXnTb_sJdEGs8f7Kw.png" /><figcaption>Feature Engineering</figcaption></figure><p>The example above shows the simplest form of feature engineering where the <strong>age </strong>variable is obtained from the <strong>DoB </strong>variable.</p><p><strong>5. Feature Selection</strong></p><p>Feature selection is the process of reducing the number of input variables for your model by selecting only those that are most relevant to the model.</p><p>Quite often, not all variables in your data are relevant to the problem your are modelling. In feature selection we’ll use statistical methods to identify and filter out such feature from the training data.</p><p>Feature selection is even more emphasized when working with a <strong>high dimensionality</strong> data(<em>Data with many features/variables</em>). High dimensionality data increases complexity and training cost of your model. It can also cause <strong>over-fitting</strong> on your ML model. Over-fitting occurs when a model performs very well for training data but has poor performance with test data/new data.</p><p>Once we have done feature selection, our data is now ready for modelling but before we can do that, we need to split our data into <strong>Training</strong> and <strong>Testing</strong> sets. This is known as the <strong>train-test split</strong>. Majority of the data will be used for training (<em>around 80%</em>) and the rest will be used to test of model after training.</p><h3>4. Modelling</h3><p>For most data scientists myself included, this is the most exciting phase of a machine learning project.</p><p>Modelling can also be divided into 3 steps.</p><ol><li><strong>Model Training.</strong></li><li><strong>Evaluation.</strong></li><li><strong>Hyperparameter tuning.</strong></li></ol><p>.</p><ol><li><strong>Model Training.</strong></li></ol><p>This is where you feed sufficient training data to a machine learning algorithm. The algorithm will extract patterns in the training data that map the input data attributes to the target (the variable that you want to predict), and output a ML model that captures these patterns.</p><p>By now you might be wondering how do you choose the algorithms to train your models with. Well, here’s a guide on how to do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8K_sO3c4fjY7TvXNX2MNQ.png" /><figcaption>Choosing a ML algorithm</figcaption></figure><p><strong>Labelled data</strong> refers to data in which the target variable(<em>the variable you are predicting</em>) is present. If your training data has a target, this type of machine learning is called <strong>Supervised Learning</strong> e.g House price prediction. If there is no target variable, this type of machine learning is called <strong>Unsupervised Learning </strong>e.g Customer Segmentation.</p><p>Under supervised learning, if your target variable is categorical/discrete you should use <strong>Classification algorithms</strong> and if it’s continuous use <strong>Regression algorithms</strong>.</p><p>You might experiment with a few algorithms and choose the best model for that problem.</p><p>2. <strong>Evaluation.</strong></p><p>Remember when we did the train-test split and ended up with 2 data sets, the training set and test set?</p><p>Well, we’ve used the training set for training the model. Now we are going to use the test set to evaluate the model.</p><p>First you use the model you’ve trained to make predictions for the test data. Second compare these predictions to the actual labels of the test data. Finally use statistical techniques relevant to your model to gauge the performance.</p><p>3. <strong>Hyperparameter Tuning.</strong></p><p>Here you are going to change the operations and settings used to control the training process of your model e.g Number of training steps. This helps to fine tune your model and improve it’s prediction accuracy.</p><p>Then re-train the model again with the new hyperparameters and validate the model again.</p><h3>5. Deployment and Monitoring.</h3><p>If the model meets the objectives you set out to achieve at the start of the project, you should now deploy it. Deployment involves making the model available do the job you built it to do. Deployment can be done inform of a Dashboard, API or embed the model in an existing software product.</p><p>The final step should be to <strong>monitor</strong> your model. As time passes, some business factors and requirements could change in the real world rendering your model obsolete. In such instances, your model needs to be updated. This often involves going back to the start and completing the whole workflow again.</p><p><strong>Conclusion</strong></p><p>In summary there are 4 main steps in a machine learning workflow:</p><ol><li><strong>Project Preparation.</strong></li><li><strong>Data Preparation.</strong></li><li><strong>Modelling.</strong></li><li><strong>Deployment and Monitoring.</strong></li></ol><p>Thank you very much for reading this article. I hope you had as much fun as I had writing it for you. I will appreciate all kinds of feedback on the comment section or my <a href="https://www.linkedin.com/in/regan-muthomi-886b6b85/">LinkedIn</a>.</p><p><em>Also feel free to say Hi✋ </em><a href="https://twitter.com/regan_codes"><em>twitter</em></a></p><p><em>Gracias!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a4302b8787e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluation Metrics for Classification.]]></title>
            <link>https://medium.com/@regansomi/evaluation-metrics-for-classification-422bc440aa69?source=rss-a2c76cabe581------2</link>
            <guid isPermaLink="false">https://medium.com/p/422bc440aa69</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Regan Muthomi]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 10:24:26 GMT</pubDate>
            <atom:updated>2022-11-29T10:24:26.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMWTHZUU-fNAFHeY3LvpNA.jpeg" /><figcaption>Model Evaluation is a very import step in building reliable and effective machine learning models.</figcaption></figure><p>Evaluating Machine Learning models is a fundamental part of building reliable machine learning models. Evaluation ensures that the models effectively do the jobs they were built to do and also check for possible biases in our models. Without proper evaluation, we wouldn’t know how bad or good our models are prior to deployment.</p><p>Today we are looking at some evaluation metrics you could use for classification models.</p><h4><strong>1. Accuracy Score.</strong></h4><p>Accuracy Score is the simplest and most frequently used evaluation metric for classification models. It’s what we are referring to when talking about the accuracy of a machine learning model.</p><p>Accuracy score is the <strong><em>ratio of the total correct predictions to the total number of samples in the data</em></strong>.</p><figure><img alt="Accuracy Score" src="https://cdn-images-1.medium.com/max/383/1*87I-iiIk2IMmLPUMWw0YyQ.png" /><figcaption>Accuracy Score</figcaption></figure><p>As simple as the accuracy score is, it can be misleading when your data contains imbalanced target classes.</p><p>Assume you are working on a fraud detection model for bank transactions where <strong>98%</strong> of all transactions are <strong>non-fraudulent </strong>and only <strong>2%</strong> are <strong>fraudulent</strong>. Your model could have a 98% accuracy score by simply predicting all transactions as <strong>non-fraudulent</strong>. This can be an awfully expensive affair if a <strong>fraudulent</strong> transaction is classified as <strong>non-fraudulent</strong> when the model is in production.</p><p>In such cases we need to look at other evaluation metrics which are better suited to deal with deals with imbalanced data.</p><h4>2. Precision</h4><p>Precision is the <strong>ratio of the true predicted positives to all predicted positives</strong>. Precision answers the question;</p><blockquote>Of all the cases the model predicted to be positive how many were actually positive.</blockquote><p>To explain the more we’ll need a confusion matrix.</p><figure><img alt="Confusion Matrix" src="https://cdn-images-1.medium.com/max/632/1*kU2_PavugP4-HszJ_URZyA.png" /><figcaption>Confusion Matrix</figcaption></figure><p><strong><em>True Negative — </em></strong><em>Observation is negative, and predicted to be negative.</em></p><p><strong><em>False Negative</em></strong><em> — Observation positive but predicted to be negative.</em></p><p><strong><em>False Positive</em></strong><em> — Observation negative but predicted to be positive.</em></p><p><strong><em>True Positive</em></strong><em> — Observation Positive and predicted to be positive.</em></p><figure><img alt="Precision Score" src="https://cdn-images-1.medium.com/max/386/1*IJ7FavKYzo6ajVVBA7Z53w.png" /><figcaption>The higher the <strong>False Positives</strong>, the lower the precision score and vice versa.</figcaption></figure><blockquote>Precision is a good metric to use when the cost of a <strong>False Positive</strong> outweighs the cost of a <strong>False Negative</strong>.</blockquote><p>A good example is <strong>Email Spam Detection </strong>where<strong> </strong>the cost of missing a very important email (like a job offer) is higher than seeing a few spams in your inbox. In this case you should use <strong>precision</strong> to evaluate your model.</p><h4>3. Recall</h4><p>Recall is the <strong>ratio of true predicted positives to the total actual positives. </strong>Precision answers the question;</p><blockquote>Out of all the actual positive cases how many did the model predict as positive.</blockquote><figure><img alt="Recall" src="https://cdn-images-1.medium.com/max/381/1*9DIlKHAASh8cvIW8JdLMYw.png" /><figcaption>The higher the <strong>False Negatives</strong> the lower the recall and vice versa.</figcaption></figure><blockquote>Recall is a good measure to evaluate your model when the cost of having a <strong>False Negative</strong> is higher than <strong>False Positive.</strong></blockquote><p>A good example is a <strong>COVID-19 prediction model</strong>. Having an <strong>infected</strong> person predicted as <strong>healthy </strong>(False Negative) could could be more detrimental than running a few more tests (False Positive). In such a scenario, <strong>Recall </strong>is a better evaluation metric.</p><h4>4. F1 Score</h4><p>We use the <strong>F1</strong> evaluation metric when we want to strike a balance between Precision and Recall of your model.</p><figure><img alt="F1 Score" src="https://cdn-images-1.medium.com/max/424/1*X-bdXKeSbBorIUqzG4T9kg.png" /><figcaption>F1 Score</figcaption></figure><p>A good example for this would be a <strong>Credit Scoring model </strong>for a financial institution like a bank. In this case , if bad loans are predicted as good loans<strong> (False Positive)</strong>, the bank might loose a lot of money from defaulted loans. On the other hand, if good loans are predicted as bad loans <strong>(False Negative)</strong>, then the bank will loose additional income from those loans.</p><p>In this scenario, we might want to use a metric that is a blend of both precision and recall and that is the <strong>F1 Score.</strong></p><p><strong>Summary</strong></p><p>In this article we have looked at 4 classification metrics that is: <strong>Accuracy</strong>, <strong>Precision</strong>, <strong>Recall</strong> and <strong>F1</strong>. There are other metrics that you can use to score your models among the <strong>Receiver Operating Characteristic (ROC)</strong>. In the next article we’ll look at ROC in depth. See you then.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422bc440aa69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>