<?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 Nkumar on Medium]]></title>
        <description><![CDATA[Stories by Nkumar on Medium]]></description>
        <link>https://medium.com/@nkumar73686?source=rss-39cdb87d635e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vbEBXGKIsZqyqGwt</url>
            <title>Stories by Nkumar on Medium</title>
            <link>https://medium.com/@nkumar73686?source=rss-39cdb87d635e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:11:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nkumar73686/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[K-Nearest Neighbors (KNN): Understanding One of the Simplest Machine Learning Algorithms]]></title>
            <link>https://medium.com/@nkumar73686/k-nearest-neighbors-knn-understanding-one-of-the-simplest-machine-learning-algorithms-7332c5c6b5fb?source=rss-39cdb87d635e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7332c5c6b5fb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[Nkumar]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 07:40:26 GMT</pubDate>
            <atom:updated>2026-11-03T07:40:26.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>How can a machine predict something by looking at its nearest neighbors?</h3><p>Machine Learning is all about teaching computers to learn from data and make predictions. There are many algorithms used in Machine Learning, and one of the easiest to understand is <strong>K-Nearest Neighbors (KNN)</strong>.</p><p>Imagine you move to a new city and want to know whether a neighborhood is safe. You might ask people who live nearby and make a decision based on their experiences.</p><p>KNN works in a similar way. Instead of learning from a complicated mathematical model, it looks at the closest data points and makes predictions based on them.</p><p>Let’s understand how it works!</p><h3><strong>1. What is K-Nearest Neighbors (KNN)?</strong></h3><p>K-Nearest Neighbors (KNN) is a <strong>supervised Machine Learning algorithm</strong> used for both classification and regression problems.</p><p>It makes predictions by finding the K closest data points to a new data point.</p><p>Here:</p><ul><li><strong>K</strong> represents the number of nearest neighbors.</li><li><strong>Nearest</strong> refers to the closest data points.</li><li><strong>Neighbors</strong> are the existing data points in the dataset.</li></ul><p>KNN compares a new data point with existing data and predicts its result based on similarity.</p><p>One interesting thing about KNN is that it is called a <strong>lazy learning algorithm</strong> because it doesn’t build an explicit model during training. Instead, it stores the training data and performs calculations when a prediction is required.</p><h3>2. How Does KNN Work?</h3><p>KNN follows three main steps:</p><p><strong>Step 1: Choose the value of K</strong></p><p>First, select how many neighbors the algorithm should consider.</p><p>For example, if K = 3, the algorithm considers the three closest data points.</p><p><strong>Step 2: Calculate the distance</strong></p><p>KNN calculates the distance between the new data point and the existing data points.</p><p>A commonly used method is Euclidean Distance.</p><p><strong>Step 3: Make a prediction</strong></p><ul><li>For classification, the algorithm selects the majority class among the nearest neighbors.</li><li>For regression, it calculates the average value of the nearest neighbors.</li></ul><p>That’s how KNN makes predictions!</p><h3>3. Understanding KNN with a Real-World Example</h3><p>Imagine a school wants to predict whether a student will pass or fail an examination based on study hours and previous academic performance.</p><p>We have two categories:</p><ul><li>Red points: Pass</li><li>Blue points: Fail</li></ul><p>Now, imagine a new student whose result is unknown.</p><p>KNN checks the nearest students and identifies their results.</p><p>If K = 5 and:</p><ul><li>3 nearby students passed.</li><li>2 nearby students failed.</li></ul><p>The algorithm predicts that the new student will <strong>Pass</strong>, because Pass has the majority vote. This is called Majority Voting.</p><h3>4. Mathematical Formula Behind KNN</h3><p>KNN commonly uses Euclidean Distance to measure the distance between two data points.</p><p>The formula is:</p><p>Distance = √[(x₂ − x₁)² + (y₂ − y₁)²]</p><p>Where:</p><ul><li>x₁, y₁ represent the coordinates of the first point.</li><li>x₂, y₂ represent the coordinates of the second point.</li></ul><p>The smaller the distance, the closer the data points are.</p><h3>5. Types of KNN</h3><p>KNN is mainly used for two types of Machine Learning tasks.</p><p><strong>1. KNN Classification</strong></p><p>Classification predicts a category or class.</p><p>Examples:</p><ul><li>Email: Spam or Not Spam.</li><li>Student: Pass or Fail.</li><li>Tumor: Benign or Malignant.</li></ul><p><strong>2. KNN Regression</strong></p><p>Regression predicts a numerical value.</p><p>Examples:</p><ul><li>Predicting house prices.</li><li>Estimating product prices.</li><li>Predicting temperature.</li></ul><h3>6. What is the Importance of Choosing K?</h3><p>Choosing the correct K value is important for getting better predictions.</p><ul><li>Small K (K = 1): The algorithm considers only one neighbor. It can be sensitive to noise and overfitting.</li><li>Large K: It considers more neighbors. It can produce smoother predictions but may underfit.</li></ul><p>A common starting point is K = 5, but the best value depends on the dataset.</p><p>We can use cross-validation to find a suitable K value.</p><h3>7. Advantages of KNN</h3><ul><li>Easy to understand and implement.</li><li>Works for both classification and regression.</li><li>No complicated training process.</li><li>Can handle nonlinear decision boundaries.</li><li>Useful for recommendation and similarity-based tasks.</li></ul><h3>8. Disadvantages of KNN</h3><ul><li>Slow predictions with large datasets.</li><li>Requires more memory because it stores training data.</li><li>Sensitive to irrelevant features and noisy data.</li><li>Performance can decrease with high-dimensional data.</li><li>Feature scaling is important because distance calculations depend on feature values.</li></ul><h3>9. Real-World Applications of KNN</h3><p>KNN is used in several areas:</p><p><strong>Healthcare:</strong> Helps classify medical data and support disease prediction.</p><p><strong>Recommendation Systems:</strong> Finds similar users or products to recommend relevant items.</p><p><strong>Fraud Detection:</strong> Helps identify transactions that resemble known fraudulent patterns.</p><p><strong>Image Recognition:</strong> Classifies images by comparing their feature representations.</p><p><strong>Finance:</strong> Can be used for credit-risk classification and other prediction tasks.</p><h3>10. Python Implementation of KNN</h3><p>Let’s implement a simple KNN classification model using Scikit-learn.</p><pre>from sklearn.neighbors import KNeighborsClassifier</pre><pre># Training data<br>X = [[1, 2], [2, 3], [3, 3],<br>     [6, 7], [7, 8], [8, 8]]</pre><pre># Labels<br>y = [&#39;Pass&#39;, &#39;Pass&#39;, &#39;Pass&#39;,<br>     &#39;Fail&#39;, &#39;Fail&#39;, &#39;Fail&#39;]</pre><pre># Create KNN model<br>knn = KNeighborsClassifier(n_neighbors=3)</pre><pre># Train the model<br>knn.fit(X, y)</pre><pre># Predict a new data point<br>prediction = knn.predict([[2, 2]])</pre><pre>print(&quot;Prediction:&quot;, prediction)</pre><p><strong>Output:</strong></p><pre>Prediction: [&#39;Pass&#39;]</pre><p>In this example, we selected K = 3. The algorithm checks the three nearest training points and predicts the majority class.</p><h3>Conclusion</h3><p>K-Nearest Neighbors is one of the simplest yet powerful Machine Learning algorithms.</p><p>Its main concept is based on similarity: data points that are close to each other are more likely to have similar characteristics.</p><p>Although KNN has some limitations, such as computational cost and sensitivity to feature scaling, it remains an important algorithm for understanding supervised Machine Learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jqb1GGerbm5dV6eA7dHRA.png" /><figcaption><strong>K-Nearest Neighbour Algorithm</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7332c5c6b5fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Preprocessing in NLP: Bag of Words (BoW) and TF-IDF]]></title>
            <link>https://medium.com/@nkumar73686/text-preprocessing-in-nlp-bag-of-words-bow-and-tf-idf-3fb17f5fc77f?source=rss-39cdb87d635e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb17f5fc77f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Nkumar]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:43:10 GMT</pubDate>
            <atom:updated>2026-11-03T06:43:10.908Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever wondered how computers understand human language?</p><p>We communicate using words, sentences, and paragraphs. However, computers and Machine Learning algorithms work with numerical data rather than directly understanding human language.</p><p>This is where <strong>Natural Language Processing (NLP)</strong> comes into the picture.</p><p>NLP is a branch of Artificial Intelligence that helps computers process, understand, and analyze human languages.</p><p>Before applying Machine Learning algorithms to text data, we need to clean and convert the text into a numerical format. This process is called <strong>Text Preprocessing</strong>.</p><p>Two popular techniques used to convert text into numerical representations are:</p><ol><li>Bag of Words (BoW)</li></ol><p>2. TF-IDF (Term Frequency–Inverse Document Frequency)</p><p>Let’s understand both techniques with simple examples.</p><h3>1. What is Text Preprocessing?</h3><p>Text preprocessing is the process of cleaning and transforming raw text into a structured format that Machine Learning algorithms can understand.</p><p>Real-world text data often contains:</p><ul><li>Unnecessary punctuation.</li><li>Uppercase and lowercase variations.</li><li>Stop words such as “is”, “the”, “a”, and “an”.</li><li>Different forms of the same word.</li><li>Extra spaces and special characters.</li></ul><h3>Common steps in text preprocessing</h3><p><strong>1. Lowercasing</strong></p><p>Converts all text into lowercase.</p><p>Example:</p><p>Original: “MACHINE Learning Is Amazing”</p><p>Output: “machine learning is amazing”</p><p><strong>2. Tokenization</strong></p><p>Splits a sentence into individual words or tokens.</p><p>Example:</p><p>Input: “I love Machine Learning”</p><p>Output: [“I”, “love”, “Machine”, “Learning”]</p><p><strong>3. Stop Word Removal</strong></p><p>Removes commonly occurring words that may not contribute much information.</p><p>Example:</p><p>Input: “I am learning machine learning”</p><p>Output: [“learning”, “machine”, “learning”]</p><p><strong>4. Stemming</strong></p><p>Reduces words to their root-like form by removing prefixes or suffixes.</p><p>Example:</p><p>Playing → Play<br>Studies → Studi</p><p><strong>5. Lemmatization</strong></p><p>Converts words into their meaningful dictionary form.</p><p>Example:</p><p>Running → Run<br>Better → Good</p><p>After these steps, the text becomes cleaner and more suitable for feature extraction.</p><h3>2. What is Bag of Words (BoW)?</h3><p>Bag of Words is one of the simplest techniques used in Natural Language Processing to convert text into numerical data.</p><p>It represents a document by counting how many times each word appears.</p><p>The important point is that <strong>BoW considers word frequency but ignores grammar and word order.</strong></p><h3>How does Bag of Words work?</h3><p>Let’s take three sentences:</p><ul><li>Document 1: “I love machine learning”</li><li>Document 2: “I love artificial intelligence”</li><li>Document 3: “Machine learning is amazing”</li></ul><p><strong>Step 1: Create a vocabulary</strong></p><p>Collect all unique words from the documents.</p><p>Vocabulary:</p><p>[“I”, “love”, “machine”, “learning”, “artificial”, “intelligence”, “is”, “amazing”]</p><p><strong>Step 2: Count word occurrences</strong></p><p>Count how many times each vocabulary word appears in each document.</p><p><strong>Step 3: Convert text into numerical vectors</strong></p><p>WordDoc 1Doc 2Doc 3I110love110machine101learning101artificial010intelligence010is001amazing001</p><p>Now, our text data has been converted into numerical vectors.</p><h3>Python implementation of Bag of Words</h3><p>We can implement Bag of Words using Scikit-learn.</p><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>documents = [<br>    &quot;I love machine learning&quot;,<br>    &quot;I love artificial intelligence&quot;,<br>    &quot;Machine learning is amazing&quot;<br>]</pre><pre>cv = CountVectorizer()</pre><pre>X = cv.fit_transform(documents)</pre><pre>print(cv.get_feature_names_out())<br>print(X.toarray())</pre><p><strong>Output:</strong> Each row represents a document, and each column represents a word frequency.</p><h3>Advantages of BoW</h3><ul><li>Simple and easy to implement.</li><li>Converts text into numerical features.</li><li>Useful for basic text classification.</li><li>Works well with smaller text datasets.</li></ul><h3>Disadvantages of BoW</h3><ul><li>Ignores word order and grammar.</li><li>Does not understand the meaning of words.</li><li>Common words can receive high importance.</li><li>Can create large and sparse feature matrices.</li></ul><h3>3. What is TF-IDF?</h3><p>TF-IDF stands for <strong>Term Frequency–Inverse Document Frequency</strong>.</p><p>It is another popular technique used in NLP to convert text into numerical representations.</p><p>Unlike Bag of Words, TF-IDF does not simply count how many times a word appears.</p><p>Instead, it calculates the importance of a word in a document compared with how frequently that word appears across the entire collection of documents.</p><p>In simple words:</p><p><strong>TF-IDF gives more importance to words that are frequent in a particular document but less common across other documents.</strong></p><h3>How does TF-IDF work?</h3><p>TF-IDF consists of two important components.</p><p><strong>1. Term Frequency (TF)</strong></p><p>Measures how frequently a word appears in a particular document.</p><p>Formula:</p><p>TF = Number of times a word appears / Total number of words in the document</p><p>Example:</p><p>Document: “Machine learning is amazing”</p><p>The word “Machine” appears once.</p><p>TF = 1/4 = 0.25</p><p><strong>2. Inverse Document Frequency (IDF)</strong></p><p>Measures how rare or common a word is across all documents.</p><p>A word appearing in almost every document receives a lower IDF score.</p><p>A word appearing in only a few documents receives a higher IDF score.</p><p>A common formula is:</p><p>IDF = log(Total number of documents / Number of documents containing the word)</p><p><strong>3. Final TF-IDF calculation</strong></p><p>TF-IDF = TF × IDF</p><p>The final score represents the importance of a word in a particular document relative to the entire document collection.</p><h3>Python implementation of TF-IDF</h3><p>We can implement TF-IDF using Scikit-learn.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre>documents = [<br>    &quot;I love machine learning&quot;,<br>    &quot;I love artificial intelligence&quot;,<br>    &quot;Machine learning is amazing&quot;<br>]</pre><pre>tfidf = TfidfVectorizer()</pre><pre>X = tfidf.fit_transform(documents)</pre><pre>print(tfidf.get_feature_names_out())<br>print(X.toarray())</pre><p><strong>Output:</strong> Each document is represented by a numerical vector containing TF-IDF scores instead of simple word counts.</p><p>Note: Scikit-learn uses a smoothed IDF formula by default, so its numerical values may differ from the basic formula shown earlier.</p><h3>Advantages of TF-IDF</h3><ul><li>Gives importance to informative words.</li><li>Reduces the influence of frequently occurring words.</li><li>Useful for document classification.</li><li>Commonly used in search engines and information retrieval.</li></ul><h3>Disadvantages of TF-IDF</h3><ul><li>Does not understand the actual meaning of words.</li><li>Ignores word order and context.</li><li>Can generate large sparse matrices.</li><li>Cannot understand synonyms automatically.</li></ul><h3>4. Difference Between Bag of Words and TF-IDF</h3><p>Both techniques convert text into numerical representations, but their approaches are different.</p><p>FeatureBag of WordsTF-IDFFull formBag of WordsTerm Frequency–Inverse Document FrequencyWorkingCounts word occurrencesCalculates word importanceWord frequencyYesYesCommon wordsNot automatically down-weightedDown-weightedOutputWord count vectorsWeighted vectorsComplexitySimpleSlightly more complexApplicationsBasic text classificationSearch engines and text classification</p><h3>5. Real-World Applications</h3><p>Where are these techniques used in the real world?</p><p><strong>1. Spam Detection</strong></p><p>Email systems can use BoW or TF-IDF features to identify suspicious words and classify emails as spam or legitimate.</p><p><strong>2. Search Engines</strong></p><p>TF-IDF can help identify important terms in documents and improve keyword-based information retrieval.</p><p><strong>3. Sentiment Analysis</strong></p><p>These techniques can convert customer reviews into numerical features to help classify opinions as positive, negative, or neutral.</p><p><strong>4. News Classification</strong></p><p>News articles can be categorized into sports, politics, business, entertainment, and other categories using text features.</p><p><strong>5. Document Similarity</strong></p><p>TF-IDF vectors can be compared using cosine similarity to find documents containing similar terms.</p><h3>6. BoW vs TF-IDF: Which One Should You Choose?</h3><p>The choice depends on the problem you are trying to solve.</p><ul><li>Choose <strong>Bag of Words</strong> when you need a simple word-frequency representation.</li><li>Choose <strong>TF-IDF</strong> when you want to give more importance to informative words and reduce the influence of common words.</li></ul><p>Both techniques are useful starting points for learning NLP and traditional Machine Learning.</p><h3>Conclusion</h3><p>Text preprocessing is an important step in Natural Language Processing because Machine Learning algorithms require numerical data to work with text.</p><p>Bag of Words converts text into numerical vectors by counting word occurrences, while TF-IDF calculates the importance of words based on their frequency within a document and across the document collection.</p><p>Although these techniques do not understand the complete meaning or context of sentences, they provide a strong foundation for traditional NLP applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6fimImotVz98olu11YA2A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb17f5fc77f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Pre-processing: Understanding Encoding and Feature Scaling in Machine Learning]]></title>
            <link>https://medium.com/@nkumar73686/data-pre-processing-understanding-encoding-and-feature-scaling-in-machine-learning-2748c5e594b1?source=rss-39cdb87d635e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2748c5e594b1</guid>
            <category><![CDATA[data-pre-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nkumar]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:30:08 GMT</pubDate>
            <atom:updated>2026-11-03T06:30:08.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever wondered how a Machine Learning model understands data containing words, categories, and numbers?</p><p>Machine Learning algorithms work primarily with numerical data. However, real-world datasets often contain different types of information, such as names, colors, gender categories, locations, prices, and ages.</p><p>Before providing this information to a Machine Learning model, we need to prepare it properly. This process is called <strong>Data Pre-processing</strong>.</p><p>In this article, we will explore two important techniques in data preprocessing:</p><ol><li>Encoding</li><li>Feature Scaling</li></ol><p>Let’s understand how they work and why they are important.</p><h3>1. What is Data Pre-processing?</h3><p>Data Pre-processing is the process of cleaning, transforming, and organizing raw data into a suitable format for Machine Learning algorithms.</p><p>Real-world datasets may contain:</p><ul><li>Missing values.</li><li>Duplicate records.</li><li>Categorical data.</li><li>Different numerical ranges.</li><li>Incorrect or inconsistent values.</li></ul><p>Pre-processing helps improve data quality and prepares it for model training.</p><h3>2. What is Encoding?</h3><p><strong>Encoding is the process of converting categorical data into numerical values so that Machine Learning algorithms can process it.</strong></p><p>For example, imagine a dataset containing information about students:</p><p>StudentFavorite ColorARedBGreenCBlueDRed</p><p>The colors are categorical values. Most traditional Machine Learning algorithms cannot directly process these text categories.</p><p>We can solve this problem using encoding techniques.</p><h3>Types of Encoding</h3><p><strong>A. Label Encoding</strong></p><p>Label Encoding assigns a unique integer to each category.</p><p>Example:</p><p>ColorEncoded ValueRed0Green1Blue2</p><p>Python implementation:</p><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>data = [&#39;Red&#39;, &#39;Green&#39;, &#39;Blue&#39;, &#39;Red&#39;]</pre><pre>le = LabelEncoder()</pre><pre>encoded_data = le.fit_transform(data)</pre><pre>print(encoded_data)</pre><p>Output:</p><pre>[2 1 0 2]</pre><p>Note: The assigned numbers depend on the encoder’s category ordering.</p><p><strong>When can we use it?</strong></p><ul><li>Encoding target labels.</li><li>Converting categories with a genuine order, when using an appropriate ordinal encoding approach.</li></ul><p>Avoid blindly using integer labels for nominal categories because the model may interpret them as having a numerical order.</p><p><strong>B. One-Hot Encoding</strong></p><p>One-Hot Encoding converts each category into a separate binary column containing 0s and 1s.</p><p>Example:</p><p>Original data:</p><p>ColorRedGreenBlue</p><p>After One-Hot Encoding:</p><p>RedGreenBlue100010001</p><p>Python implementation:</p><pre>from sklearn.preprocessing import OneHotEncoder</pre><pre>import numpy as np</pre><pre>data = np.array([<br>    [&#39;Red&#39;],<br>    [&#39;Green&#39;],<br>    [&#39;Blue&#39;],<br>    [&#39;Red&#39;]<br>])</pre><pre>encoder = OneHotEncoder(sparse_output=False)</pre><pre>encoded_data = encoder.fit_transform(data)</pre><pre>print(encoded_data)</pre><p>One-Hot Encoding is useful when categories do not have any natural order.</p><p>For datasets containing many unique categories, it can create a large number of additional columns.</p><h3>3. What is Feature Scaling?</h3><p><strong>Feature Scaling is the process of bringing numerical features into a similar range.</strong></p><p>Consider a dataset containing:</p><p>StudentAgeSalaryA2020,000B2230,000C2550,000</p><p>Here, Age has smaller numerical values compared with Salary.</p><p>Some Machine Learning algorithms are sensitive to differences in feature scales. A feature with large numerical values may influence the model more than expected.</p><p>Feature Scaling helps address this problem.</p><h3>Types of Feature Scaling</h3><p><strong>A. Standardization (Standard Scaler)</strong></p><p>Standardization transforms numerical values so that the resulting feature has:</p><ul><li>Mean = 0</li><li>Standard Deviation = 1</li></ul><p>Formula:</p><p>Z = (X — μ) / σ</p><p>Where:</p><ul><li>X = Original value</li><li>μ = Mean</li><li>σ = Standard deviation</li></ul><p>Python implementation:</p><pre>from sklearn.preprocessing import StandardScaler</pre><pre>data = [[20], [25], [30], [35], [40]]</pre><pre>scaler = StandardScaler()</pre><pre>scaled_data = scaler.fit_transform(data)</pre><pre>print(scaled_data)</pre><p>Standardization is commonly used with algorithms such as:</p><ul><li>Logistic Regression</li><li>Support Vector Machines (SVM)</li><li>K-Nearest Neighbors (KNN)</li><li>Linear Regression with regularization</li></ul><p><strong>B. Normalization (Min-Max Scaling)</strong></p><p>Min-Max Scaling transforms numerical values into a specified range, commonly between 0 and 1.</p><p>Formula:</p><p>X’ = (X — Xmin) / (Xmax — Xmin)</p><p>Where:</p><ul><li>X = Original value</li><li>Xmin = Minimum value</li><li>Xmax = Maximum value</li></ul><p>Python implementation:</p><pre>from sklearn.preprocessing import MinMaxScaler</pre><pre>data = [[10], [20], [30], [40], [50]]</pre><pre>scaler = MinMaxScaler()</pre><pre>scaled_data = scaler.fit_transform(data)</pre><pre>print(scaled_data)</pre><p>Output:</p><pre>[[0.  ]<br> [0.25]<br> [0.5 ]<br> [0.75]<br> [1.  ]]</pre><p>Min-Max Scaling is useful when we want features within a fixed numerical range.</p><p>However, it is sensitive to outliers.</p><h3>4. Difference Between Encoding and Feature Scaling</h3><p>EncodingFeature ScalingConverts categorical data into numbers.Adjusts numerical feature ranges.Works with categorical features.Works with numerical features.Example: Red → [1, 0, 0].Example: 100 → 0.5.One-Hot and Label Encoding.StandardScaler and MinMaxScaler.</p><p>Both techniques prepare data for Machine Learning, but they solve different problems.</p><h3>5. Why Are These Techniques Important?</h3><p>Encoding and Feature Scaling help Machine Learning algorithms process data more effectively.</p><p><strong>Benefits of Encoding:</strong></p><ul><li>Converts text categories into numerical representations.</li><li>Makes categorical information usable by ML algorithms.</li><li>Helps represent different categories appropriately.</li></ul><p><strong>Benefits of Feature Scaling:</strong></p><ul><li>Prevents large numerical ranges from dominating distance-based calculations.</li><li>Helps optimization algorithms converge more efficiently.</li><li>Improves the performance of scale-sensitive algorithms.</li></ul><p>Remember: Tree-based algorithms such as Decision Trees and Random Forests generally do not require feature scaling.</p><h3>6. Important Practical Tip: Avoid Data Leakage</h3><p>When performing feature scaling, always split your dataset into training and testing sets first.</p><p>Fit the scaler only on the training data, then use the same scaler to transform the test data.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre>scaler = StandardScaler()</pre><pre>X_train_scaled = scaler.fit_transform(X_train)</pre><pre>X_test_scaled = scaler.transform(X_test)</pre><p>Why?</p><p>Because fitting the scaler on the complete dataset allows information from the test set to influence the training process. This causes data leakage.</p><h3>Conclusion</h3><p>Data Pre-processing is one of the most important stages in a Machine Learning workflow.</p><p>Encoding helps convert categorical information into numerical representations, while Feature Scaling ensures that numerical features are represented on comparable scales.</p><p>Understanding these two techniques will help you prepare datasets more effectively and build better Machine Learning models.</p><h3>Data Pre-processing: Understanding Encoding and Feature Scaling in Machine Learning</h3><h3>Introduction</h3><p>Have you ever wondered how a Machine Learning model understands data containing words, categories, and numbers?</p><p>Machine Learning algorithms work primarily with numerical data. However, real-world datasets often contain different types of information, such as names, colors, gender categories, locations, prices, and ages.</p><p>Before providing this information to a Machine Learning model, we need to prepare it properly. This process is called <strong>Data Pre-processing</strong>.</p><p>In this article, we will explore two important techniques in data preprocessing:</p><ol><li>Encoding</li><li>Feature Scaling</li></ol><p>Let’s understand how they work and why they are important.</p><h3>1. What is Data Pre-processing?</h3><p>Data Pre-processing is the process of cleaning, transforming, and organizing raw data into a suitable format for Machine Learning algorithms.</p><p>Real-world datasets may contain:</p><ul><li>Missing values.</li><li>Duplicate records.</li><li>Categorical data.</li><li>Different numerical ranges.</li><li>Incorrect or inconsistent values.</li></ul><p>Pre-processing helps improve data quality and prepares it for model training.</p><h3>2. What is Encoding?</h3><p><strong>Encoding is the process of converting categorical data into numerical values so that Machine Learning algorithms can process it.</strong></p><p>For example, imagine a dataset containing information about students:</p><p>StudentFavorite ColorARedBGreenCBlueDRed</p><p>The colors are categorical values. Most traditional Machine Learning algorithms cannot directly process these text categories.</p><p>We can solve this problem using encoding techniques.</p><h3>Types of Encoding</h3><p><strong>A. Label Encoding</strong></p><p>Label Encoding assigns a unique integer to each category.</p><p>Example:</p><p>ColorEncoded ValueRed0Green1Blue2</p><p>Python implementation:</p><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>data = [&#39;Red&#39;, &#39;Green&#39;, &#39;Blue&#39;, &#39;Red&#39;]</pre><pre>le = LabelEncoder()</pre><pre>encoded_data = le.fit_transform(data)</pre><pre>print(encoded_data)</pre><p>Output:</p><pre>[2 1 0 2]</pre><p>Note: The assigned numbers depend on the encoder’s category ordering.</p><p><strong>When can we use it?</strong></p><ul><li>Encoding target labels.</li><li>Converting categories with a genuine order, when using an appropriate ordinal encoding approach.</li></ul><p>Avoid blindly using integer labels for nominal categories because the model may interpret them as having a numerical order.</p><p><strong>B. One-Hot Encoding</strong></p><p>One-Hot Encoding converts each category into a separate binary column containing 0s and 1s.</p><p>Example:</p><p>Original data:</p><p>ColorRedGreenBlue</p><p>After One-Hot Encoding:</p><p>RedGreenBlue100010001</p><p>Python implementation:</p><pre>from sklearn.preprocessing import OneHotEncoder</pre><pre>import numpy as np</pre><pre>data = np.array([<br>    [&#39;Red&#39;],<br>    [&#39;Green&#39;],<br>    [&#39;Blue&#39;],<br>    [&#39;Red&#39;]<br>])</pre><pre>encoder = OneHotEncoder(sparse_output=False)</pre><pre>encoded_data = encoder.fit_transform(data)</pre><pre>print(encoded_data)</pre><p>One-Hot Encoding is useful when categories do not have any natural order.</p><p>For datasets containing many unique categories, it can create a large number of additional columns.</p><h3>3. What is Feature Scaling?</h3><p><strong>Feature Scaling is the process of bringing numerical features into a similar range.</strong></p><p>Consider a dataset containing:</p><p>StudentAgeSalaryA2020,000B2230,000C2550,000</p><p>Here, Age has smaller numerical values compared with Salary.</p><p>Some Machine Learning algorithms are sensitive to differences in feature scales. A feature with large numerical values may influence the model more than expected.</p><p>Feature Scaling helps address this problem.</p><h3>Types of Feature Scaling</h3><p><strong>A. Standardization (Standard Scaler)</strong></p><p>Standardization transforms numerical values so that the resulting feature has:</p><ul><li>Mean = 0</li><li>Standard Deviation = 1</li></ul><p>Formula:</p><p>Z = (X — μ) / σ</p><p>Where:</p><ul><li>X = Original value</li><li>μ = Mean</li><li>σ = Standard deviation</li></ul><p>Python implementation:</p><pre>from sklearn.preprocessing import StandardScaler</pre><pre>data = [[20], [25], [30], [35], [40]]</pre><pre>scaler = StandardScaler()</pre><pre>scaled_data = scaler.fit_transform(data)</pre><pre>print(scaled_data)</pre><p>Standardization is commonly used with algorithms such as:</p><ul><li>Logistic Regression</li><li>Support Vector Machines (SVM)</li><li>K-Nearest Neighbors (KNN)</li><li>Linear Regression with regularization</li></ul><p><strong>B. Normalization (Min-Max Scaling)</strong></p><p>Min-Max Scaling transforms numerical values into a specified range, commonly between 0 and 1.</p><p>Formula:</p><p>X’ = (X — Xmin) / (Xmax — Xmin)</p><p>Where:</p><ul><li>X = Original value</li><li>Xmin = Minimum value</li><li>Xmax = Maximum value</li></ul><p>Python implementation:</p><pre>from sklearn.preprocessing import MinMaxScaler</pre><pre>data = [[10], [20], [30], [40], [50]]</pre><pre>scaler = MinMaxScaler()</pre><pre>scaled_data = scaler.fit_transform(data)</pre><pre>print(scaled_data)</pre><p>Output:</p><pre>[[0.  ]<br> [0.25]<br> [0.5 ]<br> [0.75]<br> [1.  ]]</pre><p>Min-Max Scaling is useful when we want features within a fixed numerical range.</p><p>However, it is sensitive to outliers.</p><h3>4. Difference Between Encoding and Feature Scaling</h3><p>EncodingFeature ScalingConverts categorical data into numbers.Adjusts numerical feature ranges.Works with categorical features.Works with numerical features.Example: Red → [1, 0, 0].Example: 100 → 0.5.One-Hot and Label Encoding.StandardScaler and MinMaxScaler.</p><p>Both techniques prepare data for Machine Learning, but they solve different problems.</p><h3>5. Why Are These Techniques Important?</h3><p>Encoding and Feature Scaling help Machine Learning algorithms process data more effectively.</p><p><strong>Benefits of Encoding:</strong></p><ul><li>Converts text categories into numerical representations.</li><li>Makes categorical information usable by ML algorithms.</li><li>Helps represent different categories appropriately.</li></ul><p><strong>Benefits of Feature Scaling:</strong></p><ul><li>Prevents large numerical ranges from dominating distance-based calculations.</li><li>Helps optimization algorithms converge more efficiently.</li><li>Improves the performance of scale-sensitive algorithms.</li></ul><p>Remember: Tree-based algorithms such as Decision Trees and Random Forests generally do not require feature scaling.</p><h3>6. Important Practical Tip: Avoid Data Leakage</h3><p>When performing feature scaling, always split your dataset into training and testing sets first.</p><p>Fit the scaler only on the training data, then use the same scaler to transform the test data.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><pre>scaler = StandardScaler()</pre><pre>X_train_scaled = scaler.fit_transform(X_train)</pre><pre>X_test_scaled = scaler.transform(X_test)</pre><p>Why?</p><p>Because fitting the scaler on the complete dataset allows information from the test set to influence the training process. This causes data leakage.</p><h3>Conclusion</h3><p>Data Pre-processing is one of the most important stages in a Machine Learning workflow.</p><p>Encoding helps convert categorical information into numerical representations, while Feature Scaling ensures that numerical features are represented on comparable scales.</p><p>Understanding these two techniques will help you prepare datasets more effectively and build better Machine Learning models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7WhAVbe41J-sRDibhVIVQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2748c5e594b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>