<?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 Mamoonaquddus on Medium]]></title>
        <description><![CDATA[Stories by Mamoonaquddus on Medium]]></description>
        <link>https://medium.com/@mamoonaquddusqadri?source=rss-ea7cde1bca31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pnukz88UKaVhsnA6azLP2A.jpeg</url>
            <title>Stories by Mamoonaquddus on Medium</title>
            <link>https://medium.com/@mamoonaquddusqadri?source=rss-ea7cde1bca31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:37:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mamoonaquddusqadri/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[Detecting Duplicate Questions with ML: A Practical, Accuracy-Driven Workflow]]></title>
            <link>https://medium.com/@mamoonaquddusqadri/detecting-duplicate-questions-with-ml-a-practical-accuracy-driven-workflow-6592f2957152?source=rss-ea7cde1bca31------2</link>
            <guid isPermaLink="false">https://medium.com/p/6592f2957152</guid>
            <dc:creator><![CDATA[Mamoonaquddus]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 06:07:32 GMT</pubDate>
            <atom:updated>2025-08-07T06:19:09.776Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Practical Guide to Maximizing Model Accuracy</strong></h3><h4>Learn how to build reliable NLP pipelines for question-pair detection — from data prep to model evaluation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJMIcwLNdF8I7pOY2otjDQ.jpeg" /></figure><p>Have you ever wondered how platforms like Quora or Stack Overflow detect if two questions are essentially asking the same thing? This task — identifying duplicate question pairs — is an exciting yet challenging problem in Natural Language Processing (NLP). It plays a crucial role in applications such as customer support systems, knowledge bases, and community platforms by reducing redundancy and improving user experience. In this article, we’ll walk through a general ML workflow to tackle it, focusing on strategies to maximize model accuracy at each stage.</p><p>We’ll explore everything from data preparation and feature engineering to algorithm selection and evaluation — not to build one specific model, but to understand how <em>different choices affect model performance</em>.</p><h3>Step 1: Understand the Problem</h3><p>The goal is to classify whether a pair of questions are duplicates. This is essentially a <strong>binary classification problem</strong>: 1 if the questions are semantically similar, 0 if not.</p><h3>Step 2: Data Collection</h3><p>Before diving into modeling, it’s essential to gather a <strong>clean, relevant, and labeled dataset</strong>. Your dataset forms the backbone of the model’s performance and accuracy.</p><p>Here’s how you can source high-quality text data:</p><ul><li><strong>Open Datasets</strong>: Use domain-specific datasets from platforms like Kaggle, Hugging Face, or academic repositories. Choose ones that align closely with your classification task.</li><li><strong>APIs</strong>: Extract structured text data using APIs from platforms like Twitter, Reddit, or news sites. These can provide diverse and up-to-date content.</li><li><strong>Internal Data</strong>: Leverage business-specific data like customer feedback, tickets, or forms — if available — with proper anonymization.</li><li><strong>Annotation Tools</strong>: If your data is unlabeled, use tools like Label Studio or Prodigy to manually tag it for classification tasks.</li></ul><p><em>The focus should always be on collecting data that’s relevant to your classification objective. Clean, well-labeled data will directly translate to higher model accuracy later in the pipeline.</em></p><p>In this project, we used the <a href="https://www.kaggle.com/c/quora-question-pairs/data"><strong>Quora Question Pairs</strong></a> dataset from Kaggle, which contains question pairs labeled as duplicates or not. This labeled structure makes it ideal for building a binary text classification model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1GRxFiGwknLbAtGvHnpVw.png" /><figcaption>Sample from the data set</figcaption></figure><h3>Step 3: Data Preprocessing</h3><p>Before jumping into feature engineering or model training, preprocessing is non-negotiable. Text data often comes messy — filled with noise that can confuse models. Cleaning it improves clarity and model learning.</p><p>For duplicate question detection, the goal is to simplify and normalize the text while preserving its meaning. This helps ensure that models learn meaningful patterns, not superficial noise.</p><p><strong>Common preprocessing tasks include:</strong></p><ul><li>Lowercasing</li><li>Removing punctuation, HTML tags, and extra whitespace</li><li>Tokenization</li><li>Lemmatization or stemming</li><li>Stopword removal</li><li>Handling contractions (e.g., “don’t” → “do not”)</li></ul><p>Good preprocessing improves the quality of features and boosts model performance.</p><p><strong>Pro Tip: </strong>Make sure preprocessing (like TF-IDF fitting) is done only on the <strong>training set</strong> — not the full dataset. This prevents <strong>data leakage</strong> that inflates your model’s accuracy unrealistically.</p><h3>Step 4: Exploratory Data Analysis (EDA)</h3><p>Before diving into modeling, it’s important to get a <strong>feel for the data</strong>. Exploratory Data Analysis helps you uncover insights, spot potential issues, and guide your feature engineering and model design choices.</p><p><strong>Why EDA matters:</strong></p><ul><li>Helps identify class imbalances (e.g., more “not duplicate” than “duplicate” pairs).</li><li>Reveals missing values, outliers, or formatting issues.</li><li>Allows you to inspect the distribution of text lengths, word overlaps, or question similarity scores.</li><li>Gives early signals on which features might be useful.</li></ul><p><strong>Useful EDA techniques for question-pair tasks:</strong></p><ul><li><strong>Class Distribution<br></strong> Visualize the ratio of duplicate vs. non-duplicate questions — is it imbalanced?</li><li><strong>Question Lengths<br></strong> Plot histograms of question lengths (in words/characters) — longer questions might behave differently.</li><li><strong>Word Overlap<br></strong> Check how many words two questions share — duplicates often share more words.</li><li><strong>Missing or Nulls<br></strong> Are any questions blank or duplicated in the dataset?</li><li><strong>Heatmaps &amp; Correlations<br></strong> Visualize correlations between numerical features (e.g., shared word count vs. target label).</li></ul><p><strong>Example Insight:<br></strong> You might notice that duplicate question pairs tend to have higher TF-IDF cosine similarity than non-duplicates — a helpful hint for feature engineering.</p><h3>Step 5: Feature Engineering</h3><p>Once your text data is preprocessed, it’s time to convert it into features that your machine learning model can understand. Raw text, no matter how clean, isn’t directly usable — we need to <strong>translate it into numerical representations</strong> that capture semantic or structural information.</p><p>For duplicate question detection, we’re not just looking at individual questions — we’re comparing pairs. So, feature engineering should aim to <strong>capture relationships and similarities</strong> between two questions.</p><p><strong>Common feature engineering techniques:</strong></p><p><strong>Manual/Statistical Features:</strong></p><ul><li>Word overlap ratio</li><li>Jaccard similarity</li><li>Levenshtein distance</li><li>Cosine similarity of TF-IDF vectors</li></ul><p><strong>NLP-based Features:</strong></p><ul><li>These extract information using common NLP techniques. Some are purely statistical, while others (like embeddings) are learned:</li></ul><p><strong>Traditional NLP Representations:</strong></p><ul><li>Bag of Words<strong> </strong>(BoW)</li><li>TF-IDF (Term Frequency–Inverse Document Frequency)</li></ul><p><strong>Embedding-Based Representations (Learned):</strong></p><ul><li>Word2Vec / GloVe embeddings</li><li>TF-IDF weighted Word2Vec <em>(combines statistical weighting with embeddings)</em></li></ul><p><strong>Note</strong>: While embeddings are often used in deep learning, you can incorporate them in ML pipelines too as input features.</p><p><strong>Meta-features:</strong></p><ul><li>Number of common words</li><li>Difference in question lengths</li><li>Presence of certain keywords</li><li>First-word one-hot encoding</li></ul><p><strong>Advanced (Magic) Features:</strong></p><ul><li>Frequency of each question in the dataset</li><li>Synonym match ratio</li><li>Semantic features like TF-IDF weighted Word2Vec similarity</li></ul><p>The idea is to extract features that help capture <strong>semantic similarity</strong> in addition to syntactic similarity.</p><h3>Step 6: Feature Selection</h3><p>Now that you’ve engineered a rich set of features, the next step is to <strong>select the most informative ones</strong>. Not all features contribute equally to model accuracy — some might be redundant, noisy, or even harmful (leading to overfitting or poor generalization).</p><p>The goal of feature selection is to <strong>reduce dimensionality</strong>, improve performance, and make the model more interpretable.</p><p><strong>Common feature selection techniques:</strong></p><p><strong>Univariate statistical tests</strong></p><ul><li><em>Chi-square</em>, <em>ANOVA</em>, or <em>Mutual Information</em> to score features.</li></ul><p><strong>Model-based selection</strong></p><ul><li>Use models like <em>Random Forest</em> or <em>XGBoost</em> to check feature importance.</li><li>Recursive Feature Elimination (RFE) with a base model.</li></ul><p><strong>Regularization techniques</strong></p><ul><li>Models like <em>Lasso Regression</em> shrink less important features to zero.</li></ul><p><strong>Correlation analysis</strong></p><ul><li>Remove features that are highly correlated with each other.</li></ul><p><strong>Pro Tip: </strong>Feature selection is often iterative — test different subsets using cross-validation to find the sweet spot between model complexity and performance.</p><h3><strong>Step 7: Splitting the Data for Better Generalization</strong></h3><p>Splitting your dataset is a <strong>crucial step</strong> to evaluate your model’s real-world performance without introducing bias.</p><p><strong>Recommended Practice<br></strong> Instead of a simple 2:1 train-test split, it’s better to divide your dataset into:</p><ul><li><strong>70% training</strong> — for model learning</li><li><strong>15% validation</strong> — for hyperparameter tuning and model selection</li><li><strong>15% testing</strong> — for final performance evaluation</li></ul><p>This ensures your model is not just memorizing data but actually generalizing well to unseen inputs.</p><p><strong>Important Tips</strong></p><ul><li>Always shuffle your data before splitting (unless the data is time-series).</li><li>Use train_test_split() from scikit-learn or StratifiedKFold for balanced class distribution.</li></ul><p><strong><em>Why not just train/test?</em></strong><em><br></em> Because using validation helps you tune and choose the <strong>best model configuration</strong> <em>before</em> you test, reducing the risk of overfitting on the test set.</p><h3>Step 8: Choosing the Right Algorithm</h3><p>Now that your data is preprocessed, explored, and transformed into features, it’s time to select the right machine learning algorithm. The choice of model has a <strong>huge impact on accuracy</strong> — but no single model fits all.</p><p><strong>Things to consider when choosing an algorithm:</strong></p><ul><li><strong>Size &amp; quality of your data<br></strong> Larger datasets may benefit from deep learning, while smaller ones might do better with tree-based methods.</li><li><strong>Training time &amp; interpretability<br></strong> Simpler models (like Logistic Regression or Naive Bayes) are faster and easier to interpret. More complex models (like XGBoost or neural networks) may deliver better accuracy at the cost of transparency and compute.</li><li><strong>Text data representation<br></strong> Classical models work well with TF-IDF or hand-crafted features. Deep learning models like LSTM or BERT handle raw text better, especially in NLP tasks.</li></ul><p><strong>Comparison table </strong>of commonly used models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko6krRg-NoTZEwrfxX-gYw.png" /><figcaption><strong>Comparison table</strong></figcaption></figure><h3>Step 9: Hyperparameter Tuning &amp; Cross Validation</h3><p>Once you’ve built a base model, the next step is to optimize it — and that’s where hyperparameter tuning and cross-validation come in.</p><p><strong>Hyperparameters</strong> are configuration settings that govern how your model learns (unlike model parameters, which are learned from the data).</p><p><strong>Examples of Hyperparameters:</strong></p><ol><li>Logistic Regression(C , penalty)</li><li>SVM(C, kernel, gamma)</li><li>Random Forest(n_estimators, max_depth)</li><li>XGBoost(learning_rate, n_estimators, subsample)</li></ol><p>Choosing the right combination of hyperparameters can significantly improve model performance. This process is called <strong>hyperparameter tuning</strong>.</p><p>However, evaluating performance on just a single train-test split can lead to biased results. That’s where <strong>cross-validation</strong> helps. It involves splitting the dataset into multiple folds (usually 5 or 10), training the model on different combinations of those folds, and averaging the results. This gives a more reliable estimate of how the model will perform on unseen data.</p><p>Once your base model works, refine it:</p><ul><li>Use <strong>GridSearchCV</strong> or <strong>RandomizedSearchCV</strong></li><li>Apply <strong>K-Fold Cross-Validation</strong> to avoid overfitting</li><li>Use <strong>StratifiedKFold</strong> if classes are imbalanced</li><li><strong>Optuna</strong> (for smarter, faster tuning)</li></ul><p>In short, combining hyperparameter tuning with cross-validation not only fine-tunes your model but also ensures it generalizes well to new data.</p><h3>Step 10: Evaluation Strategy</h3><p>After training your model, it’s crucial to evaluate its performance using the right metrics — especially in binary classification tasks like duplicate question detection.</p><p><strong>Different metrics provide different insights:</strong></p><ul><li><strong>Accuracy</strong>:<br> Quick overall score — but unreliable for imbalanced data (e.g., spam detection).</li><li><strong>Precision</strong>:<br> Use when false positives are costly (e.g., flagging a non-spam as spam).</li><li><strong>Recall</strong>:<br> Crucial when missing a positive case is risky (e.g., missing spam emails).</li><li><strong>F1 Score</strong>:<br> Balanced metric for precision &amp; recall — great for imbalanced datasets.</li><li><strong>ROC-AUC Score</strong>:<br> Evaluates model’s probability ranking — good for comparing classifiers.</li><li><strong>Confusion Matrix</strong>:<br> Visual breakdown of true vs. false predictions (TP, FP, FN, TN) for clearer analysis.</li></ul><p><strong>Pro Tip</strong>: Always use a combination of these metrics — especially when dealing with real-world, imbalanced datasets.</p><h4>Learning Curves</h4><p>Learning curves help you diagnose model behavior during training and testing:</p><ul><li><strong>Overfitting</strong>:<br> High performance on training data but poor generalization on validation/test data.</li><li><strong>Underfitting</strong>:<br> Poor performance on both training and test sets — the model is too simple.</li></ul><p>Visualizing learning curves lets you decide whether to gather more data, tune hyperparameters, or try a different algorithm altogether.</p><h3>Working with Large Datasets</h3><p>Real-world datasets can be massive — sometimes with hundreds of thousands of rows. But your machine might not be built to handle it all in memory. Here’s how to work smarter:</p><h4>Practical Tips</h4><ul><li><strong>Use Cloud Platforms</strong>:<br> Platforms like <strong>Google Colab</strong>, <strong>AWS</strong>, or <strong>Kaggle Kernels</strong> offer extra RAM and GPU power.</li><li><strong>Batch/Incremental Learning Libraries</strong>:<br> Tools like <strong>Vaex</strong> and <strong>Dask</strong> let you process data in chunks, avoiding full RAM usage.</li><li><strong>Dimensionality Reduction</strong>:<br> Apply techniques like <strong>PCA</strong> or <strong>Truncated SVD</strong> to reduce feature size and memory load.</li><li><strong>Upgrade Your System (if possible)</strong>:<br> Increasing RAM helps when working locally with large datasets.</li></ul><p><strong>Pro Tip</strong>: You don’t need to load the whole dataset into memory at once. Use chunked processing and generators to handle large files efficiently.</p><h3>Avoid Data Leakage</h3><p>One of the most frequent — and damaging — mistakes:</p><p><strong>Wrong</strong>: Apply scaling, vectorization, or feature engineering on the <strong>entire dataset</strong> first.</p><p><strong>Correct</strong>:</p><ul><li>First, <strong>split into train and test sets</strong>.</li><li>Then <strong>fit</strong> the scalers or encoders on <strong>training only</strong>.</li><li><strong>Transform</strong> both train and test <strong>separately</strong>.</li></ul><p>This ensures your model doesn’t peek into the test set — avoiding artificially high scores.</p><h3>Final Thoughts</h3><p>There’s no silver bullet model — the key to high performance is thoughtful preprocessing, strategic feature engineering, and iterative tuning. With the right workflow, identifying duplicate questions becomes not just feasible, but accurate and scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6592f2957152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Most NLP Projects Fail: A Beginner’s Guide to Text Preprocessing]]></title>
            <link>https://medium.com/@mamoonaquddusqadri/why-most-nlp-projects-fail-a-beginners-guide-to-text-preprocessing-d7c39075e73c?source=rss-ea7cde1bca31------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c39075e73c</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mamoonaquddus]]></dc:creator>
            <pubDate>Wed, 07 May 2025 04:57:03 GMT</pubDate>
            <atom:updated>2025-05-25T13:21:40.588Z</atom:updated>
            <content:encoded><![CDATA[<h4>Preprocessing Steps for NLP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thzHqP28H17P8oFfs4_41w.png" /><figcaption>Text Preprocessing Steps for NLP</figcaption></figure><p>Before feeding text into any model, text <strong>preprocessing</strong> is crucial.</p><p>It’s the base step of the NLP pipeline, and without cleaning your textual data, your model won’t perform well, no matter how good the algorithm is.</p><p>In this article, I’ll walk you through the basic <strong>text</strong> <strong>preprocessing </strong>steps. Let’s get into it</p><h3>1. Lowercasing</h3><p>We lowercase the entire text to avoid confusion for the model. Python is a case-sensitive programming language. Therefore, to avoid any issues and ensure consistency in the processing of the text, we convert all the text to lowercase.</p><p>So this ensures <strong>consistency</strong> and helps reduce the total vocabulary size.</p><p>For example:</p><p>“Movie” and “movie” should be treated as the same word, not two different tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDQ5zdN_Z4s-ga7GRr0GZw.png" /><figcaption>Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8dqjj1IgNwS4759YDDuqg.png" /><figcaption>Sample review before converting text into lowercase</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvfGj1zNfJjSrCrTGZhxmg.png" /><figcaption>Sample review after converting text into lowercase</figcaption></figure><h3>2. Removing HTML Tags</h3><p>When we scrape data from websites or use data from different sources like blogs, news, etc., they contain a lot of HTML tags. So we remove those tags and keep only the text.</p><pre>import re<br>def remove_html_tags(text):<br>    pattern = re.compile(&#39;&lt;.*?&gt;&#39;)<br>    return pattern.sub(r&#39;&#39;, text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kTLL0iDWZylK4mfzHM-gA.png" /><figcaption>Text before and after removing all HTML tags.</figcaption></figure><h3>3. Removing URLs</h3><p>Sometimes, the data contains links, especially if it’s scraped or collected from social media. These URLs do not help with NLP tasks like sentiment analysis or classification. URLs are typically not relevant and can be removed from the text data.</p><p>URLs only create <strong>noise</strong> in the data and increase the size unnecessarily.</p><pre>def remove_url(https://medium.com/text):<br>    pattern = re.compile(r&#39;https?://\S+|www\.\S+&#39;)<br>    return pattern.sub(r&#39;&#39;, text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42WSFDP3H0n34ZqW4tiq2Q.png" /><figcaption>Text before and after removing all URLs.</figcaption></figure><h3>4. Removing Punctuation</h3><p>Punctuation may carry information, especially in tasks like emotion detection or dialogue generation, but in most use cases (like classification or sentiment analysis), punctuation is not helpful.</p><p>So we remove them to reduce data complexity and vocabulary size.</p><p>Also, it can affect tokenization.</p><pre>import string<br>exclude = string.punctuation<br>def remove_punc1(text):<br>    return text.translate(str.maketrans(&#39;&#39;, &#39;&#39;, exclude))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1Wu5_3S_nqUW_OMTbdySQ.png" /><figcaption>Sample review before and after removing punctuation marks.</figcaption></figure><h3>5. Chat Word Treatment</h3><p>When dealing with informal data like chats, tweets, or casual conversations, we often find words like:</p><p>“u” instead of “you”</p><p>“pls” instead of “please”</p><p>We replace these short/informal words with their actual forms using a dictionary.</p><p>This step improves model understanding by making the data more <strong>formal</strong> and <strong>standardized</strong>.</p><pre>chat_words = {&quot;TTYL&quot;: &quot;talk to you later&quot;,<br>              &quot;LOL&quot;: &quot;laughing out loud&quot;}<br>def chat_conversion(text):<br>    new_text = []<br>    for w in text.split():<br>        if w.upper() in chat_words:<br>            new_text.append(chat_words[w.upper()])<br>        else:<br>            new_text.append(w)<br>    return &quot; &quot;.join(new_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFoHzbRN_6SeFoTglV1sHg.png" /><figcaption>Sample chat before and after replacing shortcut words with their full forms.</figcaption></figure><h3>6. Spelling Correction</h3><p>Spelling mistakes are very common in real-world data. Misspelled words are treated as <strong>different</strong> words, which increases vocabulary size and reduces model <strong>accuracy</strong>.</p><p>Spelling correction is done using libraries like TextBlob or SymSpell.</p><p>But if your data contains domain-specific words (e.g., medical terms), these libraries may not work well. In that case, you may need a custom spell checker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pNMtu-2X-DM2v3J6qNXMQ.png" /><figcaption>Text before and after correcting spelling mistakes.</figcaption></figure><h3>7. Removing Stop Words</h3><p>Stop words like “is”, “the”, “in”, etc., appear frequently in the data but add little meaning in many NLP tasks (e.g., text classification, sentiment analysis).</p><p>Removing them helps reduce the number of tokens and improves processing.</p><p>But stop words are useful in tasks like <strong>POS tagging</strong>, where context is important.</p><p>So again, <strong>decide based on your use case.</strong></p><pre>from nltk.corpus import stopwords<br>stopwords.words(&#39;english&#39;)<br>def remove_stopwords(text):<br>    new_text = []<br>    <br>    for word in text.split():<br>        if word in stopwords.words(&#39;english&#39;):<br>            new_text.append(&#39;&#39;)<br>        else:<br>            new_text.append(word)<br>    x = new_text[:]<br>    new_text.clear()<br>    return &quot; &quot;.join(x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PY4aIfmkubz4_mIJ1xCVhg.png" /><figcaption>Text before and after removing stopwords.</figcaption></figure><h3>8. Handling Emojis</h3><p>Emojis are widely used in text conversations and social media posts. They can hold <strong>emotional meaning</strong> and sentiment.</p><p>Handling emojis can be done in two <strong>ways</strong>:</p><ol><li>Remove them</li><li>Convert them to their textual meaning (e.g., 😍 → “love”)</li></ol><pre>import re<br>def remove_emoji(text):<br>    emoji_pattern = re.compile(&quot;[&quot;<br>                           u&quot;\U0001F600-\U0001F64F&quot;  # emoticons<br>                           u&quot;\U0001F300-\U0001F5FF&quot;  # symbols &amp; pictographs<br>                           u&quot;\U0001F680-\U0001F6FF&quot;  # transport &amp; map symbols<br>                           u&quot;\U0001F1E0-\U0001F1FF&quot;  # flags (iOS)<br>                           u&quot;\U00002702-\U000027B0&quot;<br>                           u&quot;\U000024C2-\U0001F251&quot;<br>                           &quot;]+&quot;, flags=re.UNICODE)<br>    return emoji_pattern.sub(r&#39;&#39;, text)</pre><p>You can decide whether to remove or convert, based on the task (e.g., in sentiment analysis, converting makes sense).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsIhr9wzbVgOvNbgEwZHJA.png" /><figcaption>Text before and after removing emojis.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2kkFscByIh0nm0PWXON6w.png" /><figcaption>Text before and after converting emojis.</figcaption></figure><h3>9. Tokenization</h3><p>Tokenization is the process of <strong>splitting text into smaller parts</strong> (tokens), such as words or subwords.</p><p>This is a <strong>very crucial step</strong> because incorrect tokenization can confuse the model.</p><p>For example:</p><p>&quot;I love NLP&quot; → [&quot;I&quot;, &quot;love&quot;, &quot;NLP&quot;]</p><p><em>There are some things that can cause trouble during tokenization.</em></p><p><strong>Prefix</strong> (before word, e.g., $)</p><p><strong>Suffix</strong> (after word, e.g., !)</p><p><strong>Infix</strong> (within word, e.g., - in “U.S.”)</p><p><strong>Exceptions</strong> (e.g., “U.S”, “10km”)</p><p>There are many methods to tokenize text:</p><p><strong>I. Example Using </strong><strong>split() (Not recommended for complex text)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNZqzYj-viOmO-nvYbmkFA.png" /><figcaption><em>Text before and after splitting text into tokens (words) using split function.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HxdDlLUKa2L8QMbOQJOUw.png" /><figcaption>Problem with split funtcion</figcaption></figure><p>But there are some problems with the split function, like Here, <em>Pakistan,</em> with and without the exclamation mark, is treated as different tokens, so it is not handled well by the split function.</p><p>And the split function can also work on only one thing, but here we are splitting (tokenize) it using . But in our split function, it is not working because we don’t have a . in the given sentence. That’s why in difficult scenarios, we do not use it.</p><p><strong>II.</strong> <strong>Example Using </strong><strong>re.findall() with regex</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjUoK5vVUSFuYXHUICNr1A.png" /><figcaption><em>Text before and after splitting text into tokens (words) using </em>regular expression</figcaption></figure><p>So we can use <strong>regular expressions</strong>. Although they have some problems, they are better than split.<br>We can use them to remove any pattern like the exclamation mark, but what if we <strong>want</strong> that exclamation mark? So, according to our needs, we have to make separate patterns, which can be challenging.</p><p><strong>III. Example Using libraries like </strong><strong>nltk.word_tokenize()</strong></p><p>There are some libraries like <strong>NLTK </strong>and<strong> </strong><strong>SpaCy</strong>that can solve this problem, and we don’t need to manually apply patterns like regular expressions.</p><p>In <strong>NLTK</strong>, we’ve got two functions: word_tokenize and sent_tokenize.<br> These functions have internal algorithms that can handle those difficult scenarios like prefix, suffix, infix, and exceptions.</p><pre>from nltk.tokenize import word_tokenize,sent_tokenize</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yslVR2neyCqtijf9zL-Ug.png" /><figcaption><em>Text before and after splitting text into tokens (words) using NLTK</em></figcaption></figure><p><strong>IV. Example: Using libraries like </strong><strong>SpaCy</strong></p><p>It is the best library after NLTK.</p><pre>import spacy<br>nlp = spacy.load(&#39;en_core_web_sm&#39;)<br>doc4 = nlp(sent1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcHYuZnqRAongvVrsPkz2A.png" /><figcaption><em>Text before and after splitting text into tokens (words) using SpaCy</em></figcaption></figure><p>But still, we have to choose between one of them. In some scenarios, one can perform better, and in others, not.<br>For example, if we have less complex data, we can use NLTK.</p><p>Before deep diving into the world of stemming and lemmatization, we have to consider a concept called <strong>inflection</strong>!</p><h3>Inflection</h3><p>In grammar, <strong>inflection</strong> is the modification of a word to express different grammatical categories such as tense, case, voice, aspect, person, number, gender, and mood.</p><p><strong>Simple explanation:</strong><br> If we make some changes in any word so that it can tell or express something different, it’s known as <strong>inflection</strong>.</p><p>Example:</p><p><strong>Walk</strong> → This is the root word.</p><ul><li>Walking</li><li>Walks</li><li>Walked</li></ul><p>Another example:<br> <strong>Undoable</strong></p><ul><li><em>Un</em> = prefix</li><li><em>Do</em> = infix</li><li><em>Able</em> = suffix</li></ul><p>This is problematic for NLP tasks. So, to handle it, we use <strong>stemming</strong> and <strong>lemmatization</strong>.</p><h3>10. Stemming</h3><p><strong>Stemming</strong> is the process of reducing inflection in words to their root form, such as mapping a group of words to the same stem (root word), even if the stem is not a valid word in the language.</p><p>So basically, it means:<br> If we have inflected words and we are converting them into their root forms, this process is called <strong>stemming</strong>.</p><p>We can use the <strong>NLTK libraries</strong> for stemming.</p><h4><strong>Stemmer</strong></h4><p>A <strong>stemmer</strong> is an algorithm that performs stemming.</p><p>Stemming reduces a word to its <strong>root</strong> or <strong>stem</strong> form by removing suffixes like “-ing”, “-ed”, etc.</p><p>For example:</p><ul><li>“Walking”, “Walks”, “Walked” → “walk”</li></ul><p>Stemming is a rule-based approach and sometimes produces <strong>non-meaningful roots</strong> (e.g., “studies” → “studi”).</p><p>We use <strong>Porter Stemmer</strong> or <strong>Snowball Stemmer</strong> from NLTK. <strong>Porter Stemmer</strong> is specifically for the English language.</p><pre>from nltk.stem.porter import PorterStemmer<br>ps = PorterStemmer()<br>def stem_words(text):<br>    return &quot; &quot;.join([ps.stem(word) for word in text.split()])<br>sample = &quot;walk walks walking walked&quot;<br>stem_words(sample)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Zgq7mhhcDZw0j_lyqg-Cw.png" /><figcaption>Text before and after applying stemming</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZUPCyZOTMJH_Cwp2poMPw.png" /><figcaption>Text before and after applying stemming</figcaption></figure><p><strong>Stemming </strong>is a very useful text preprocessing step.<br>It is mostly used in information retrieval systems (e.g., Google search engine uses it) where variations of a word can match the same root.</p><p>(By the way, stemmers are made by <strong>linguists</strong> who understand language.)</p><p><strong>Note:</strong><br> Stemming is not always a good technique for finding root words.</p><h3>11. Lemmatization</h3><p><strong>Lemmatization</strong>, unlike stemming, reduces the inflected words <strong>properly</strong>, ensuring that the root word belongs to the language.<br> In lemmatization, the root word is called a <strong>lemma</strong>.</p><p><em>A lemma (plural: lemmata) is the canonical form, dictionary form, or citation form of a set of words.</em></p><p>It uses <strong>WordNet</strong> or linguistic rules to find the <strong>base form</strong> of a word based on its part of speech.</p><p>While doing lemmatization, we also have to provide <strong>POS (Part of Speech) tagging, </strong>meaning, in which part of speech we want to perform lemmatization.</p><p>For example:</p><ul><li>“was” → “be”</li><li>“studies” → “study”</li></ul><p>We use WordNetLemmatizer from NLTK or lemmatizer In SpaCy.</p><p>We are going to use <strong>WordNet Lemmatizer, which is</strong> like a dictionary.</p><p>It stores information about how English words are related to each other.</p><pre>import nltk<br>from nltk.stem import WordNetLemmatizer<br>wordnet_lemmatizer = WordNetLemmatizer()<br><br>sentence = &quot;He was running and eating at same time. He has bad habit of swimming after playing long hours in the Sun.&quot;<br>punctuations=&quot;?:!.,;&quot;<br>sentence_words = nltk.word_tokenize(sentence)<br>for word in sentence_words:<br>    if word in punctuations:<br>        sentence_words.remove(word)<br><br>sentence_words<br>print(&quot;{0:20}{1:20}&quot;.format(&quot;Word&quot;,&quot;Lemma&quot;))<br>for word in sentence_words:<br>    print (&quot;{0:20}{1:20}&quot;.format(word,wordnet_lemmatizer.lemmatize(word,pos=&#39;v&#39;)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*bJYbaaa04ic7KefAqRZtvQ.png" /><figcaption>Text after applying lemmatization</figcaption></figure><p>In lemmatization, we go into the <strong>dictionary</strong> to find the root words.<br> So basically, we are <strong>searching</strong> for the root word, that’s why it’s slow.<br> So we have to consider in which scenario we should use which technique</p><ul><li>If you want <strong>speed</strong>, use <strong>stemming; </strong>otherwise, use <strong>lemmatization</strong>.</li></ul><h4>Note:</h4><p>It’s not necessary to apply all the steps. Some are applicable depending on the nature of your textual data. For example, <strong>stemming or lemmatization</strong> might not be required in some cases, but <strong>punctuation and stop word removal</strong> almost always are. So, evaluate your data and then decide which preprocessing techniques to apply.</p><blockquote>If you have any suggestions, please contact me via <a href="https://www.linkedin.com/in/mamoonaquddus/"><strong>Linkedin</strong></a><strong>.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c39075e73c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>