<?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 Farhan Sarguroh on Medium]]></title>
        <description><![CDATA[Stories by Farhan Sarguroh on Medium]]></description>
        <link>https://medium.com/@farhansarguroh?source=rss-d2182225ddc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MxdVKzuLEtB3B0GgT3RIew.png</url>
            <title>Stories by Farhan Sarguroh on Medium</title>
            <link>https://medium.com/@farhansarguroh?source=rss-d2182225ddc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:39:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farhansarguroh/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[Word Order HackerRank]]></title>
            <link>https://farhansarguroh.medium.com/word-order-hackerrank-e77b29ed27b5?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e77b29ed27b5</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[hackerrank-solution]]></category>
            <category><![CDATA[hackerrank-python]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 00:32:29 GMT</pubDate>
            <atom:updated>2024-02-09T00:32:29.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem:</h3><p>You are given <em>n</em> words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.</p><p><strong>Note:</strong> Each input line ends with a “\n” character.</p><p><strong>Constraints:</strong></p><p><em>1 ≤ n ≤ 10⁵</em></p><p>The sum of the lengths of all the words do not exceed 10⁶</p><p>All the words are composed of lowercase English letters only.</p><p><strong>Input Format:</strong></p><p>The first line contains the integer, <em>n</em>.</p><p>The next <em>n</em> lines each contain a word.</p><p><strong>Output Format:</strong></p><p>Output <strong><em>2</em></strong> lines.</p><p>On the first line, output the number of distinct words from the input.</p><p>On the second line, output the number of occurrences for each distinct word according to their appearance in the input.</p><p><strong>Sample Input:</strong></p><pre>4<br>bcdef<br>abcdefg<br>bcde<br>bcdef</pre><p><strong>Sample Output:</strong></p><pre>3<br>2 1 1</pre><p><strong>Explanation:</strong></p><p>There are <strong><em>3</em></strong> distinct words. Here, <strong>“bcdef”</strong> appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are <strong>“bcdef”</strong>, <strong>“abcdefg”</strong> and <strong>“bcde”</strong> which corresponds to the output.</p><h3>Code:</h3><pre>t = int(input())<br>strings = []<br><br>for _ in range(t):<br>    strings.append(input())<br><br>counts = {}<br><br>for string in strings:<br>    counts[string] = counts.get(string, 0) + 1<br><br><br>print(len(counts))<br>print(&quot; &quot;.join(str(count) for count in counts.values()))</pre><p>Hey there! So, this Python code I’ve got here is pretty straightforward. Imagine you’ve got a bunch of strings, and you want to know how many times each one appears. So, first, it asks you how many strings you’ve got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_heiX8W0DPGu2uqvrS1Lw.png" /></figure><p>Then, you just type in each string one by one. Easy, right?</p><p>Behind the scenes, it’s keeping track of how many times each string appears using a neat trick with a dictionary.</p><p>Once you’re done typing in all your strings, it tells you how many unique strings you entered and how many times each one appeared.</p><p>Simple, efficient, and handy for counting strings in Python!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e77b29ed27b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[262. Trips and Users]]></title>
            <link>https://farhansarguroh.medium.com/262-trips-and-users-906c64f3f9f2?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/906c64f3f9f2</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 17:03:05 GMT</pubDate>
            <atom:updated>2023-08-28T17:03:05.379Z</atom:updated>
            <content:encoded><![CDATA[<p>Leetcode (Hard)</p><p>Table: Trips</p><pre>+-------------+----------+<br>| Column Name | Type     |<br>+-------------+----------+<br>| id          | int      |<br>| client_id   | int      |<br>| driver_id   | int      |<br>| city_id     | int      |<br>| status      | enum     |<br>| request_at  | date     |     <br>+-------------+----------+<br>id is the primary key (column with unique values) for this table.<br>The table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table.<br>Status is an ENUM (category) type of (&#39;completed&#39;, &#39;cancelled_by_driver&#39;, &#39;cancelled_by_client&#39;).</pre><p>Table: Users</p><pre>+-------------+----------+<br>| Column Name | Type     |<br>+-------------+----------+<br>| users_id    | int      |<br>| banned      | enum     |<br>| role        | enum     |<br>+-------------+----------+<br>users_id is the primary key (column with unique values) for this table.<br>The table holds all users. Each user has a unique users_id, and role is an ENUM type of (&#39;client&#39;, &#39;driver&#39;, &#39;partner&#39;).<br>banned is an ENUM (category) type of (&#39;Yes&#39;, &#39;No&#39;).</pre><p>The <strong>cancellation rate</strong> is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.</p><p>Write a solution to find the <strong>cancellation rate</strong> of requests with unbanned users (<strong>both client and driver must not be banned</strong>) each day between &quot;2013-10-01&quot; and &quot;2013-10-03&quot;. Round Cancellation Rate to <strong>two decimal</strong> points.</p><p>Return the result table in <strong>any order</strong>.</p><p>The result format is in the following example.</p><p><strong>Example 1:</strong></p><pre>Input: <br>Trips table:<br>+----+-----------+-----------+---------+---------------------+------------+<br>| id | client_id | driver_id | city_id | status              | request_at |<br>+----+-----------+-----------+---------+---------------------+------------+<br>| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |<br>| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |<br>| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |<br>| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |<br>| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |<br>| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |<br>| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |<br>| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |<br>| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |<br>| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |<br>+----+-----------+-----------+---------+---------------------+------------+<br>Users table:<br>+----------+--------+--------+<br>| users_id | banned | role   |<br>+----------+--------+--------+<br>| 1        | No     | client |<br>| 2        | Yes    | client |<br>| 3        | No     | client |<br>| 4        | No     | client |<br>| 10       | No     | driver |<br>| 11       | No     | driver |<br>| 12       | No     | driver |<br>| 13       | No     | driver |<br>+----------+--------+--------+<br>Output: <br>+------------+-------------------+<br>| Day        | Cancellation Rate |<br>+------------+-------------------+<br>| 2013-10-01 | 0.33              |<br>| 2013-10-02 | 0.00              |<br>| 2013-10-03 | 0.50              |<br>+------------+-------------------+<br>Explanation: <br>On 2013-10-01:<br>  - There were 4 requests in total, 2 of which were canceled.<br>  - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation.<br>  - Hence there are 3 unbanned requests in total, 1 of which was canceled.<br>  - The Cancellation Rate is (1 / 3) = 0.33<br>On 2013-10-02:<br>  - There were 3 requests in total, 0 of which were canceled.<br>  - The request with Id=6 was made by a banned client, so it is ignored.<br>  - Hence there are 2 unbanned requests in total, 0 of which were canceled.<br>  - The Cancellation Rate is (0 / 2) = 0.00<br>On 2013-10-03:<br>  - There were 3 requests in total, 1 of which was canceled.<br>  - The request with Id=8 was made by a banned client, so it is ignored.<br>  - Hence there are 2 unbanned request in total, 1 of which were canceled.<br>  - The Cancellation Rate is (1 / 2) = 0.50</pre><p><em>Calculating Cancellation Rate</em></p><p>The cancellation rate is computed by dividing the number of canceled requests (by clients or drivers) with unbanned users by the total number of requests with unbanned users on a specific day.</p><p>Here’s the SQL query that calculates this cancellation rate for each day between “2013–10–01” and “2013–10–03”:</p><pre>SELECT<br>    t.request_at AS Day,<br>    ROUND(<br>        SUM(CASE WHEN t.status IN (&#39;cancelled_by_client&#39;, &#39;cancelled_by_driver&#39;) THEN 1 ELSE 0 END) /<br>        COUNT(*),<br>        2<br>    ) AS &#39;Cancellation Rate&#39;<br>FROM<br>    Trips t<br>JOIN<br>    Users u ON t.client_id = u.users_id<br>JOIN<br>    Users u2 ON t.driver_id = u2.users_id<br>WHERE<br>    u.banned = &#39;No&#39; AND u2.banned = &#39;No&#39;<br>    AND t.request_at BETWEEN &#39;2013-10-01&#39; AND &#39;2013-10-03&#39;<br>GROUP BY<br>    t.request_at<br>ORDER BY<br>    t.request_at;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906c64f3f9f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1393. Capital Gain/Loss]]></title>
            <link>https://farhansarguroh.medium.com/1393-capital-gain-loss-b70f4652125b?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70f4652125b</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 11:03:59 GMT</pubDate>
            <atom:updated>2023-08-24T11:03:59.294Z</atom:updated>
            <content:encoded><![CDATA[<p>Leetcode (Medium)</p><p><strong>Introduction:</strong><br>In the world of financial markets, managing stocks involves buying and selling them to generate profit. To effectively analyze the performance of stocks, it’s essential to calculate the capital gain or loss resulting from these transactions. In this blog post, we will explore how to use SQL to report the capital gain/loss for each stock using the provided “Stocks” table.</p><p><strong>Understanding the Problem:</strong><br>The problem provides a table named “Stocks” with columns such as `stock_name`, `operation`, `operation_day`, and `price`. Each row in the table represents a stock operation, either a ‘Buy’ or a ‘Sell’, with corresponding details. It’s mentioned that for each ‘Sell’ operation, there’s a previous ‘Buy’ operation, and for each ‘Buy’ operation, there’s a corresponding upcoming ‘Sell’ operation. The goal is to calculate the capital gain/loss for each stock.</p><p><strong>Approach:</strong><br>To calculate the capital gain/loss for each stock, we need to follow these steps:</p><p>1. Calculate the accumulated gains and losses for each stock.<br>2. Subtract the accumulated losses from the accumulated gains to get the capital gain/loss for each stock.</p><p>We’ll break down the SQL solution into two parts:<br>1. Calculate accumulated gains and losses for each stock.<br>2. Subtract losses from gains to get the capital gain/loss.</p><p><strong>SQL Solution:</strong></p><pre>SELECT stock_name,<br>       SUM(CASE WHEN operation = &#39;Sell&#39; THEN price ELSE 0 END) -<br>       SUM(CASE WHEN operation = &#39;Buy&#39; THEN price ELSE 0 END) AS capital_gain_loss<br>FROM Stocks<br>GROUP BY stock_name;</pre><p><strong>Explanation:</strong></p><p>1. The `SUM` function with `CASE` statements calculates the total price for each operation type (‘Sell’ or ‘Buy’) separately.<br>2. We subtract the total ‘Buy’ price from the total ‘Sell’ price to get the capital gain/loss for each stock.</p><p><strong>Conclusion</strong>:<br>Calculating the capital gain/loss for stocks is an essential task in financial analysis. By utilizing SQL, we can efficiently process and summarize the data to derive meaningful insights. The provided solution demonstrates how to aggregate data using `SUM` and `CASE` statements to calculate the capital gain/loss for each stock. This approach provides a clear and concise way to analyze the performance of different stocks based on their buy and sell transactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70f4652125b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[04: Text Representation (Part-1)]]></title>
            <link>https://farhansarguroh.medium.com/04-text-representation-part-1-b57659320e48?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b57659320e48</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ngrams]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[nlp-learning-series]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 12:40:22 GMT</pubDate>
            <atom:updated>2023-07-19T12:40:22.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><h4>What is feature extraction from text?</h4><p>Feature extraction from text refers to the process of transforming raw text data into a numerical representation that can be used as input for machine learning algorithms. Since most machine learning algorithms work with numerical data, feature extraction is essential to convert unstructured text into a structured format that can be understood by these algorithms.</p><h4>Why do we need it?</h4><p>Feature extraction from text is crucial for transforming unstructured text data into a structured format that can be effectively used by machine learning algorithms, enabling pattern recognition, noise reduction, generalization, and facilitating transfer learning.</p><h4>Why is it difficult?</h4><p>Feature extraction from text is challenging due to the following reasons:</p><p>1. <strong>Unstructured nature:</strong> Text data lacks the inherent structure of structured data, making it difficult to extract meaningful features.</p><p>2. <strong>High dimensionality:</strong> Text data can have a large number of features, such as individual words or phrases, resulting in a high-dimensional feature space that poses computational challenges.</p><p>3. <strong>Contextual ambiguity:</strong> Text often contains ambiguous and context-dependent information, requiring sophisticated techniques to capture and represent the intended meaning accurately.</p><p>4. <strong>Sparsity:</strong> Text data is sparse, with most features appearing infrequently, which creates challenges for traditional machine learning algorithms.</p><p>5. <strong>Language variability:</strong> Text can involve different languages, dialects, slang, or domain-specific jargon, adding complexity to feature extraction.</p><p>6. <strong>Lack of interpretability:</strong> Some feature extraction methods create dense vector representations that lack interpretability, making it harder to understand the original meaning of each feature.</p><p>7. <strong>Domain specificity:</strong> Different domains may require domain-specific knowledge to extract meaningful features, necessitating adaptations of feature extraction techniques.</p><p>8. <strong>Evolving language and data:</strong> Language and data patterns are constantly evolving, requiring adaptable feature extraction methods.</p><p>Overcoming these challenges requires a combination of domain knowledge, linguistic analysis, machine learning techniques, and continuous refinement of feature extraction methods.</p><h4>Common Techniques:</h4><ol><li>Bag of Words (BoW): This approach represents a document as a collection of individual words, disregarding grammar and word order. Each word in the document is treated as a feature, and a matrix is constructed where each row corresponds to a document and each column corresponds to a word. The value in each cell represents the frequency or presence of the word in the document.</li><li>Term Frequency-Inverse Document Frequency (TF-IDF): TF-IDF represents the importance of a word in a document within a collection of documents. It calculates a weight for each word based on its frequency in the document (term frequency) and its rarity across all documents (inverse document frequency). TF-IDF assigns higher weights to words that are more informative and discriminative.</li><li>Word Embeddings: Word embeddings are dense vector representations of words that capture semantic and contextual information. Popular word embedding techniques such as Word2Vec, GloVe, and FastText create vector representations in which similar words have similar vector representations. These embeddings can be used to represent individual words or combined to represent entire documents.</li><li>N-grams: N-grams capture the frequency of consecutive sequences of words in a document. They can be used to preserve some degree of word order information. For example, a 2-gram representation of the sentence “I love to code” would include “I love,” “love to,” and “to code” as features.</li></ol><h3>Common Terms</h3><p><strong>Corpus: </strong>A corpus, in the context of natural language processing and linguistics, refers to a collection of texts or documents that are used as a dataset for language analysis, research, or machine learning tasks. A corpus serves as a representative sample of a particular language or domain, containing a wide range of texts that can be used to study language patterns, analyze linguistic phenomena, or train and evaluate language models.</p><p><strong>Vocabulary: </strong>In natural language processing (NLP), vocabulary refers to the set of unique words or terms that appear in a given corpus or dataset. It represents the collection of all distinct words and their associated properties that are used for language analysis and processing tasks.</p><p><strong>Document: </strong>In the context of NLP (Natural Language Processing), “document” refers to a unit of text that is treated as a single entity for analysis or processing. It can refer to various types of textual units, such as a single sentence, a paragraph, an email, a web page, a news article, or an entire book.</p><p><strong>Word: </strong>In NLP (Natural Language Processing), a “word” refers to the smallest meaningful unit of text that can stand alone or be combined with other words to form sentences. Words play a fundamental role in language understanding and analysis. NLP models and algorithms process and manipulate text at the word level to extract meaning, detect patterns, and perform various language-related tasks.</p><h3>Techniques</h3><h4>One Hot Encoding:</h4><p>One-hot encoding is a technique commonly used in NLP (Natural Language Processing) to represent categorical variables, such as words or tokens, as binary vectors. In the context of NLP, one-hot encoding is applied to convert individual words or tokens from a vocabulary into a numerical representation that can be used as input for machine learning algorithms.</p><p>Here’s how one-hot encoding works in NLP:</p><p>1. Vocabulary Creation: First, a vocabulary is created, which is a set of all unique words or tokens present in the corpus or dataset.</p><p>2. Indexing: Each word in the vocabulary is assigned a unique index or position.</p><p>3. One-Hot Encoding: For each word in a document or sentence, a binary vector of the same length as the vocabulary is created. The vector contains all zeros except for the position that corresponds to the index of the word, which is set to 1. This position indicates the presence of the word in the given document.</p><p>4. Sparse Matrix Representation: The resulting binary vectors form a sparse matrix representation, where each row represents a document or sentence, and each column represents a word in the vocabulary. The matrix contains mostly zeros, except for the positions that correspond to the words present in each document.</p><p>One-hot encoding has some advantages and limitations in NLP:</p><p>Advantages:<br>- Simple and straightforward representation.<br>- Preserves the discrete nature of words.<br>- Can be easily used as input for various machine learning algorithms.</p><p>Limitations:<br>- High dimensionality: One-hot encoding results in a high-dimensional sparse representation, which can be computationally expensive and memory-intensive.<br>- Loss of semantic information: One-hot encoding does not capture the semantic relationships between words or their similarities.<br>- Vocabulary size: The size of the vocabulary can impact the dimensionality of the resulting one-hot encoded vectors, especially when dealing with large corpora.</p><p>One-hot encoding is commonly used in tasks like text classification, document retrieval, or building bag-of-words representations. However, it may not be suitable for tasks that require capturing word relationships or semantic information. In such cases, alternative techniques like word embeddings or contextual embeddings are often preferred.</p><h4>Code:</h4><pre>from sklearn.preprocessing import OneHotEncoder<br><br># Sample data<br>documents = [<br>    &quot;I love to eat pizza&quot;,<br>    &quot;Pizza is my favorite food&quot;,<br>    &quot;I enjoy eating pizza with friends&quot;<br>]<br><br># Create a vocabulary from the documents<br>vocabulary = set()<br>for doc in documents:<br>    words = doc.split()<br>    vocabulary.update(words)<br><br># Convert vocabulary to a list and sort it<br>vocabulary = sorted(list(vocabulary))<br><br># Create an instance of the OneHotEncoder<br>encoder = OneHotEncoder(sparse=False, categories=&#39;auto&#39;)<br><br># Fit and transform the documents<br>onehot_encoded = encoder.fit_transform([[word] for word in vocabulary])<br><br># Print the vocabulary and one-hot encoded vectors<br>print(&quot;Vocabulary:&quot;)<br>print(vocabulary)<br><br><br>print(&quot;\nOne-hot encoded vectors:&quot;)<br>for i, doc in enumerate(documents):<br>    print(f&quot;Document {i+1}:&quot;)<br>    words = doc.split()<br>    for word in words:<br>        word_index = vocabulary.index(word)<br>        print(f&quot;{word}: {onehot_encoded[i, word_index]}&quot;)<br>    print()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*M48CJaHfZAtNVUN5Winuvg.png" /></figure><h4>Bag of Words</h4><p>The Bag of Words (BoW) is a popular and simple technique used in Natural Language Processing (NLP) for representing text data. It treats each document as a collection or “bag” of individual words, disregarding grammar, word order, and context. The Bag of Words model focuses on word frequency and presence in the document to create a numerical representation for further analysis.</p><p>Here’s how the Bag of Words model works:</p><p>1. <strong>Vocabulary Creation:</strong> First, a vocabulary is created by collecting all unique words from the corpus or dataset. Each word in the vocabulary becomes a feature or dimension in the representation.</p><p>2. <strong>Tokenization:</strong> Each document in the corpus is split into individual words or tokens using tokenization techniques. This step typically involves removing punctuation, handling capitalization, and handling special characters.</p><p>3. <strong>Word Frequency Representation:</strong> For each document, a vector is created with the length equal to the size of the vocabulary. The vector represents the frequency or presence of each word in the vocabulary within the document. The values can be binary (presence or absence) or represent the count or frequency of the word in the document.</p><p>4. <strong>Document-Term Matrix:</strong> The collection of vectors from all documents forms a matrix known as the Document-Term Matrix. Each row corresponds to a document, and each column represents a word in the vocabulary. The values in the matrix indicate the occurrence or frequency of each word in each document.</p><p><strong>Code:</strong></p><pre>import pandas as pd<br>from sklearn.feature_extraction.text import CountVectorizer<br><br># Sample documents<br>documents = [<br>    &quot;I love to eat pizza&quot;,<br>    &quot;Pizza is my favorite food&quot;,<br>    &quot;I enjoy eating pizza with friends&quot;<br>]<br>text = pd.DataFrame(documents)<br># Create an instance of CountVectorizer<br>vectorizer = CountVectorizer()<br><br># Fit and transform the documents<br>bag_of_words = vectorizer.fit_transform(documents)<br><br>print(vectorizer.vocabulary_)<br><br>print(&quot;\nBag-of-Words Matrix:&quot;)<br>print(bag_of_words.toarray())</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWvpu4fgG6bF8bF1HRKw1w.png" /></figure><p>The Bag of Words model has some advantages and limitations:</p><p><strong>Advantages:</strong><br>- <em>Simplicity:</em> The Bag of Words model is easy to understand and implement.<br>- <em>Flexibility:</em> It can handle various types of text data, including documents of different lengths and languages.<br>- <em>Computational Efficiency:</em> The representation is computationally efficient and suitable for large datasets.</p><p><strong>Limitations:</strong><br>- <em>Loss of Word Order and Context:</em> The Bag of Words model ignores the word order and context, leading to the loss of valuable information.<br>- <em>Vocabulary Size:</em> The size of the vocabulary can be large, resulting in high-dimensional and sparse representations, especially when dealing with large corpora.<br>- <em>Lack of Semantic Understanding: </em>The model does not capture the semantic relationships or meanings between words.</p><p>The Bag of Words representation serves as input for various NLP tasks, including text classification, sentiment analysis, information retrieval, and document clustering. While it has limitations, the Bag of Words model provides a starting point for text analysis and can be enhanced with advanced techniques like TF-IDF (Term Frequency-Inverse Document Frequency) or word embeddings to capture more semantic information.</p><h4>N-grams:</h4><p>N-grams refer to contiguous sequences of n items (typically words or characters) within a given text. They are commonly used in natural language processing (NLP) and computational linguistics for tasks such as language modeling, text generation, and information retrieval.</p><p>N-grams are created by sliding a window of size n across the text and extracting the sequence of items within that window. For example, in the sentence “I love to code,” if we consider 2-grams (bigrams), we would have the following:</p><p>1. “I love”<br>2. “love to”<br>3. “to code”</p><p>Similarly, if we consider 3-grams (trigrams), we would have:</p><p>1. “I love to”<br>2. “love to code”</p><p>N-grams can provide valuable information about the statistical properties and structure of a text. They can be used to estimate probabilities, identify common phrases or patterns, and generate text that resembles the original input.</p><p>It’s worth noting that the choice of the value for “n” depends on the specific application and the size of the dataset. Smaller values of n capture more local context, while larger values capture more global context but may suffer from sparsity issues if the dataset is small.</p><p>N-grams are widely used in various NLP tasks, including machine translation, sentiment analysis, and text classification. They serve as a foundation for more advanced techniques, such as n-gram language models and the famous n-gram-based smoothing technique known as Laplace smoothing or add-one smoothing.</p><p><strong>Code:</strong></p><pre>import pandas as pd<br>from sklearn.feature_extraction.text import CountVectorizer<br><br># Sample documents<br>documents = [<br>    &quot;I love to eat pizza&quot;,<br>    &quot;Pizza is my favorite food&quot;,<br>    &quot;I enjoy eating pizza with friends&quot;,<br>    &quot;Friends enjoy eating pizza&quot;<br>]<br>df_documents = pd.DataFrame(documents)<br># Create an instance of CountVectorizer with n-gram range<br>vectorizer = CountVectorizer(ngram_range=(1, 3))<br><br># Fit and transform the documents<br>ngram_matrix = vectorizer.fit_transform(documents)<br><br># Get the feature names (n-grams)<br>print(vectorizer.vocabulary_)<br><br>print(&quot;\nBag-of-Words Matrix:&quot;)<br>print(ngram_matrix.toarray())</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNHRDv6H5KULRF2-dqKg1Q.png" /></figure><p>N-grams have several pros and cons that are important to consider when using them in natural language processing (NLP) tasks. Let’s explore some of the advantages and disadvantages:</p><p>Pros of N-grams:</p><p>1. Simple and easy to understand: N-grams provide a straightforward way to represent text data by breaking it down into contiguous sequences of items. This simplicity makes them easy to implement and interpret.</p><p>2. Capturing local context: N-grams capture local dependencies and context within a text. They can identify common phrases, collocations, and patterns that occur frequently, which can be useful for tasks such as text classification and information retrieval.</p><p>3. Efficient storage: N-grams require less storage space compared to more complex language models, making them suitable for large datasets and memory-constrained environments.</p><p>4. Language generation: N-grams can be used for text generation by predicting the next item in a sequence based on the previous n-1 items. This approach is simple and can produce coherent and contextually relevant text, especially for shorter sequences.</p><p>Cons of N-grams:</p><p>1. Limited context: N-grams have a fixed window size, which means they have a limited view of the surrounding context. As a result, they may miss long-range dependencies and global context in the text.</p><p>2. Sparsity and data spillover: When dealing with large values of n or sparse datasets, some n-grams may have low frequencies or even be absent in the training data. This sparsity can lead to inaccurate probability estimates and hinder the effectiveness of NLP models.</p><p>3. Increased computational complexity: As the value of n increases, the number of possible n-grams grows exponentially, resulting in increased computational requirements for training and inference. This can be challenging when dealing with large datasets or real-time applications.</p><p>4. Out-of-vocabulary issues: N-grams rely on a fixed vocabulary of items. Out-of-vocabulary (OOV) words or unseen combinations of items can pose challenges and may require special handling techniques, such as smoothing or backoff strategies.</p><p>5. Lack of semantic understanding: N-grams do not inherently capture semantic meaning or syntactic structure. They focus on statistical patterns based on the co-occurrence of items. This limitation makes it difficult for N-grams alone to comprehend the deeper meaning of language.</p><p>It’s important to note that while N-grams have their limitations, they are still widely used and serve as a fundamental building block in many NLP applications. Researchers and practitioners often combine N-grams with other techniques to overcome their drawbacks and improve overall performance.</p><h4>TF-IDF:</h4><p>TF-IDF stands for Term Frequency-Inverse Document Frequency and is a numerical statistic used in information retrieval and text mining to assess the importance of a term within a document or a collection of documents. It is commonly used to rank and retrieve relevant documents in search engines, text classification, and document clustering tasks.</p><p>The TF-IDF score of a term is calculated based on two components: term frequency (TF) and inverse document frequency (IDF).</p><p>Term Frequency (TF) measures how frequently a term occurs in a document. It is calculated as the ratio of the number of times a term appears in a document to the total number of terms in that document. The idea is that the more frequent a term is within a document, the more important it is for representing the content of that document.</p><p>Inverse Document Frequency (IDF) measures the significance of a term in the entire collection of documents. It is calculated as the logarithm of the ratio of the total number of documents to the number of documents containing the term. The IDF score is higher for terms that appear in fewer documents, indicating their relative rarity and potential importance.</p><p>The TF-IDF score of a term is obtained by multiplying the term frequency (TF) by the inverse document frequency (IDF). The resulting score reflects the relevance of the term to a specific document in the context of the entire document collection.</p><p>The TF-IDF approach helps to address the limitations of simple term frequency by considering both the local importance of a term within a document (TF) and the global significance of the term across the document collection (IDF). It allows for the identification of key terms that are distinctive to a particular document while downplaying terms that are common across many documents.</p><p>Applications of TF-IDF include:</p><p>1. Information retrieval: TF-IDF is used to rank and retrieve relevant documents in search engines. Documents with higher TF-IDF scores for the search terms are considered more relevant.</p><p>2. Text classification: TF-IDF is used to represent documents as numerical feature vectors in machine learning algorithms. The TF-IDF scores serve as input features for training classifiers to categorize documents into predefined classes or topics.</p><p>3. Keyword extraction: TF-IDF can be used to identify important keywords or phrases within a document by selecting terms with high TF-IDF scores.</p><p>4. Document clustering: TF-IDF is utilized to cluster similar documents together by measuring the similarity between their TF-IDF representations.</p><p>It’s worth noting that TF-IDF has its own limitations. For example, it does not consider the semantic relationship between terms and may not capture the full context or meaning of documents. Additionally, it assumes that each term within a document is independent of others, which may not always hold true. Nevertheless, TF-IDF remains a widely used and effective technique in many information retrieval and text mining tasks.</p><h4>Code:</h4><pre>import pandas as pd<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># Sample documents<br>documents = [<br>    &quot;I love to eat pizza&quot;,<br>    &quot;Pizza is my favorite food&quot;,<br>    &quot;I enjoy eating pizza with friends&quot;<br>]<br># Create an instance of TfidfVectorizer<br>vectorizer = TfidfVectorizer()<br><br># Fit and transform the documents<br>tfidf_matrix = vectorizer.fit_transform(documents)<br><br># Get the feature names (terms)<br>print(vectorizer.vocabulary_)<br><br># Print the TF-IDF values<br>print(&quot;TF-IDF Values:&quot;)<br>for i, doc in enumerate(documents):<br>    print(f&quot;Document {i+1}:&quot;)<br>    for j, term in enumerate(vectorizer.vocabulary_):<br>        tfidf_value = tfidf_matrix[i, j]<br>        print(f&quot;{term}: {tfidf_value:.4f}&quot;)<br>    print()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*jrsm1chWbyFL5XGuOfz3oA.png" /></figure><p>TF-IDF has several pros and cons that are important to consider when using this approach for information retrieval and text mining tasks. Let’s explore some of the advantages and disadvantages:</p><p>Pros of TF-IDF:</p><p>1. Term importance: TF-IDF helps identify important terms within a document or a collection of documents. It assigns higher scores to terms that are both frequent within a document (TF) and relatively rare across the document collection (IDF). This allows for the prioritization of significant terms in representing the content of a document.</p><p>2. Versatility: TF-IDF can be applied to various text-based tasks, including information retrieval, text classification, and document clustering. Its flexibility makes it suitable for a wide range of applications.</p><p>3. Simple and interpretable: TF-IDF is a straightforward and interpretable approach. It assigns numerical scores to terms based on their frequencies and document presence, making it easy to understand and explain.</p><p>4. Computational efficiency: Calculating TF-IDF scores is computationally efficient, especially when compared to more complex language models or deep learning approaches. It can handle large collections of documents with reasonable computational resources.</p><p>5. Language independence: TF-IDF is language-independent. It can be applied to text data in any language as long as appropriate preprocessing (e.g., tokenization, stemming) is performed.</p><p>Cons of TF-IDF:</p><p>1. Disregards word order and context: TF-IDF treats each term independently and does not consider the word order or context in which terms appear within documents. This limitation may result in the loss of important semantic information.</p><p>2. Lack of semantic understanding: TF-IDF does not capture the semantic meaning or relationships between terms. It solely relies on statistical measures, which can lead to limited understanding of the text’s deeper semantics.</p><p>3. Sparsity and OOV issues: When dealing with a large vocabulary or sparse data, TF-IDF may suffer from sparsity issues. Rare terms or out-of-vocabulary (OOV) words may have low IDF scores, potentially affecting the overall relevance ranking.</p><p>4. Sensitivity to document length: The term frequency component (TF) of TF-IDF is influenced by document length. Longer documents may have higher term frequencies, potentially biasing the importance of terms solely based on document length.</p><p>5. Difficulty handling synonyms and polysemy: TF-IDF treats each term as a separate entity, which can pose challenges when dealing with synonyms or terms with multiple meanings (polysemy). Synonyms may have different TF-IDF scores, and terms with different meanings may be treated as the same.</p><p>6. Lack of document similarity measures: While TF-IDF can be used to represent documents, it does not directly provide a measure of document similarity. Additional techniques, such as cosine similarity, are often used in conjunction with TF-IDF to compare documents.</p><p>It’s important to note that despite its limitations, TF-IDF remains a widely used and effective approach in many text-based applications. Researchers and practitioners often combine TF-IDF with other techniques, such as word embeddings or neural network models, to address its drawbacks and improve overall performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b57659320e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1321. Restaurant Growth]]></title>
            <link>https://farhansarguroh.medium.com/1321-restaurant-growth-58f97c378f7c?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/58f97c378f7c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 09:38:55 GMT</pubDate>
            <atom:updated>2023-07-16T09:39:17.064Z</atom:updated>
            <content:encoded><![CDATA[<p>Leetcode Medium</p><p>SQL Schema &gt;</p><p>Table: Customer</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| customer_id   | int     |<br>| name          | varchar |<br>| visited_on    | date    |<br>| amount        | int     |<br>+---------------+---------+<br>(customer_id, visited_on) is the primary key for this table.<br>This table contains data about customer transactions in a restaurant.<br>visited_on is the date on which the customer with ID (customer_id) has visited the restaurant.<br>amount is the total paid by a customer.</pre><p>You are the restaurant owner and you want to analyze a possible expansion (there will be at least one customer every day).</p><p>Write an SQL query to compute the moving average of how much the customer paid in a seven days window (i.e., current day + 6 days before). average_amount should be <strong>rounded to two decimal places</strong>.</p><p>Return result table ordered by visited_on <strong>in ascending order</strong>.</p><p>The query result format is in the following example.</p><p><strong>Example 1:</strong></p><pre>Input: <br>Customer table:<br>+-------------+--------------+--------------+-------------+<br>| customer_id | name         | visited_on   | amount      |<br>+-------------+--------------+--------------+-------------+<br>| 1           | Jhon         | 2019-01-01   | 100         |<br>| 2           | Daniel       | 2019-01-02   | 110         |<br>| 3           | Jade         | 2019-01-03   | 120         |<br>| 4           | Khaled       | 2019-01-04   | 130         |<br>| 5           | Winston      | 2019-01-05   | 110         | <br>| 6           | Elvis        | 2019-01-06   | 140         | <br>| 7           | Anna         | 2019-01-07   | 150         |<br>| 8           | Maria        | 2019-01-08   | 80          |<br>| 9           | Jaze         | 2019-01-09   | 110         | <br>| 1           | Jhon         | 2019-01-10   | 130         | <br>| 3           | Jade         | 2019-01-10   | 150         | <br>+-------------+--------------+--------------+-------------+<br>Output: <br>+--------------+--------------+----------------+<br>| visited_on   | amount       | average_amount |<br>+--------------+--------------+----------------+<br>| 2019-01-07   | 860          | 122.86         |<br>| 2019-01-08   | 840          | 120            |<br>| 2019-01-09   | 840          | 120            |<br>| 2019-01-10   | 1000         | 142.86         |<br>+--------------+--------------+----------------+<br>Explanation: <br>1st moving average from 2019-01-01 to 2019-01-07 has an average_amount of (100 + 110 + 120 + 130 + 110 + 140 + 150)/7 = 122.86<br>2nd moving average from 2019-01-02 to 2019-01-08 has an average_amount of (110 + 120 + 130 + 110 + 140 + 150 + 80)/7 = 120<br>3rd moving average from 2019-01-03 to 2019-01-09 has an average_amount of (120 + 130 + 110 + 140 + 150 + 80 + 110)/7 = 120<br>4th moving average from 2019-01-04 to 2019-01-10 has an average_amount of (130 + 110 + 140 + 150 + 80 + 110 + 130 + 150)/7 = 142.86</pre><h4>Explanation :</h4><p>As per the question we have to calculate moving average for a span of 7 days, thus we use rows between 6 preceding and current row and current row where 6 is the number of previous days and current row adds current row, we make a separate column of row number as we have to calculate a span of 7 days, so in order to take out rows other than that (i.e. not completing a span of 7 days e.g. 1–6,2–6,..5–6) we have to filter it that way.</p><h4>Code :</h4><pre>select visited_on, amount, average_amount<br>from<br>(select visited_on,<br>       round(sum(sum(amount)) over(rows between 6 preceding and current row), 2) as amount,<br>       round(avg(sum(amount)) over(rows between 6 preceding and current row), 2) as average_amount,<br>       row_number() over() new<br>from customer<br>group by visited_on<br>order by visited_on) new_tb<br>where new &gt;=7</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58f97c378f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[03: Basic Text Preprocessing (NLP)]]></title>
            <link>https://farhansarguroh.medium.com/03-basic-text-preprocessing-nlp-90ea4469fb87?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/90ea4469fb87</guid>
            <category><![CDATA[text-preprocessing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 17:30:24 GMT</pubDate>
            <atom:updated>2023-07-10T17:30:24.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Text preprocessing is an essential step in natural language processing (NLP) tasks that involves cleaning and transforming raw text data into a format suitable for further analysis or modeling. It helps to standardize the text, remove noise, and reduce dimensionality, leading to improved results in various NLP tasks such as text classification, information extraction, sentiment analysis, and machine translation.</p><h3>Basic Methods for Text Preprocessing:</h3><h4>Lowercasing:</h4><p>Converting all text to lowercase helps to standardize the text and reduce the complexity of the vocabulary. It ensures that words like “apple” and “Apple” are treated as the same word.</p><pre>text = &quot;This is an EXAMPLE text.&quot;<br><br>lowercased_text = text.lower()<br><br>print(lowercased_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*FV9uMg1FxcqNKox2CUbNjg.png" /></figure><h4>Removing HTML tags:</h4><p>Removing HTML tags and special characters: When dealing with text data from web sources, it is common to encounter HTML tags, URLs, and special characters. Removing these elements helps to extract the meaningful text and eliminate noise.</p><p><strong>Code:</strong></p><pre>import re<br><br>def remove_html_tags(text):<br>    clean_text = re.sub(&#39;&lt;.*?&gt;&#39;, &#39;&#39;, text)<br>    return clean_text<br><br>html_text = &quot;&lt;html&gt;This is &lt;b&gt;farhan&lt;/b&gt;, fan of zoro.&lt;/p&gt;&quot;<br><br>clean_text = remove_html_tags(html_text)<br><br>print(clean_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9hVKIbZ7bAa67uQ8ChmtDQ.png" /></figure><h4>Removing URLs</h4><p>Removing URLs from text is a useful practice in NLP for several reasons. It helps to reduce noise by eliminating URLs that often contain non-meaningful characters and parameters. Removing URLs also standardizes the text and reduces dimensionality, making subsequent analysis or modeling more efficient. Additionally, it can contribute to privacy and security by eliminating potentially sensitive or private information. Removing URLs allows for a focused analysis of the textual content and facilitates the extraction of meaningful information based on the context of the remaining text.</p><p><strong>Code:</strong></p><pre>import re<br><br>def remove_urls(text):<br>    clean_text = re.sub(r&#39;http\S+|www\S+|https\S+&#39;, &#39;&#39;, text)<br>    return clean_text<br><br>text_with_urls = &quot;This is a sample text with a URL: https://www.example.com&quot;<br><br>clean_text = remove_urls(text_with_urls)<br><br>print(clean_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*d_Xm6xhvoeKHLxVbWj24sQ.png" /></figure><h4>Removing Punctuation:</h4><p>Removing punctuation marks such as periods, commas, and quotation marks can help eliminate unnecessary noise and simplify the text.</p><p><strong>Code:</strong></p><pre>import string<br><br>def remove_punctuation(text):<br>    cleaned_text = text.translate(str.maketrans(&quot;&quot;, &quot;&quot;, string.punctuation))<br>    return cleaned_text<br><br>text_with_punctuation = &quot;Hello, world! How are you today?&quot;<br><br>cleaned_text = remove_punctuation(text_with_punctuation)<br><br>print(cleaned_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*mP3olK4gNoisxL9KalzsyA.png" /></figure><h4>Chatword Treatment:</h4><p>Chat word treatment refers to the process of handling and processing the unique characteristics of language typically used in online chats or informal digital communication. These chats often involve the use of abbreviations, acronyms, slang, emoticons, and non-standard grammar or spelling.</p><p><strong>Code:</strong></p><pre>import re<br><br>def preprocess_chat_text(text):<br>    # Expand common abbreviations<br>    abbreviation_mapping = {<br>        &quot;lol&quot;: &quot;laugh out loud&quot;,<br>        &quot;brb&quot;: &quot;be right back&quot;,<br>        &quot;omg&quot;: &quot;oh my god&quot;<br>        # Add more mappings as needed<br>    }<br>    <br>    # Replace abbreviations with their expanded forms<br>    for abbreviation, expansion in abbreviation_mapping.items():<br>        text = text.replace(abbreviation, expansion)<br>    <br>    # Remove emoticons<br>    text = re.sub(r&#39;:[a-z]+:&#39;, &#39;&#39;, text)<br>    <br>    # Normalize common misspellings<br>    misspelling_mapping = {<br>        &quot;u&quot;: &quot;you&quot;,<br>        &quot;gr8&quot;: &quot;great&quot;,<br>        # Add more mappings as needed<br>    }<br>    <br>    # Replace misspelled words with their correct forms<br>    for misspelling, correction in misspelling_mapping.items():<br>        text = re.sub(r&quot;\b{}\b&quot;.format(misspelling), correction, text)<br>    <br>    # Tokenize the text<br>    tokens = text.split()<br>    <br>    return tokens<br><br>chat_text = &quot;Hey, lol, brb in a sec :D&quot;<br><br>processed_text = preprocess_chat_text(chat_text)<br><br>print(&quot; &quot;.join(processed_text))</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*oBpy3p3o_mdnRZPDyZESsQ.png" /></figure><h4>Spelling Correction:</h4><p>Spelling correction is a common text preprocessing task that aims to correct misspelled words in a text. There are different approaches to spell correction, but one popular method is using a pre-built dictionary or language model to suggest the most likely correct spelling for a given word.</p><p><strong>Code:</strong></p><pre>from textblob import TextBlob<br>text_with_misspellings = &quot;uuser is smsart.&quot;<br>textblb = TextBlob(text_with_misspellings)<br>textblb.correct().string</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*s_lo_-BzFtjmXJDnUomWrw.png" /></figure><h4>Stopword Removal:</h4><p>Stopword removal is a text preprocessing technique that involves eliminating common words that do not carry significant meaning or contribute much to the overall understanding of the text. These words, known as stopwords, include articles (e.g., “a,” “an,” “the”), pronouns (e.g., “he,” “she,” “it”), prepositions (e.g., “in,” “on,” “at”), and other frequently occurring words in a language.</p><p><strong>Code:</strong></p><pre>import nltk<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br><br>def remove_stopwords(text):<br>    stop_words = set(stopwords.words(&#39;english&#39;))<br>    tokens = word_tokenize(text)<br>    filtered_text = [word for word in tokens if word.lower() not in stop_words]<br>    return &#39; &#39;.join(filtered_text)<br><br>text_with_stopwords = &quot;This is a sample sentence with some stopwords that should be removed.&quot;<br><br>filtered_text = remove_stopwords(text_with_stopwords)<br><br>print(filtered_text)</pre><blockquote>Note: Download these packages first ;)</blockquote><pre>import nltk<br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;punkt&#39;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*RUzeT0a0zIjTOBBI8fPVVQ.png" /></figure><h4>Handling Emoji</h4><p>Handling emojis in text is an important aspect of text preprocessing, especially in contexts such as social media analysis or sentiment analysis where emojis can convey valuable information about emotions or sentiments.</p><p><strong>Removing emoji’s:</strong></p><p>In some cases, you may want to remove emojis from text if they are not relevant to your analysis</p><p><strong>Code:</strong></p><pre>import emoji<br><br>def remove_emojis(text):<br>    cleaned_text = emoji.demojize(text)<br>    cleaned_text = cleaned_text.replace(&quot;:&quot;, &quot;&quot;)<br>    return cleaned_text<br><br>text_with_emojis = &quot;I&#39;m so excited! 😃&quot;<br><br>cleaned_text = remove_emojis(text_with_emojis)<br><br>print(cleaned_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*525JdbrzRgAyZiHhy8CpUg.png" /></figure><p><strong>Translating Emoji’s:</strong></p><p>In some cases translating emoji’s may also be considered to detect the sentiment.</p><p><strong>Code:</strong></p><pre>import emoji<br><br>def convert_to_textual_emojis(text):<br>    converted_text = emoji.demojize(text)<br>    return converted_text<br><br>text_with_emojis = &quot;I&#39;m so excited! 😃&quot;<br><br>converted_text = convert_to_textual_emojis(text_with_emojis)<br><br>print(converted_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*81DKFzFqsxdv4JqS-R1kUA.png" /></figure><h4>Tokenization</h4><p>Chat messages may not always follow standard word boundaries or sentence structures. Specialized tokenization approaches can be employed to handle these cases, such as preserving emoticons as single tokens or recognizing domain-specific contractions.</p><p><strong>Code(regexp):</strong></p><pre>import re<br><br>def tokenize_regex(text):<br>    tokens = re.findall(r&#39;\b\w+\b&#39;, text)<br>    return tokens<br><br>text = &quot;example@gmail.com is my new email id!&quot;<br><br>tokens = tokenize_regex(text)<br><br>print(tokens)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aDWyvKnwhpPqh_Vb_d68ng.png" /></figure><p><strong>Code(nltk):</strong></p><pre>import nltk<br>from nltk.tokenize import word_tokenize<br><br>def tokenize_nltk(text):<br>    tokens = word_tokenize(text)<br>    return tokens<br><br>text = &quot;example@gmail.com is my new email id!&quot;<br><br>tokens = tokenize_nltk(text)<br><br>print(tokens)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*t-mCd4hGdzO8piRdtNnVnA.png" /></figure><p><strong>Code(spacy):</strong></p><pre>import spacy<br><br>def tokenize_spacy(text):<br>    nlp = spacy.load(&#39;en_core_web_sm&#39;)<br>    doc = nlp(text)<br>    tokens = [token.text for token in doc]<br>    return tokens<br><br>text = &quot;example@gmail.com is my new email id!&quot;<br><br>tokens = tokenize_spacy(text)<br><br>print(tokens)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*Fug3Z1jEA4FO85WdHzw-AA.png" /></figure><blockquote>Note: Regexp takes more time as compared to nltk and spacy, both spacy and nltk must be usd according to the question statement, also you can compare all the results as well.</blockquote><h4>Stemming</h4><p>Stemming is a text normalization technique in natural language processing (NLP) that aims to reduce words to their base or root form, known as the stem. The stem may not always be a valid word, but it represents the core meaning of the word.</p><p><strong>Code:</strong></p><pre>import nltk<br>from nltk.stem import PorterStemmer<br><br>def stem_text(text):<br>    stemmer = PorterStemmer()<br>    stemmed_words = [stemmer.stem(word) for word in text.split()]<br>    return &quot; &quot;.join(stemmed_words)<br><br>text = &quot;I love playing football and I played football yesterday.&quot;<br><br>stemmed_text = stem_text(text)<br><br>print(stemmed_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*1t9DWRK20XgrPY0XjYwvLQ.png" /></figure><h4>Lemmatization</h4><p>Lemmatization is a specific type of normalization that reduces words to their base or dictionary form called the lemma. Unlike stemming, lemmatization considers the context and part of speech (POS) of the word, producing a more meaningful base form.</p><p><strong>Code:</strong></p><pre>import nltk<br>from nltk.stem import WordNetLemmatizer<br>from nltk.tokenize import word_tokenize<br><br>def lemmatize_text(text):<br>    lemmatizer = WordNetLemmatizer()<br>    lemmatized_words = [lemmatizer.lemmatize(word) for word in word_tokenize(text)]<br>    return &quot; &quot;.join(lemmatized_words)<br><br>text = &quot;I love playing football and I played football yesterday.&quot;<br><br>lemmatized_text = lemmatize_text(text)<br><br>print(lemmatized_text)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*KDup26o4wFg8da6HsEE4Ew.png" /></figure><h4>Stemming vs Lemmatization</h4><p>stemming is a simpler and faster method that reduces words to their stems, while lemmatization is a more sophisticated approach that considers the context and part of speech to obtain the base forms of words. The choice between stemming and lemmatization depends on the specific requirements of your NLP task and the trade-offs between speed and linguistic accuracy.</p><p>Leave a follow if you found it useful :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90ea4469fb87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[185. Department Top Three Salaries]]></title>
            <link>https://farhansarguroh.medium.com/185-department-top-three-salaries-58e012e19920?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/58e012e19920</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 09:18:07 GMT</pubDate>
            <atom:updated>2023-07-09T09:18:07.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>( Leetcode Hard )</h3><p>Table: Employee</p><pre>+--------------+---------+<br>| Column Name  | Type    |<br>+--------------+---------+<br>| id           | int     |<br>| name         | varchar |<br>| salary       | int     |<br>| departmentId | int     |<br>+--------------+---------+<br>id is the primary key column for this table.<br>departmentId is a foreign key of the ID from the Department table.<br>Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.</pre><p>Table: Department</p><pre>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| id          | int     |<br>| name        | varchar |<br>+-------------+---------+<br>id is the primary key column for this table.<br>Each row of this table indicates the ID of a department and its name.</pre><p>A company’s executives are interested in seeing who earns the most money in each of the company’s departments. A <strong>high earner</strong> in a department is an employee who has a salary in the <strong>top three unique</strong> salaries for that department.</p><p>Write an SQL query to find the employees who are <strong>high earners</strong> in each of the departments.</p><p>Return the result table <strong>in any order</strong>.</p><p>The query result format is in the following example.</p><p><strong>Example 1:</strong></p><pre>Input: <br>Employee table:<br>+----+-------+--------+--------------+<br>| id | name  | salary | departmentId |<br>+----+-------+--------+--------------+<br>| 1  | Joe   | 85000  | 1            |<br>| 2  | Henry | 80000  | 2            |<br>| 3  | Sam   | 60000  | 2            |<br>| 4  | Max   | 90000  | 1            |<br>| 5  | Janet | 69000  | 1            |<br>| 6  | Randy | 85000  | 1            |<br>| 7  | Will  | 70000  | 1            |<br>+----+-------+--------+--------------+<br>Department table:<br>+----+-------+<br>| id | name  |<br>+----+-------+<br>| 1  | IT    |<br>| 2  | Sales |<br>+----+-------+<br>Output: <br>+------------+----------+--------+<br>| Department | Employee | Salary |<br>+------------+----------+--------+<br>| IT         | Max      | 90000  |<br>| IT         | Joe      | 85000  |<br>| IT         | Randy    | 85000  |<br>| IT         | Will     | 70000  |<br>| Sales      | Henry    | 80000  |<br>| Sales      | Sam      | 60000  |<br>+------------+----------+--------+<br>Explanation: <br>In the IT department:<br>- Max earns the highest unique salary<br>- Both Randy and Joe earn the second-highest unique salary<br>- Will earns the third-highest unique salary</pre><pre>In the Sales department:<br>- Henry earns the highest salary<br>- Sam earns the second-highest salary<br>- There is no third-highest salary as there are only two employees</pre><h4>Explanation:</h4><p>Since the question asks us to get the top three salaries of each department we just have to use the dense_rank() function and partition it by departments in descending order and create a new table (Since, derived columns cannot be used in the where clause), then, just select ranks less than or equal to three.</p><p>Happy Coding ! :)</p><h4>Code:</h4><pre>select Department, Employee, Salary<br>from ( <br>select d.name as Department, e.name as Employee, e.salary as Salary, dense_rank() over(<br>                       partition by d.name <br>                       order by salary desc <br>                       ) new <br>from employee e<br>join department d <br>on e.departmentId = d.id<br>) tab<br>where new &lt;= 3</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58e012e19920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1341. Movie Rating ( Leetcode )]]></title>
            <link>https://farhansarguroh.medium.com/1341-movie-rating-leetcode-9d7e4dd150e6?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7e4dd150e6</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 12:53:27 GMT</pubDate>
            <atom:updated>2023-07-08T12:53:27.321Z</atom:updated>
            <content:encoded><![CDATA[<p>1341. Movie Rating</p><p>SQL Schema</p><p>Table: Movies</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| movie_id      | int     |<br>| title         | varchar |<br>+---------------+---------+<br>movie_id is the primary key for this table.<br>title is the name of the movie.</pre><p>Table: Users</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| user_id       | int     |<br>| name          | varchar |<br>+---------------+---------+<br>user_id is the primary key for this table.</pre><p>Table: MovieRating</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| movie_id      | int     |<br>| user_id       | int     |<br>| rating        | int     |<br>| created_at    | date    |<br>+---------------+---------+<br>(movie_id, user_id) is the primary key for this table.<br>This table contains the rating of a movie by a user in their review.<br>created_at is the user&#39;s review date.</pre><p>Write an SQL query to:</p><ul><li>Find the name of the user who has rated the greatest number of movies. In case of a tie, return the lexicographically smaller user name.</li><li>Find the movie name with the <strong>highest average</strong> rating in February 2020. In case of a tie, return the lexicographically smaller movie name.</li></ul><p>The query result format is in the following example.</p><p><strong>Example 1:</strong></p><pre>Input: <br>Movies table:<br>+-------------+--------------+<br>| movie_id    |  title       |<br>+-------------+--------------+<br>| 1           | Avengers     |<br>| 2           | Frozen 2     |<br>| 3           | Joker        |<br>+-------------+--------------+<br>Users table:<br>+-------------+--------------+<br>| user_id     |  name        |<br>+-------------+--------------+<br>| 1           | Daniel       |<br>| 2           | Monica       |<br>| 3           | Maria        |<br>| 4           | James        |<br>+-------------+--------------+<br>MovieRating table:<br>+-------------+--------------+--------------+-------------+<br>| movie_id    | user_id      | rating       | created_at  |<br>+-------------+--------------+--------------+-------------+<br>| 1           | 1            | 3            | 2020-01-12  |<br>| 1           | 2            | 4            | 2020-02-11  |<br>| 1           | 3            | 2            | 2020-02-12  |<br>| 1           | 4            | 1            | 2020-01-01  |<br>| 2           | 1            | 5            | 2020-02-17  | <br>| 2           | 2            | 2            | 2020-02-01  | <br>| 2           | 3            | 2            | 2020-03-01  |<br>| 3           | 1            | 3            | 2020-02-22  | <br>| 3           | 2            | 4            | 2020-02-25  | <br>+-------------+--------------+--------------+-------------+<br>Output: <br>+--------------+<br>| results      |<br>+--------------+<br>| Daniel       |<br>| Frozen 2     |<br>+--------------+<br>Explanation: <br>Daniel and Monica have rated 3 movies (&quot;Avengers&quot;, &quot;Frozen 2&quot; and &quot;Joker&quot;) but Daniel is smaller lexicographically.<br>Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smaller lexicographically.</pre><p>Explanation:</p><p>The question has two different outcomes to be fulfilled, its very obvious we’ll have to use union in order to solve this problem.</p><ol><li>The first requirement is to identify the name of the user who has rated the greatest number of movies, easy, just order by the count of ratings in descending order and name (to return the lexicographically smaller user name in case of tie) and limit by 1, you will get the very first value.</li><li>Our second requirement is similar to the first one, we just have to use the where clause in order to filter our solution for February 2020, and then order them by average of rating in descending order (since, maximum average rating is asked) and name (to return the lexicographically smaller user name in case of tie) and limit by 1, you will get the very first value, again.</li></ol><p>What bugged me is the 17th testcase, i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*pt_q3v0KY3FWlLI3r0YJ5Q.png" /></figure><p>Here, the title (i.e. movie name) is same as the name of the user, thus I had the same thing repeated twice, in order to fix that I went from union to union all and the task was done.</p><p>Happy Coding :)</p><pre>select results<br>from (<br>  select u.name results<br>  from MovieRating mr<br>  join users u on mr.user_id = u.user_id<br>  group by u.name<br>  order by count(mr.rating) desc, name<br>  limit 1 <br>  ) as ratings<br>union all<br>select results <br>from (<br>  select m.title results<br>  from MovieRating mr2<br>  join Movies m on mr2.movie_id = m.movie_id <br>  where DATE_FORMAT(mr2.created_at, &quot;%Y-%m&quot;) = &#39;2020-02&#39;<br>  group by m.title<br>  order by avg(mr2.rating) desc, m.title <br>  limit 1<br>) movie_ratings</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7e4dd150e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[02: NLP Pipeline`]]></title>
            <link>https://farhansarguroh.medium.com/02-nlp-pipeline-de3bf51f5a7f?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3bf51f5a7f</guid>
            <category><![CDATA[nlp-training]]></category>
            <category><![CDATA[end-to-end]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 05:10:09 GMT</pubDate>
            <atom:updated>2023-07-07T05:10:09.194Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is NLP Pipeline?</h3><p>A set of steps followed to build an end to end NLP software.</p><h4><strong>NLP software consists of following steps:</strong></h4><ol><li><strong>Data Acquisition</strong></li><li><strong>Text Preparation : </strong>Text Cleanup, Basic Preprocessing, Advanced Preprocessing</li><li><strong>Feature Engineering</strong></li><li><strong>Modelling:</strong> Model building, Evaluation</li><li><strong>Deployment: </strong>Deployment, Monitoring, Model Update</li></ol><blockquote>Note: This is not a universally accepted pipeline, Deep learning pipelines are slightly different, Pipeline is non linear.</blockquote><h3>Data Acquisition</h3><ul><li>Available data ( table, database(database team to create a warehouse), less data(Data augmentation(GPT, Sigma flip))</li></ul><ol><li>Through available Tables: Data acquisition from tables for NLP tasks involves extracting textual information from structured tabular data. The process includes identifying relevant tables that contain the desired text fields and converting the table data into a suitable format for NLP analysis.</li><li>Through Company Database : Data acquisition through a company database involves obtaining authorized access to the database and querying the data to extract the desired information for analysis or further processing. You have to collaborate with the team of Database engineers to acquire this data.</li><li>When there is less data available Data Augmentation is used:</li></ol><p>Data augmentation is a technique used to artificially increase the size and diversity of a dataset by creating modified or synthetic versions of existing data. In the context of NLP, data augmentation methods aim to introduce variations to the textual data while preserving the original meaning or intent. Data augmentation can help improve the performance and generalization of NLP models, especially when the available labeled data is limited.</p><p>Here are some commonly used data augmentation techniques in NLP:</p><ol><li>Synonym Replacement: Replace words or phrases in the text with their synonyms. This can be done using pre-trained word embeddings or lexical resources like WordNet.</li><li>Back-Translation: Translate the text from the source language to one or more target languages using machine translation models and then translate it back to the source language. This introduces variations in the wording and sentence structure.</li><li>Paraphrasing: Generate paraphrased versions of sentences using techniques like neural machine translation models, paraphrase generation models, or rule-based methods.</li></ol><ul><li>Corpus and Dataset Selection: Identify suitable corpora or datasets that align with your NLP task. This could include publicly available datasets, domain-specific data, or data collected specifically for your project.</li><li>Web Scraping: Extracting data from websites is a common method to acquire text data. Web scraping tools and libraries, such as BeautifulSoup or Scrapy, can help automate this process by parsing the HTML structure and extracting relevant text.</li><li>Publicly Available Datasets: Many organizations and research institutions provide publicly available datasets for NLP research. Examples include the Common Crawl, Wikipedia dumps, sentiment analysis datasets, question-answering datasets, and more. These datasets often require preprocessing and filtering based on your specific task.</li><li>APIs and Web Services: Some platforms and services offer APIs for accessing and retrieving textual data. For example, social media platforms like Twitter, Facebook, or Reddit provide APIs to fetch public posts and comments.</li><li>Crowdsourcing: Crowdsourcing platforms like Amazon Mechanical Turk or Figure Eight (previously CrowdFlower) can be utilized to collect labeled data by creating annotation tasks for human workers. This approach is useful when fine-grained human judgment is required for labeling tasks.</li></ul><h3>Text Preparation</h3><h4>Basic Clean up:</h4><p>Text data cleaning in NLP (Natural Language Processing) involves preprocessing and transforming raw text data into a cleaner and more standardized format. This process helps remove noise, irrelevant information, and inconsistencies, making the text data more suitable for analysis and modeling. Here are some common techniques used in text data cleaning:</p><ol><li>Spell Checking: Correcting misspelled words using techniques like dictionary-based approaches or statistical models.</li><li>Removing HTML Tags: If the text data contains HTML tags, removing them to extract only the text content.</li><li>Handling Numerical Data: Treating numbers as a separate entity or converting them into a standardized format, such as replacing all numbers with a generic placeholder like “NUM.”</li><li>Dealing with Special Characters and Encoding: Handling special characters, foreign characters, or non-ASCII characters by encoding or replacing them appropriately.</li></ol><h4>Basic preprocessing:</h4><p>1. Tokenization: Splitting the text into individual words or tokens. This step helps in understanding the basic units of text.</p><p>2. Lowercasing: Converting all text to lowercase to ensure case insensitivity and reduce the vocabulary size. This step helps in treating “apple” and “Apple” as the same word.</p><p>3. Stopword Removal: Removing common words that do not carry significant meaning, such as articles, pronouns, or prepositions (e.g., “the,” “and,” “is”). This step reduces noise in the data and focuses on important content words.</p><p>4. Punctuation Removal: Removing punctuation marks, symbols, and special characters from the text. This step helps in simplifying the text and focusing on the essential words.</p><p>5. Normalization: Converting different variants of a word into a standard format. This can involve techniques like stemming (reducing words to their root form, e.g., “running” to “run”) or lemmatization (reducing words to their base or dictionary form, e.g., “better” to “good”).</p><p>6. Stemming and lemmatization are techniques used in NLP for normalizing words by reducing them to their base or root forms. Both techniques help in reducing variations of words to a common representation, which can improve text analysis and understanding. <br>Stemming reduces words to their base form by removing prefixes and suffixes, while lemmatization determines the base form of a word based on its dictionary definition, considering the part of speech. Lemmatization produces valid words, whereas stemming may result in non-words.</p><h4>Advanced preprocessing</h4><ol><li>Part-of-speech (POS) tagging is the process of assigning grammatical tags to words in a sentence, indicating their syntactic roles and categories. It helps in understanding the structure of a sentence and disambiguating word meanings.</li><li>Parsing, in the context of natural language processing (NLP), refers to the process of analyzing the syntactic structure of a sentence and determining its grammatical relationships. It involves breaking down a sentence into its constituent parts and representing them in a structured format such as a parse tree or a dependency graph.</li><li>Coreference resolution is a natural language processing task that involves identifying and linking noun phrases (or named entities) within a text that refer to the same entity. The goal is to determine when different expressions or mentions in a sentence or document actually refer to the same thing.</li></ol><h3>Feature Engineering</h3><p>Feature engineering plays a crucial role in Natural Language Processing (NLP) tasks, as it involves transforming raw text data into a numerical representation that machine learning algorithms can understand and process.</p><h4>Methods?</h4><ol><li>Bag-of-Words (BoW): In this approach, each document is represented as a bag of individual words or tokens, disregarding grammar and word order. The frequency or presence/absence of words can be used as features. Stop words (common words like “the,” “is,” etc.) are often removed to reduce noise.</li><li>Term Frequency-Inverse Document Frequency (TF-IDF): This technique assigns a weight to each word in a document based on its frequency in the document (term frequency) and its rarity across all documents in a corpus (inverse document frequency). It helps identify important and distinctive words within a document.</li><li>Word Embeddings: Word embeddings are dense vector representations of words in a high-dimensional space. Techniques like <em>Word2Vec</em>, <em>GloVe</em>, and <em>FastTex</em>t can generate these embeddings based on the distributional properties of words. Embeddings capture semantic relationships between words and can be used as features or input to machine learning models</li></ol><p>Feature engineering can follow ML or DL approaches, However both have their set of advantages and disadvantages. Let’s discuss this in detail:</p><h4>ML Approach:</h4><p>ML models often require extensive feature engineering to extract meaningful representations from raw data. Engineers or data scientists manually design and select features that are relevant to the task at hand.</p><ol><li>Advantages : Outcomes can be justified (Since, one has manually selected the features, the interpretation of outcomes becomes easy)</li><li>Disadvantages:</li></ol><ul><li>Some features can result into disadvantage for the model and may mess the functioning of model.</li><li>A lot of Domain knowledge is required to pull this off which increases the workload.</li></ul><h4>DL Approach:</h4><p>DL models can learn representations directly from raw data, eliminating the need for explicit feature engineering. Deep neural networks can automatically learn and discover useful features at different levels of abstraction from the input data.</p><ol><li>Advantages: Features are developed without any prior domain knowledge by the neural networks.</li><li>Disadvantages: Outcomes cannot be justified easily which causes issues in interpretability.</li></ol><blockquote>Note : The nature of problem determines the type of approach you choose.</blockquote><h3>Modelling and Evaluation</h3><p>Modelling in Natural Language Processing (NLP) involves building computational models that can understand and generate human language. These models aim to capture the inherent structure, semantics, and context of textual data to perform various NLP tasks. Here are some common approaches and models used in NLP modelling:</p><p>1. Rule-based Models: Rule-based models rely on explicit linguistic rules and patterns to process and analyze text. These rules can be handcrafted by experts or derived from linguistic resources. Rule-based models are useful for tasks like part-of-speech tagging, named entity recognition, or syntactic parsing. However, they often struggle with capturing complex linguistic phenomena and require extensive manual engineering.</p><p>2. Statistical Models: Statistical models in NLP use machine learning techniques to learn patterns and associations from labeled training data. These models make use of various algorithms like Naive Bayes, Hidden Markov Models (HMM), Conditional Random Fields (CRF), or Maximum Entropy Markov Models (MEMM). Statistical models can be effective for tasks like text classification, sentiment analysis, or sequence labeling.</p><p>3. Neural Network Models: Neural network models, particularly deep learning models, have made significant advancements in NLP. These models leverage artificial neural networks with multiple layers to learn hierarchical representations of text data. Some popular neural network architectures for NLP include:</p><p>- Recurrent Neural Networks (RNN): RNNs are designed to process sequential data and have recurrent connections that allow information to persist over time. They are commonly used for tasks involving sequential data, such as language modeling, machine translation, and sentiment analysis.</p><p>- Convolutional Neural Networks (CNN): CNNs are well-suited for tasks that involve local patterns and structure in text data. They excel at tasks like text classification and sentiment analysis, where capturing local features is important.</p><p>- Transformer Models: Transformers have revolutionized many NLP tasks and achieved state-of-the-art performance. They employ attention mechanisms to capture global dependencies in text data and have been instrumental in tasks such as machine translation, language understanding, and text generation. Models like BERT, GPT, and T5 are based on transformer architectures.</p><p>4. Pre-trained Language Models: Pre-trained language models have gained popularity in recent years. These models are trained on large corpora and learn rich representations of text. They are often fine-tuned on specific downstream tasks, leveraging transfer learning. Models like BERT, GPT, and RoBERTa have demonstrated remarkable performance across various NLP tasks.</p><p>5. Sequence-to-Sequence Models: Sequence-to-sequence models are used for tasks that involve generating sequences from input sequences. They employ architectures like Recurrent Neural Networks (RNN) or Transformers to generate translations, summarizations, or responses. Sequence-to-sequence models have been influential in machine translation, chatbots, and text summarization.</p><p>6. Reinforcement Learning Models: Reinforcement learning techniques can be applied to NLP tasks, particularly in dialogue systems and conversational agents. These models learn to interact with an environment and optimize their responses based on rewards or feedback.</p><p>Cloud APIs can also be used</p><blockquote>Note: These are just a few examples of the modelling approaches used in NLP. The choice of model depends on the specific task, available data, and computational resources. It’s common to experiment with different models, architectures, and techniques to find the most suitable approach for a given NLP task.</blockquote><p><strong>Evaluation is usually based on the results of unseen data.</strong></p><h4>Two key ways for evaluation are:</h4><ol><li>Intrinsic Evaluation: Intrinsic evaluation focuses on assessing the performance of a model on a specific NLP task or subtask in isolation, without considering its impact on downstream applications. It aims to measure how well the model performs a particular linguistic or NLP-related objective. Intrinsic evaluation typically involves using specific evaluation metrics designed for the task at hand. Its the “Technical” aspect for evaluation.</li><li>Extrinsic Evaluation: Extrinsic evaluation assesses the performance of an NLP model within the context of a larger application or downstream task. Instead of measuring the model’s performance in isolation, extrinsic evaluation considers the impact of the model on the overall performance of the application. It aims to evaluate how well the NLP model contributes to solving real-world problems or tasks. Its the “Business centric” aspect for evaluation</li></ol><h3>Deployment</h3><p>Deployment in the context of natural language processing (NLP) refers to the process of taking a trained NLP model or system and making it available for use in a production environment.</p><h4>Key tasks:</h4><ol><li>Deploy : Deploying an NLP model involves integrating it into an application, setting up the necessary infrastructure, and making it accessible to end-users.</li><li>Monitoring : Monitoring an NLP model typically involves tracking its performance, usage, and any potential issues. By consistently monitoring performance, resource usage, and gathering user feedback, you can ensure the model’s reliability, identify potential areas for improvement, and address any issues promptly. ( For ex. Track Performance metrics, Collect user Feedback, Monitor system resource uses)</li><li>Update : Updating an NLP model based on evaluation involves utilizing the insights and feedback obtained from the evaluation process to make improvements to the model.</li></ol><p>Thankyou :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3bf51f5a7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triangle Quest 2 (Hackerrank)]]></title>
            <link>https://farhansarguroh.medium.com/triangle-quest-2-hackerrank-5dc82727fc0b?source=rss-d2182225ddc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc82727fc0b</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[hackerrank]]></category>
            <dc:creator><![CDATA[Farhan Sarguroh]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 11:10:03 GMT</pubDate>
            <atom:updated>2023-07-06T11:10:03.755Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given a positive integer .<br>Your task is to print a palindromic triangle of size .</p><p>For example, a palindromic triangle of size is:</p><pre>1<br>121<br>12321<br>1234321<br>123454321</pre><p>You can’t take more than two lines. The first line (a for-statement) is already written for you.<br>You have to complete the code using exactly one print statement.</p><p><strong>Note</strong>:<br>Using anything related to strings will give a score of .<br>Using more than one for-statement will give a score of .</p><p><strong>Input Format</strong></p><p>A single line of input containing the integer .</p><p><strong>Constraints</strong></p><p><strong>Output Format</strong></p><p>Print the palindromic triangle of size as explained above.</p><p><strong>Sample Input</strong></p><pre>5</pre><p><strong>Sample Output</strong></p><pre>1<br>121<br>12321<br>1234321<br>123454321</pre><h3>Explanation:</h3><p>The basic idea for palindromic triangle is, as soon as you reach the number equal to current iteration you go backtrack to the first number of your row i.e. if you are at i = 3, the row should stop at 3 (123) and then it should backtrack ( 12321).</p><p>Here, the question asks to derive the logic in one line (no nested loops allowed :( ), so, we observe a pattern here which repeats when you square 1, you get 1, when you square 11 you get 121, when you square 111 you get 12321 thus, we simply have to repeat this strategy, n (input) number of times.</p><p>For that very purpose, we have to derive our logic in such a way that our loop squares 1, 11, 111 over each iteration. Thus if we square the result of the value we get dividing (10**i— 1) where i is the iteration ( ex : 10¹–1 = 9, 10²-1 = 99, 10³-1 = 999) by 9 ( we use // to get the nearest whole number), we get 1, 11, 111. These results gets squared and returns the required output.</p><p>Happy Coding :)</p><h3>Code:</h3><pre>for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also<br>    print(((10**i-1)//9)**2)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc82727fc0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>