<?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 Roman Karki on Medium]]></title>
        <description><![CDATA[Stories by Roman Karki on Medium]]></description>
        <link>https://medium.com/@rxman?source=rss-336f77d9ad36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TliS3vHMDeuuBhM21R_Hew.jpeg</url>
            <title>Stories by Roman Karki on Medium</title>
            <link>https://medium.com/@rxman?source=rss-336f77d9ad36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:02:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rxman/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[Production Logging in NestJS with Pino]]></title>
            <link>https://medium.com/@rxman/production-logging-in-nestjs-with-pino-f21ee5844bd4?source=rss-336f77d9ad36------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21ee5844bd4</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[nest-js-logging-with-pino]]></category>
            <category><![CDATA[pino]]></category>
            <dc:creator><![CDATA[Roman Karki]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 08:21:54 GMT</pubDate>
            <atom:updated>2026-03-31T08:22:35.159Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tags:</strong> NestJS, Pino, Production, Observability</p><blockquote><em>Why the default NestJS logger quietly holds you back in production and how to replace it with a structured, blazing-fast alternative in one module.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*Gzh2HC470uziXt-j" /></figure><h3>The Problem with NestJS’s Default Logger</h3><p>NestJS ships with a built-in Logger from @nestjs/common. For local development it works fine with colourful output, timestamps, class context. But the moment you deploy to production, the seams start to show.</p><p>The default logger writes plain <strong>human-readable strings</strong>. That seems ok until you’re staring at a k8s dashboard trying to filter by request Id or correlate a spike in 500 errors to a specific service. Because the logs are strings and not a structured data that the machine can read and query.</p><p>A typical NestJS default log line looks like this:</p><pre>[Nest] 28705  - 03/31/2026, 12:21:49 PM   DEBUG [PgService] PG Connection established.<br>[Nest] 28705  - 03/31/2026, 12:21:49 PM     LOG [NestApplication] Nest application successfully started +3ms</pre><p>There is no field for userId, no durationMs, no traceId. It is fundamentally unqueryable in any log aggregation platform.</p><p>Beyond the structure of this setup, there are two more quiet problems, which are <strong>performance</strong> and <strong>HTTP visibility</strong>. The default logger has no automatic HTTP request/response logging. And it’s synchronous, blocking the event loop on every write in high-throughput traffic.</p><h3>What we’re actually solving</h3><p>Before reaching for a library, we need to understand what we need:</p><ol><li><strong>Structured JSON output: </strong>Every log line is a JSON object. Log platforms like ELK stack can index fields individually. You can filter level=error AND service=payments AND userId=123.</li><li><strong>Automatic HTTP request logging: </strong>Every incoming request and outgoing response gets logged with method, path, status code, and duration without a single line of middleware code from you.</li><li><strong>Request correlation across the whole request lifecycle: </strong>ArequestId is stamped on every log line that happens <em>inside</em> the handling of that request not just the HTTP layer. So you can trace a single request through guards, interceptors, services, and repositories.</li><li><strong>Non-blocking async writes: </strong>Pino uses a worker thread to flush logs so your app’s hot path is never blocked waiting for a write syscall.</li><li><strong>Sensitive data redaction: </strong>Auth tokens, cookies, and PII never land in your log storage. Configured once, enforced everywhere.</li></ol><h3>Pino vs. Winston vs. the Default</h3><p>There are three realistic choices when replacing the NestJS logger: stick with the built-in, reach for Winston (the traditional Node.js choice), or use Pino. Here’s how they compare on dimensions that actually matter in production:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e0e220e7a68f3a59df69379d105abf/href">https://medium.com/media/91e0e220e7a68f3a59df69379d105abf/href</a></iframe><blockquote><strong><em>Why Pino is so fast:</em></strong><em> Pino uses a technique called </em>deferred serialisation<em>. When you call </em><em>logger.info({ user }), Pino doesn&#39;t immediately stringify the object but it rather batches log entries and processes them in a dedicated worker thread, keeping your application&#39;s event loop free. It also avoids object allocation in hot paths by reusing internal buffers. think use of JIT compiler like.</em></blockquote><h3>What nestjs-pino Does Under the Hood</h3><p>Before writing a single line of config, it helps to understand the three-layer system you’re setting up. Many tutorials skip this and leave you unable to debug when something unexpected happens.</p><p>Here’s the internal architecture for a single request lifecycle:</p><pre>Your NestJS application code<br>        ↓  (inject Logger, call logger.log())<br>nestjs-pino Logger (DI provider)<br>        ↓  (wraps pino-http, implements NestJS LoggerService interface)<br>pino-http middleware           ← THE KEY LAYER<br>        ↓  (binds child logger to AsyncLocalStorage per request)<br>pino core logger<br>        ↓  (serialises to JSON, applies redact rules)<br>transport layer<br>        ↓  (stdout / pino-pretty in dev / external sink)</pre><p>The crucial piece is the <strong>pino-http middleware</strong> layer. When a request comes in, pino-http creates a <em>child logger </em>instance that inherits all the parent’s config but carries an additional context object with the request ID, method, and URL. This child logger is stored in AsyncLocalStorage for the duration of the request.AsyncLocalStorage is Node.js&#39;s built-in mechanism for carrying context across async boundaries without passing it explicitly. It&#39;s similar to thread-local storage in other runtimes.</p><p>When you call logger.log(&#39;cache miss&#39;) inside a service, nestjs-pino looks up the current AsyncLocalStorage store, finds the child logger for the active request, and routes your message through it. The result: every log line during that request carries the same req.id.</p><h3>The 3 configuration pieces in code</h3><p>There are exactly three things to wire up, and it matters that you understand what each one does:</p><p><strong>1. </strong><strong>LoggerModule:</strong>This is responsible to register pino-http as an Express middleware and creates the nestjs-pino DI provider. This is your central config: log level, transport (pretty or raw), redaction rules, and serializers.</p><p><strong>2. </strong><strong>app.useLogger(app.get(Logger)):</strong> This part replaces NestJS&#39;s internal logger (used for framework-level messages like &quot;Nest application started&quot;) with pino. Without this, Nest&#39;s own bootstrap logs bypass pino entirely and come out as plain pretty strings.</p><p><strong>3. </strong><strong>AppLoggerModule in </strong><strong>AppModule:</strong>This makes the pino Logger available for injection globally across your entire application. Any service that injects Logger will get the pino-backed one.</p><h3>Setup: Step by Step</h3><h3>1. Install dependencies</h3><pre>pnpm add nestjs-pino pino-http pino<br>pnpm add -D pino-pretty</pre><h3>2. Create the logger module</h3><p>Create a dedicated module to keep logging config isolated and reusable. This module wraps LoggerModule.forRootAsync so it can consume your config service at runtime:</p><pre>src/logger/app-logger.module.ts</pre><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { LoggerModule } from &#39;nestjs-pino&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br>@Module({<br>  imports: [<br>    LoggerModule.forRootAsync({<br>      imports: [ConfigModule],<br>      inject: [ConfigService],<br>      useFactory: (config: ConfigService) =&gt; {<br>        const isDev = config.get(&#39;NODE_ENV&#39;) === &#39;development&#39;;<br>        return {<br>          pinoHttp: {<br>            // Log level by environment<br>            level: isDev ? &#39;debug&#39; : &#39;info&#39;,<br>            // Dev: pretty-printed, colourised, single-line<br>            // Prod: raw JSON (no transport = stdout JSON)<br>            transport: isDev<br>              ? {<br>                  target: &#39;pino-pretty&#39;,<br>                  options: { colorize: true, singleLine: true },<br>                }<br>              : undefined,<br>            // Never log sensitive headers into your storage<br>            redact: [&#39;req.headers.authorization&#39;, &#39;req.headers.cookie&#39;],<br>            // Control exactly which request/response fields are logged<br>            serializers: {<br>              req: (req) =&gt; ({<br>                method: req.method,<br>                url: req.url,<br>                requestId: req.id,<br>              }),<br>              res: (res) =&gt; ({<br>                statusCode: res.statusCode,<br>              }),<br>            },<br>          },<br>        };<br>      },<br>    }),<br>  ],<br>})<br>export class AppLoggerModule {}</pre><h3>3. Register globally in AppModule</h3><pre>src/app.module.ts</pre><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { AppLoggerModule } from &#39;./logger/app-logger.module&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br>    AppLoggerModule, // ← registers pino globally<br>  ],<br>})<br>export class AppModule {}</pre><h3>4. Replace the NestJS internal logger in main.ts</h3><pre>src/main.ts</pre><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { Logger } from &#39;nestjs-pino&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule, {<br>    // Suppress NestJS&#39;s default logger during bootstrap<br>    bufferLogs: true,<br>  });<br>  // Hand over to pino for ALL subsequent logging including Nest internals<br>  app.useLogger(app.get(Logger));<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><blockquote><strong><em>The </em></strong><strong><em>bufferLogs: true option matters.</em></strong><em> Without it, NestJS uses its own logger for the period between </em><em>NestFactory.create() and your </em><em>useLogger() call. That window includes &quot;Nest application starting&quot; messages and any errors during module initialisation. </em><em>bufferLogs: true holds those messages in a buffer and replays them through pino once it&#39;s registered.</em></blockquote><h3>5. Using the logger in your services</h3><pre>import { Logger } from &#39;@nestjs/common&#39;;<br>@Injectable()<br>export class UsersService {<br>  constructor(private readonly logger: Logger) {}<br>  async findOne(id: string) {<br>    this.logger.log({ userId: id }, &#39;Fetching user&#39;);<br>  }<br>}</pre><p>The resulting JSON in production with the request Id is automatically propagated from the HTTP layer:</p><pre>{&quot;level&quot;:30,&quot;time&quot;:1774944584005,&quot;pid&quot;:32936,&quot;hostname&quot;:&quot;archlinux&quot;,&quot;context&quot;:&quot;RouterExplorer&quot;,&quot;msg&quot;:&quot;Mapped {/api/v1/dimensions/user, GET} route&quot;}<br>{&quot;level&quot;:30,&quot;time&quot;:1774944584005,&quot;pid&quot;:32936,&quot;hostname&quot;:&quot;archlinux&quot;,&quot;context&quot;:&quot;NestApplication&quot;,&quot;msg&quot;:&quot;Nest application successfully started&quot;}</pre><h3>Config</h3><h3>Log levels</h3><p>Pino uses numeric levels: trace (10), debug (20), info (30), warn (40), error (50), fatal (60). Setting level: &#39;info&#39; means anything below 30 is suppressed — so your logger.debug() calls are zero-cost in production because pino checks the level before doing any serialisation work.</p><h3>Redaction</h3><p>The redact array accepts dot-notation paths using the fast-redact library under the hood. Common paths to always include:</p><pre>redact: [<br>  &#39;req.headers.authorization&#39;,   // Bearer tokens<br>  &#39;req.headers.cookie&#39;,           // Session cookies<br>]</pre><h3>The Complete Setup at a Glance</h3><p><strong>You now have:</strong></p><ul><li>✅ Automatic HTTP request/response logging</li><li>✅ Per-request correlation IDs</li><li>✅ Structured JSON in production</li><li>✅ Colourised pretty output in development</li><li>✅ Sensitive field redaction</li><li>✅ Full NestJS DI integration</li><li>✅ Zero performance tax on suppressed log levels</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21ee5844bd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Big O, Search and Sort Algorithm]]></title>
            <link>https://medium.com/@rxman/guide-to-big-o-search-and-sort-algorithm-9645f855fa2a?source=rss-336f77d9ad36------2</link>
            <guid isPermaLink="false">https://medium.com/p/9645f855fa2a</guid>
            <dc:creator><![CDATA[Roman Karki]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 17:43:51 GMT</pubDate>
            <atom:updated>2025-09-13T17:43:51.554Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents:</h3><ul><li>Big O Notation</li><li>Searching Algorithms</li><li>Sorting Algorithms</li></ul><h3>Big O Notation</h3><p>Big O notation is a mathematical notation used in computer science to describe the upper bound of the time complexity or space complexity of an algorithm in terms of the size of its input.</p><p>Below is the Graph representation of various Big O:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*EI1zk0kFclgTl-gbRARnVw.png" /></figure><h4>Time Complexity</h4><p>The amount of time taken by an algorithm to run as a function of the size of its input.</p><h4>O(n) — Linear Time</h4><ul><li>The resources usage increases with the increase in input size.</li><li>The graph increases proportionally, which is straight.</li></ul><h4>O(1) — Constant Time</h4><ul><li>The algorithm’s execution time or resource usage remains constant regardless of the input size.</li><li>The graph is horizontal and parallel to the x-axis regardless of input size.</li></ul><h4>O(n²) — Quadratic Time</h4><ul><li>The algorithm’s size of operation is n * n.</li><li>The graph is a parabolic curve that rapidly increases as the input size grows.</li><li>It becomes steeper as the input size increases, indicating an exponential relationship between input size and resource usage.</li></ul><h4>O(n!) — Factorial Time</h4><ul><li>Nested loop for every input we have.</li><li>The most expensive and steepest graph in the Big O Notation.</li></ul><h4>O(n log n) — Linearithmic Time</h4><ul><li>The algorithm’s resource usage grows in a near-linear fashion but is more efficient than quadratic time.</li><li>Commonly seen in efficient sorting algorithms like merge sort and quicksort.</li><li>The graph has a steeper slope compared to O(n), indicating a faster growth rate as the input size increases.</li></ul><h4>Big O Rule</h4><ul><li>Worst case: Search item at the end of the array while looping.</li><li>Best Case: Search item at the beginning of the array.</li><li>Remove Constants: O(n+1), O(3n + 4), O(2n) — everything is O(n).</li><li>Nested dependency of n: If there is nested n dependency, the time complexity is represented as O(n * n), i.e., O(n²).</li><li>Drop non-dominant: In case of O(n + n²), we drop the non-dominant term, i.e., n on the front. It becomes O(n²), O(n³), and so on.</li></ul><h4>Good Code</h4><ol><li>Readability</li><li>Scalability</li><li>Three pillars to identify the best code:</li></ol><blockquote>Readable.</blockquote><blockquote>Speed (Time complexity).</blockquote><blockquote>Memory usage (Space complexity).</blockquote><h4>Space Complexity</h4><p>The amount of memory taken by an algorithm to run as a function of the size of its input.</p><ul><li>How much of inputs a function can take?</li><li>If there is less memory and more inputs to be stored, it might overflow, known as Stack Overflow.</li><li><strong>Causes</strong>:</li></ul><blockquote>Variables.</blockquote><blockquote>Data Structures.</blockquote><blockquote>Function calls.</blockquote><blockquote>Allocations.</blockquote><h4>TLE (Time Limit Exceeded)</h4><p>An error message that is returned when the time taken to execute a program takes longer than the time limit allowed.<br>Processor being able to compute 10⁸ operations per second<br>Here is the list of rules that will help to optimize the program and not exceed the time limit:</p><p><strong>Solutions:</strong> Optimize Algorithm, Reduce Input Size, Use Early Exit, Dynamic Programming and Block Infinite Loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*bEMB-Qx3Cy9M7Ix2DK0WfQ.png" /></figure><h3>Searching Algorithm</h3><h4>Linear Search O(n)</h4><ul><li>Simple search algorithm for finding a target value within a list.</li><li>Iterates through elements, comparing them to the target.</li><li>Returns the index of the target or a signal for absence.</li></ul><h4>Binary Search O(log n)</h4><ul><li>Efficient search in sorted data (Sorting is compulsory).</li><li>Divides the search interval in half, reducing elements to check (making search range concise).</li><li>Steps:</li></ul><ol><li>Start with the middle element.</li><li>If it’s the target, the search is done.</li><li>If the target is greater, search the upper half.</li><li>If the target is smaller, search the lower half.</li><li>Repeat until found or interval is empty.</li></ol><h4>Linear VS Binary search</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e93eb0f81b4312b90f280c977a6dc71/href">https://medium.com/media/6e93eb0f81b4312b90f280c977a6dc71/href</a></iframe><h4>Application of Binary search</h4><ul><li>Finding Number of Occurrences</li><li>Searching in Rotated Arrays</li><li>Square Root Approximation</li><li>Matrix Search</li><li>Closest Value Search</li><li>Peak Element Search</li><li>Finding First and Last Occurrences</li><li>Checking Element Existence</li><li>String Matching</li><li>Exponential Search</li><li>Lower Bound and Upper Bound Searches</li><li>Finding Missing Element</li></ul><h3>Sorting Algorithms</h3><p>Sorting is the process of arranging a collection of data elements in a specific order, either ascending or descending. Some sorting algorithms are <strong>stable</strong>, meaning that equal elements maintain their relative order in the sorted output.</p><h4>1. Selection Sort</h4><p>Selection Sort is simple but not efficient for large datasets. It works by repeatedly selecting the smallest (or largest) element from the unsorted portion and placing it at the beginning of the sorted portion.</p><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> O(1)</li><li><strong>Use Case:</strong> Small arrays, memory-limited environments</li></ul><p><strong>How it Works:</strong></p><ol><li>Find the minimum element in the unsorted portion of the array.</li><li>Swap it with the first element of the unsorted portion.</li><li>Move the boundary between sorted and unsorted portions one element forward.</li><li>Repeat until the entire array is sorted.</li></ol><h4>2. Bubble Sort</h4><p>Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.</p><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> O(1)</li><li><strong>Use Case:</strong> Small arrays, educational purposes</li></ul><p><strong>How it Works:</strong></p><ol><li>Start from the first element of the array.</li><li>Compare each pair of adjacent elements and swap them if they are out of order.</li><li>After each pass, the largest unsorted element “bubbles” to its correct position.</li><li>Repeat passes until no swaps occur in a pass.</li></ol><h4>3. Insertion Sort</h4><p>Insertion Sort builds a sorted portion of the array one element at a time by inserting each element into its correct position.</p><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> O(1)</li><li><strong>Use Case:</strong> Small or nearly sorted arrays</li></ul><p><strong>How it Works:</strong></p><ol><li>Divide the array into sorted and unsorted regions.</li><li>Take the first element from the unsorted region.</li><li>Compare it with elements in the sorted region and shift larger elements to the right.</li><li>Insert the element in its correct position in the sorted region.</li><li>Repeat until the unsorted region is empty.</li></ol><h4>4. Merge Sort</h4><p>Merge Sort is an efficient, divide-and-conquer algorithm that divides the array, sorts the halves, and merges them.</p><ul><li><strong>Time Complexity:</strong> O(n log n)</li><li><strong>Space Complexity:</strong> O(n)</li><li><strong>Use Case:</strong> Large datasets</li></ul><p><strong>How it Works:</strong></p><ol><li>Divide the array into two halves.</li><li>Recursively sort the left half.</li><li>Recursively sort the right half.</li><li>Merge the two sorted halves into a single sorted array.</li><li>Repeat until the entire array is merged and sorted.</li></ol><h4>5. Quick Sort</h4><p>Quick Sort is a highly efficient, divide-and-conquer algorithm. It partitions the array around a pivot element and recursively sorts the partitions.</p><ul><li><strong>Time Complexity:</strong> O(n log n) on average, O(n²) worst case</li><li><strong>Space Complexity:</strong> O(log n)</li><li><strong>Use Case:</strong> Large datasets, efficient average-case sorting</li></ul><p><strong>How it Works:</strong></p><ol><li>Choose a pivot element from the array.</li><li>Partition the array into two parts: elements smaller than the pivot on the left, elements larger than the pivot on the right.</li><li>Recursively apply Quick Sort to the left partition.</li><li>Recursively apply Quick Sort to the right partition.</li><li>Repeat until all partitions are sorted.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca109f28e9923fcd22e6754dabae420/href">https://medium.com/media/fca109f28e9923fcd22e6754dabae420/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9645f855fa2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing in Machine Learning]]></title>
            <link>https://medium.com/@rxman/data-preprocessing-in-machine-learning-36405bad8698?source=rss-336f77d9ad36------2</link>
            <guid isPermaLink="false">https://medium.com/p/36405bad8698</guid>
            <category><![CDATA[data-preprocessing-steps]]></category>
            <category><![CDATA[data-preprocessing-guide]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Roman Karki]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 06:42:40 GMT</pubDate>
            <atom:updated>2025-02-18T06:42:40.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*INuSlUfVkF7SL0C0.jpg" /><figcaption>Data PreProcessing</figcaption></figure><p>Data preprocessing is the crucial step in any machine learning pipeline. Ununiformed data or unsanitized data can lead a model to have poor predictions. So it is important for us to pre process the data before feeding to the model to improve the performance and reliability. This article outlines the key steps of data preprocessing, their importance and best practices for effective data cleaning and preparation.</p><p><strong>Key Contents</strong></p><ol><li>Handling Missing Data</li><li>Encoding Categorical Data</li><li>Feature Engineering</li><li>Best Practices</li></ol><h3>1. Handling Missing Data</h3><p>Handling missing data is essential to prevent the loss of information, and avoid biasness or errors that may get introduced while analyzing and evaluating a ml model. For numerical values, some of the widely used technique is to fill with the mean or median. However for categorical data mode is much preferred along with custom labels. Some tools to fill missing data from a dataset are:</p><ul><li>SimpleImputer from scikit, and</li><li>fillna() from pandas</li></ul><h3><strong>2. Encoding categorical data</strong></h3><p>Most machine learning algorithms can only interpret data in numerical format. So, categorical data needs to be encoded to numerical values. Some ways to convert categorical data to numerical are Binary encoding, Ordinal encoding, Frequency encodingm Target encoding, Feature hashing, and mostly used Label Encoding and One-Hot Encoding.</p><h4>2.1. Label Encoding</h4><p>Label encoding assigns a unique category to an integer.</p><pre>[“Red”, “Blue”, “Green”] converts to [0, 1, 2]</pre><p>It is best suited for ordinal data like education, and others having no inherent order.</p><blockquote><strong>Limitations: </strong>It can introduce false hierarchies and numerical relationships among categories that do not exist, which can mislead the model during training.</blockquote><h4><strong>2.2. One-Hot Encoding</strong></h4><p>It is also known as dummy encoding which transforms each unique label in the categorical column to a separate binary column.</p><pre>[“Red”, “Blue”, “Green”] converts to [1, 0, 0], [0, 1, 0], [0, 0, 1]</pre><p>Where each label has separate columns, filled with binary values. (also addresses missing category by representing all new category column as 0&#39;s). It is based suited for nominal data like colors, brands, cities etc.</p><blockquote><strong>Limitations</strong></blockquote><blockquote>It can lead to high dimensional feature in the dataset making computation and storage expensive.</blockquote><blockquote>Introduction to Muliticollinearity and Data Sparsity (all zeroes when there is large categories)</blockquote><h4><strong>2.3. Binary Encoding</strong></h4><p>It is the combination of both label and one hot encoding while reducing the dimensionality.</p><pre>[“Red”, “Blue”, “Green”] converts to [0, 0], [0, 1], [1, 1]</pre><p>Where the categories are converted through label encoding making [0, 1, 2] and then converted with one hot encoding to get binary representation of all values as [0, 0], [0, 1], [1, 1].</p><p>It works best for high cardinality data like products, countries etc. The count of final added columns will be log2(N), as 2 power N can accomodate N number of categories.</p><h4>2.4. Ordinal Encoding</h4><p>Ordinal encoding assigns a unique integer to each category based on its natural order.</p><pre>[“Low”, “Medium”, “High”] converts to [0, 1, 2]. </pre><p>It is either alphabetical ordered or custom mapped. It is best suited for ordinal data where the categories have a meaningful order (or inherent order) (e.g., education levels, rating scales).</p><blockquote><strong>Limitations: </strong>It may assume that the difference between adjacent categories is the same, which can be misleading if the actual differences are not equal.</blockquote><h4><strong>2.5. Frequency Encoding</strong></h4><p>Frequency encoding assigns numerical values to categories based on their frequency of occurrence in the dataset.</p><pre>[“Red”, “Blue”, “Blue”, “Green”, “Red”, “Red”] converts to [3, 2, 2, 1, 3, 3]</pre><p>Where each category is replaced by the number of time they occur in the dataset. It is best suited for data where frequency of the categories has impact over the target column and we need to reduce the dimensions.</p><blockquote><strong>Limitations</strong></blockquote><blockquote>It does not preserve the categorical identity.</blockquote><blockquote>Non linearity assumptions</blockquote><blockquote>Bias Introduction</blockquote><h4><strong>2.6. Feature Hashing</strong></h4><p>Feature Hashing, also known as the <em>Hashing Trick</em>, transforms categorical data into numerical features by applying a hash function to each category. This function maps categories to a fixed number of columns using a modulo operation.</p><pre>[“Red”, “Blue”, “Green”] will produce [1, 0, 0], [0, 1, 0], [0, 0, 1].</pre><p>It is best suited for high cardinality data where memory and computational resources are limited. It is less interpretable than binary encoding.</p><blockquote><strong>Limitations</strong></blockquote><blockquote>Hash Collision</blockquote><blockquote>Loss of interpretability</blockquote><blockquote>Limited use in small dataset</blockquote><h4><strong>2.7. Target Encoding</strong></h4><p>Target encoding, also known as mean encoding, replaces each category in a categorical feature with the mean of the target variable for that category.</p><p>It is best suited for high cardinality data and regression problems with continous variables to predict. Optimum technique to capture categorical feature and the target in place of OneHot encoding.</p><p>Smoothing techniques:</p><blockquote><strong>Limitations</strong></blockquote><blockquote>Overfitting if there is not enough sample for each item.</blockquote><blockquote>Data Leakage if the mean calculated is based on the entire dataset instead of the training-valildation split.</blockquote><h3><strong>3. Feature Engineering</strong></h3><h4><strong>3.1. Split into Training and Testing sets</strong></h4><p>Before applying any transformations, we need to split the dataset into training and testing sets. This ensures that the model is evaluated on data it hasn’t seen during training, preventing data leakage. Typically, a 70–80% split for training and 20–30% for testing is used.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Same random state makes test data same across multiple run of same model.</p><h4><strong>3.2. Feature Scaling</strong></h4><p>Feature Scaling adjusts the range of features in a dataset to bring them into alignment, typically using techniques like normalization or standardization. It is important because many machine learning algorithms (e.g., gradient descent-based models, SVMs) are sensitive to feature magnitudes. Without scaling, features with larger ranges can dominate the model, leading to biased results and slower convergence.</p><blockquote>Features Scaling is performed after splitting the dataset to prevent data leakage.</blockquote><h4><strong>3.2.1. Normalization</strong></h4><p>Normalization, also known as Min-Max Scaling, rescales the data so that it lies within a specific range, typically [0, 1]. This scaling technique is useful when we want all features to have the same scale, especially when the model relies on the magnitude of the input features (like in distance-based algorithms such as k-NN).</p><p>Formula for Min-Max Normalization:</p><p><em>x normalized = (x − x min) / (x max​ − x min)</em></p><p>The transformed values are guaranteed to fall within the specified range (typically [0, 1]) and the relationships between values are preserved, which can be important when analyzing data for certain machine learning models.</p><blockquote><strong>Limitations: </strong>It is sensitive to outliers which may distort the range of the datapoints and it is not roboust to frequent changes in data and needs to get calculated frequently.</blockquote><h4><strong>3.2.2. Standardization</strong></h4><p>Standardization, or Z-Score Scaling, rescales the data by transforming it to have a mean of 0 and a standard deviation of 1. This technique is particularly effective when the data is normally distributed, and it’s widely used for machine learning algorithms that assume the data follows a Gaussian distribution (such as linear regression, logistic regression, and neural networks).</p><p>Formula for Standardization (Z-Score Scaling): <em>z = x−μ / σ</em></p><p>This is the most effective scaling technique which works almost all the time because of the following reasons:</p><ul><li>The values are bounded within a specific range.</li><li>It is less sensative to outliers than the normalization.</li><li>It performs well with ml models that assumes the dataset to be normally distributed.</li></ul><blockquote><strong>Limitations:</strong> Assumptions of a normal distribution</blockquote><p><em>While Normalization is ideal for ml models that uses distance based metrics like (k-NN), Standardization is suitable for normally distributed dataset, where datapoints are centered and scaled (linear regression, logistic regression, PCA).</em></p><h4><strong>3.3. Transformation to Test Set</strong></h4><p>Once we are done with all the preprocessing the training data after train-test split, it is important to apply the same transformations and feature engineering techniques to the test set as well. This particularly helps prevent data leakage to train set and influence the independent evaluation.</p><p>Some key points to remember for transformation of testing set are:</p><ul><li>Apply all transformations (encoding, scaling, etc.) to the test set using parameters from the training set.</li><li>Avoid leaking information and extract the metrics from training set alone.</li><li>Ensure consistency in transforming and feature engineering between training and testing set.</li></ul><h3>Summary</h3><p>In machine learning, data preprocessing plays an essential role in efficiency and reliability of models. Here is the summary of the topics discussed above:</p><ol><li>Handling missing values case by case.</li><li>Choosing the right encoding techniques for categorical variables.</li><li>Splitting the data to training and testing dataset to avoid data leakage.</li><li>Different techniques to scale the features.</li></ol><p>By carefully considering each preprocessing step, we can lay the groundwork for building robust, scalable, and accurate machine learning models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36405bad8698" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>