<?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 Annanya Pandey on Medium]]></title>
        <description><![CDATA[Stories by Annanya Pandey on Medium]]></description>
        <link>https://medium.com/@AnnanyaPandey?source=rss-81b96b652c20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Annanya Pandey on Medium</title>
            <link>https://medium.com/@AnnanyaPandey?source=rss-81b96b652c20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AnnanyaPandey/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[Building a Custom grep-Like Pattern Matcher in Go]]></title>
            <link>https://medium.com/@AnnanyaPandey/building-a-custom-grep-like-pattern-matcher-in-go-40825fb9c98d?source=rss-81b96b652c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/40825fb9c98d</guid>
            <category><![CDATA[regexp]]></category>
            <category><![CDATA[grep]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Annanya Pandey]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 03:55:51 GMT</pubDate>
            <atom:updated>2024-10-11T03:55:51.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pqQUWEPdtTFh_bW1e_6pw.png" /></figure><h3>Introduction</h3><p>In this post, I’ll walk you through building a custom pattern matcher in Go, mimicking the behaviour of the popular grep command.</p><p>Pattern matching is a powerful technique used in programming to check if a certain sequence of characters (or data) conforms to a specific pattern. It allows us to search, identify, and extract information from a body of text based on given criteria. In tools like grep, pattern matching is essential for sifting through large files, logs, or data streams to find specific strings or formats efficiently. Its applications span across fields like data validation, syntax parsing, and text processing, making it an indispensable tool for developers working with large data sets or automating searches within files.</p><p>This tool enables you to search for patterns within lines of text using regular expressions, with support for special characters like *, +, ?, [], and ^.</p><p>We’ll break down the journey into the matcher&#39;s components, starting with simple cases and gradually handling more complex patterns.</p><h3>Why Build a Custom grep?</h3><p>While Go provides regexp for regular expressions, writing your own matcher gives a better understanding of how such tools work. By implementing common features step by step, you’ll uncover the underlying mechanisms and pitfalls.</p><h3>Features Covered</h3><ul><li>Anchoring patterns with ^ (start) and $ (end)</li><li>Character classes like [abc] and [a-z]</li><li>Quantifiers such as + (one or more) and ? (zero or one)</li><li>Handling alternation ((cat|dog))</li><li>Escape sequences such as \d (digit) and \w (word character)</li><li>Literal character matches</li></ul><h3>Code Walkthrough</h3><h4>Step 1: Anchoring Patterns</h4><p>The core of the matcher checks if any part of the input line matches the given pattern. This is handled by the MatchLine function, which starts by handling special cases like anchoring (^, $) before falling back on checking each position of the line for a match. Anchoring patterns are those found either at the start or end of a pattern.</p><p>To match patterns anchored to the start (^) or end ($) of the line or for negated character classes ([^), the code checks for these symbols and limits the search to specific positions.</p><pre>// matchLine checks if any part of the line matches the pattern<br>func MatchLine(line []byte, pattern string) (bool, error) {<br> if utf8.RuneCountInString(pattern) == 0 {<br>  return false, fmt.Errorf(&quot;unsupported pattern: %q&quot;, pattern)<br> }<br><br> // Check if pattern starts with &#39;^&#39; and ends with &#39;$&#39;<br> if pattern[0] == &#39;^&#39; &amp;&amp; pattern[len(pattern)-1] == &#39;$&#39; {<br>  return matchExact(line, pattern[1:len(pattern)-1]), nil<br> }<br> // Check if pattern starts with &#39;^&#39;<br> if pattern[0] == &#39;^&#39; {<br>  return matchFromPosition(line, pattern[1:]), nil<br> }<br> // Check if pattern ends with &#39;$&#39;<br> if pattern[len(pattern)-1] == &#39;$&#39; {<br>  return matchFromEnd(line, pattern[0:len(pattern)-1]), nil<br> }<br><br> // Iterate through each position in the line to try matching the pattern<br> for i := 0; i &lt; len(line); i++ {<br>  if strings.HasPrefix(pattern, &quot;[^&quot;) &amp;&amp; !matchFromPosition(line[i:], pattern) {<br>   return false, nil<br>  }<br>  if matchFromPosition(line[i:], pattern) {<br>   return true, nil<br>  }<br> }<br><br> return false, nil<br>}</pre><h4>Step 2: Matching Escape Sequence</h4><p>The code supports escape sequences, such as \d for digits and \w for word characters (letters, digits, and underscores). These are matched using Go’s unicode package.</p><pre>if patternRune == &#39;\\&#39; {<br>   j += patternSize<br>   patternRune, patternSize = utf8.DecodeRuneInString(pattern[j:])<br>   switch patternRune {<br>   // Match a digit<br>   case &#39;d&#39;:<br>    if !unicode.IsDigit(lineRune) {<br>     return false<br>    }<br>    i += lineSize<br>    j += patternSize<br>    continue<br>   // Match a word character (alphanumeric or underscore)<br>   case &#39;w&#39;:<br>    if !unicode.IsLetter(lineRune) &amp;&amp; !unicode.IsDigit(lineRune) &amp;&amp; lineRune != &#39;_&#39; {<br>     return false<br>    }<br>    i += lineSize<br>    j += patternSize<br>    continue<br>   // Invalid escape sequence<br>   default:<br>    return false<br>   }<br>  }</pre><h4>Step 3: Handling Alternation (cat|dog)</h4><p>The alternation operator allows matching one of several options (e.g., (cat|dog) matches either &quot;cat&quot; or &quot;dog&quot;). The code handles this by splitting the pattern inside the parentheses and checking each alternative.</p><pre>if patternRune == &#39;(&#39; {<br>   // Handle alternation (e.g., (cat|dog))<br>   j += patternSize<br>   endIdx := j<br>   depth := 1 // Keep track of nested parentheses<br>   for endIdx &lt; len(pattern) {<br>    if pattern[endIdx] == &#39;(&#39; {<br>     depth++<br>    } else if pattern[endIdx] == &#39;)&#39; {<br>     depth--<br>     if depth == 0 {<br>      break<br>     }<br>    }<br>    endIdx++<br>   }<br>   if endIdx &gt;= len(pattern) || pattern[endIdx] != &#39;)&#39; {<br>    return false // Unmatched parentheses<br>   }<br>   // Extract the alternation inside the parentheses<br>   alternation := pattern[j:endIdx]<br>   alternatives := strings.Split(alternation, &quot;|&quot;)<br>   // Try each alternative<br>   for _, alt := range alternatives {<br>    if matchFromPosition(line[i:], alt) {<br>     // If one of the alternatives matches, skip over the entire `(cat|dog)` part<br>     j = endIdx + 1<br>     return matchFromPosition(line[i:], pattern[j:])<br>    }<br>   }<br>   // No alternatives matched<br>   return false<br>  }</pre><h4>Step 4: Matching Character Classes</h4><p>Character classes such as [abc] or [a-z] allow flexible matching of any character from the specified set. The code also handles negated classes ([^abc]) where the match is successful if none of the specified characters appear.</p><pre>if patternRune == &#39;[&#39; {<br>   // Handle character classes like [abc] or [^abc]<br>   j += patternSize<br>   isNegated := false<br>   charSet := &quot;&quot;<br><br>   // Check if it&#39;s a negated character class<br>   if nextRune, nextSize := utf8.DecodeRuneInString(pattern[j:]); nextRune == &#39;^&#39; {<br>    isNegated = true<br>    j += nextSize // Move past the &#39;^&#39;<br>   }<br><br>   // Collect characters in the character class until we hit a closing `]`<br>   for {<br>    char, size := utf8.DecodeRuneInString(pattern[j:])<br>    if char == &#39;]&#39; {<br>     j += size // Move past the closing bracket<br>     break<br>    }<br>    charSet += string(char)<br>    j += size<br>   }<br><br>   // Check if the current lineRune matches the character class<br>   matches := false<br>   for _, c := range charSet {<br>    if lineRune == rune(c) {<br>     matches = true<br>     break<br>    }<br>   }<br><br>   // Handle negated class or normal class behavior<br>   if (isNegated &amp;&amp; matches) || (!isNegated &amp;&amp; !matches) {<br>    // If negated and matched, or not negated but didn&#39;t match, return false<br>    return false<br>   }<br><br>   // If character class matched correctly, proceed<br>   i += lineSize<br>   continue<br>  }</pre><h4>Step 5: Quantifiers</h4><p>Quantifiers allow flexible matching of repeated characters or groups. For example, + matches one or more occurrences of the previous element, while ? matches zero or one occurrence. This is handled in the following way:</p><pre>// Handle quantifiers like &#39;+&#39; (one or more) and &#39;?&#39; (zero or one)<br>  if j+patternSize &lt; len(pattern) &amp;&amp; (pattern[j+patternSize] == &#39;+&#39; || pattern[j+patternSize] == &#39;?&#39;) {<br>   prevRune := patternRune<br>   quantifier := pattern[j+patternSize]<br>   j += patternSize + 1 // Move past the quantifier<br><br>   // Handle the &#39;+&#39; quantifier (one or more)<br>   if quantifier == &#39;+&#39; {<br>    // Ensure the first occurrence matches<br>    if prevRune != lineRune {<br>     return false<br>    }<br>    i += lineSize<br><br>    // Continue matching as long as we find the same character<br>    for i &lt; len(line) {<br>     nextRune, nextSize := utf8.DecodeRune(line[i:])<br>     if nextRune != prevRune {<br>      break<br>     }<br>     i += nextSize<br>    }<br>    continue<br>   }<br><br>   if quantifier == &#39;?&#39; {<br><br>    // Case 1: Try skipping the preceding character (zero occurrence)<br>    if matchFromPosition(line[i:], pattern[j:]) {<br>     return true<br>    }<br><br>    // Case 2: Try matching the preceding character (one occurrence)<br>    if lineRune == prevRune {<br>     i += lineSize<br>     continue<br>    }<br><br>    // If neither case matches, return false<br>    return false<br>   }<br>  } else if patternRune == &#39;.&#39; {<br>   // Handle &#39;.&#39; (match any single character)<br>   i += lineSize<br>   j += patternSize<br>   continue<br>  }</pre><h4>Step 6: Check for a literal character match</h4><p>Lastly, if the pattern does not match any of the if-else conditions we check for a literal match between the pattern and line characters.</p><pre>else if patternRune != lineRune {<br>   // Literal character match<br>   return false<br>  }</pre><h3>Conclusion</h3><p>We’ve explored the mechanics behind regular expression engines and their functionality by building a custom pattern matcher in Go. This implementation offers a flexible approach to pattern matching, handling basic literal matches as well as complex alternations and character classes.</p><p>For anyone looking to deepen their understanding of pattern matching using Go’s built-in regexp package, building a tool like this is a great exercise.</p><p>The complete code can be referred to from <a href="https://github.com/Annanya481/Grep-Tool">Grep-Tool</a></p><h3>References</h3><p><a href="https://app.codecrafters.io/courses/grep/introduction">Build Your Own Grep — Codecrafters</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40825fb9c98d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Latency Numbers for Programmers]]></title>
            <link>https://medium.com/@AnnanyaPandey/important-latency-numbers-for-programmers-8a8f92df849d?source=rss-81b96b652c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a8f92df849d</guid>
            <category><![CDATA[memory-systems]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[latency-numbers]]></category>
            <dc:creator><![CDATA[Annanya Pandey]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 07:01:22 GMT</pubDate>
            <atom:updated>2024-09-19T07:01:22.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Understanding and minimizing latency is a concept that programmers should be familiar with as it is a crucial factor in the scalability, responsiveness and efficiency of applications and systems. But first, let’s understand a little about what exactly latency refers to.</p><p>Latency is the delay experienced when data is transmitted between two points, such as across a network or within a system’s memory. Understanding latency numbers is vital because these delays impact the performance of operations like accessing memory, disk, or network resources. By knowing the relative speeds of various components, developers can optimize their code to ensure critical data is accessed from faster storage (like CPU cache) and minimize the use of slower resources (like hard drives or network connections). Optimizing for low-latency operations leads to more efficient, scalable, and responsive systems — especially in fields such as real-time computing, databases, and distributed applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*p0lZc8Mgab54N9Xb_e-lQg.png" /><figcaption>Latency in a network</figcaption></figure><h3>Key Latency Numbers</h3><p>Computer memory systems (L1 cache, RAM, etc.) are structured in a hierarchy to balance performance and cost, where each tier has different latency characteristics. An important component of computer memory systems is the cache. Cache is a temporary storage area that improves performance by allowing quick access to data. Below are important latency numbers programmers should be aware of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*lUy16m1AhK-bcO-J_hkhmg.png" /></figure><h4>L1 Cache Reference</h4><p>L1 cache is the smallest and fastest cache closest to the CPU core. It stores data and instructions that the CPU is likely to reuse. Accessing data from the L1 cache has extremely low latency — typically around 0.5 nanoseconds (ns). This cache is critical for speeding up processing, as it avoids the need to fetch data from slower memory tiers.</p><h4>Branch Mispredict</h4><p>Modern CPUs use branch prediction to anticipate the outcome of conditional statements in code (e.g., if-else blocks). When the CPU guesses wrong (a branch mispredict), it has to throw away incorrect instructions and fetch the correct ones, which introduces a delay of around 5 ns. In performance-critical applications, frequent branch mispredictions can accumulate and significantly slow down execution.</p><h4>L2 Cache Reference</h4><p>L2 cache is larger but slower than L1 cache, storing data that isn’t as frequently used but still important for quick access. A reference to L2 cache typically takes around 7 ns, about 14 times slower than L1. Still, it is much faster than accessing the main memory (RAM), which has a higher latency.</p><h4>Mutex Lock/Unlock</h4><p>A mutex is used in multithreading to ensure only one thread accesses a shared resource at a time, preventing race conditions. However, the locking and unlocking process introduces a delay of approximately 25 ns. In highly concurrent systems, this delay can impact performance, especially when multiple threads frequently compete for the same resources.</p><h4>Main Memory Reference</h4><p>Accessing data from <strong>main memory (RAM)</strong> is significantly slower than from CPU caches. A memory reference takes around 100 ns, which is roughly 200 times slower than accessing L1 cache. Modern systems try to avoid this by caching data in faster memory to reduce the need for costly RAM accesses.</p><h4>Compress 1K Bytes with Zippy</h4><p><strong>Zippy</strong>, also known as <strong>Snappy</strong>, is a fast compression algorithm. Compressing 1 KB of data with Zippy typically takes about 3 microseconds (µs). Although compression can reduce data size for storage or transfer, it introduces some computational overhead that must be taken into account, particularly when speed is critical.</p><h4>Send 1K Bytes over 1 Gbps Network</h4><p>Sending 1 kilobyte of data over a <strong>1 Gbps network</strong> typically incurs a latency of around 10 microseconds (10,000 ns). This latency includes both the time spent transmitting data and the network’s overhead for handling the packet, though this delay can increase with network congestion or distance.</p><h4>Read 4K Randomly from SSD</h4><p>Solid-state drives (SSDs) are known for their speed compared to traditional hard drives. Reading a 4 KB block of data randomly from an SSD takes about 150 microseconds (150,000 ns), due to the time needed to find and fetch the data from the SSD’s storage cells.</p><h4>Read 1 MB Sequentially from Memory</h4><p>Reading 1 MB of data sequentially from RAM takes about 250 microseconds (µs). In this case, sequential means reading the data continuously from adjacent memory locations, which is much faster than randomly accessing data because there’s no need to “jump” to different parts of memory.</p><h4>Disk Seek</h4><p>On a traditional mechanical hard drive, a <strong>disk seek</strong> refers to the time it takes for the read/write head to physically move to the right spot on the disk platter. This is a slow process, taking around 10 milliseconds (ms), or 10,000,000 ns. This operation is considerably slower than SSDs, as it involves mechanical movement.</p><h4>Read 1 MB Sequentially from the Disk</h4><p>Reading 1 MB of data sequentially from a mechanical hard drive takes about 20 milliseconds. This is about 80 times slower than reading the same amount from RAM and around 20 times slower than reading from an SSD. The mechanical nature of hard drives significantly contributes to this delay.</p><h4>Send Packet CA → Netherlands → CA</h4><p>Transmitting a packet of data from California to the Netherlands and back (a round trip across the Atlantic Ocean) introduces a latency of approximately 150 milliseconds. The delay is caused by the physical distance the data must travel, as well as processing delays at each intermediate network node. Network performance is limited by the speed of light and the number of hops the data packet takes along the way.</p><h3>Conclusion</h3><p>Understanding these latency numbers helps programmers design systems that avoid bottlenecks caused by slower operations. By minimizing latency through the effective use of faster memory caches and optimizing network and disk I/O, developers can ensure their applications are more responsive, scalable, and efficient.</p><h3>Reference</h3><ul><li>Peter Norvig: <a href="http://norvig.com/21-days.html#answers">http://norvig.com/21-days.html#answers</a></li><li>Jeff Dean: <a href="https://gist.github.com/jboner/2841832">https://gist.github.com/jboner/2841832</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a8f92df849d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email Spam Detection and Filtering Model]]></title>
            <link>https://medium.com/@AnnanyaPandey/email-spam-detection-and-filtering-model-b2098ea73182?source=rss-81b96b652c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2098ea73182</guid>
            <category><![CDATA[binary-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[spam-detection]]></category>
            <category><![CDATA[spam-filter]]></category>
            <dc:creator><![CDATA[Annanya Pandey]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 16:58:54 GMT</pubDate>
            <atom:updated>2022-07-18T17:01:38.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M7yT7DUcrkBdo4ic" /><figcaption>Photo by <a href="https://unsplash.com/@hostreviews?utm_source=medium&amp;utm_medium=referral">Stephen Phillips - Hostreviews.co.uk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In today’s world, email is a widespread form of official communication most commonly used in almost all sectors. This is owing to the fact that it is fast, cheap, reliable and accessible and can be used to communicate messages to a large group of persons at the click of a button. The most common disadvantage of email as a method of communication is spam. Spam refers to the unsolicited and unwanted junk mail that leads to a plethora of security vulnerabilities including but not limited to phishing attacks, zero-day attacks, etc. Spam accounts for around 92% of a person’s email communication and while not all have malicious intent, they are at the very least quite annoying. To combat the growing nuisance that is spam, email spam filters are used which detect and block spam messages from filling up a person’s inbox thus leaving room for legitimate communication. In the following article, we will look at the creation of one such simple email spam filter using machine learning. Furthermore, we’ll dive into deploying the model using Flask.</p><h3><strong>Workflow</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*pe2lSYqKOO0hCWboaaE3qg.png" /></figure><p>The workflow is this project consists of two major steps:</p><ul><li>Building the machine learning model</li><li>Deploying the model using Flask</li></ul><h4><strong>Building the Model</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*4C1Lbm_heqGLLtIN4Gn1mg.png" /></figure><p><strong>Importing Dependencies</strong></p><p>We’ll start with loading the required dependencies. The libraries used are Pandas, Numpy, Pickle and Sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/851ce0a63babfa74d5718438495cfedb/href">https://medium.com/media/851ce0a63babfa74d5718438495cfedb/href</a></iframe><p><strong>Data Loading and Preprocessing</strong></p><p>The first step of every machine learning project is data preprocessing which is the process of preparing the raw data to make it suitable for the machine learning model since the data found often contains noise. The dataset used here is preprocessed through the following steps:</p><ul><li>Loading the dataset</li></ul><p>The dataset used in this project is from Kaggle and can be found <a href="https://www.kaggle.com/datasets/bagavathypriya/spam-ham-dataset"><strong>here</strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/762f1e60236fa6ad39a4a87d3297a1d3/href">https://medium.com/media/762f1e60236fa6ad39a4a87d3297a1d3/href</a></iframe><ul><li>Label Encoding</li></ul><p>The machine learning model cannot be trained on labels and hence these labels must be converted into a numeric form. This process is called label encoding. In the given dataset, ‘Spam’ emails are labelled as 0 and ‘Ham’ emails or non-spam emails are labelled as 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a850ea1e05aa6671d6dcbf1ebdbb4a/href">https://medium.com/media/85a850ea1e05aa6671d6dcbf1ebdbb4a/href</a></iframe><ul><li>Separating data as text and labels</li></ul><p>The current dataset consists of two columns namely the text or the email messages and labels i.e. the category of the email message (spam or ham). The messages are the input variable (i.e. X) and the labels are the target variable (i.e. Y).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2aa37a689d816020fed5766d767335b/href">https://medium.com/media/b2aa37a689d816020fed5766d767335b/href</a></iframe><p><strong>Splitting the dataset</strong></p><p>The dataset is split into train and test data. Since the given dataset is relatively small, an 80:20 split is performed to provide more data for training the model to improve its accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8510e83e1aac75027ad2c198fc67aadc/href">https://medium.com/media/8510e83e1aac75027ad2c198fc67aadc/href</a></iframe><p><strong>Feature Extraction</strong></p><p>Feature Extraction is the process of transforming textual data into feature vectors to be used as input by the machine learning model. This is performed with the help of a Vectorizer. Vectorization is the process of conversion of text to numeric vectors. Here we use the TfidfVectorizer(). Tfidf stands for term-frequency inverse document-frequency. Term frequency denotes the importance of a specific term in the given data while document frequency indicates how commonly a term occurs. Hence, Tfidf is used to scale down the impact of frequently occurring terms in a given text.</p><p>Here, the parameters passed to the TfidfVectorizer() are:</p><ul><li>min_df which is set to 1 to indicate that words occurring less than once are to be ignored</li><li>stop_words=’english’ indicates that stop_words, which are the English words that do not particularly add meaning to a sentence, can be safely ignored. Some examples of stop_words are ‘is’, ‘the’, ‘and’, ‘are’, etc.</li><li>lowercase=True converts all alphabets to lowercase</li></ul><p>Furthermore, the Y_train and Y_test values which are currently of type ‘object’ are converted to the integer type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a75a5fc614c6edc55d187c3a826728/href">https://medium.com/media/30a75a5fc614c6edc55d187c3a826728/href</a></iframe><p><strong>Training the Model</strong></p><p>The data has been preprocessed and is ready to be passed as input to train the model. Four models are used for this problem namely Logistic Regression, Support Vector Machine, Naive Bayes and Random Forest, and the best performing model is selected to be deployed.</p><ul><li>Logistic Regression</li></ul><p>Logistic Regression is the simplest algorithm to be used for binary classification problems such as this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be60e6058b475058cd1d7a68afb5ab5/href">https://medium.com/media/0be60e6058b475058cd1d7a68afb5ab5/href</a></iframe><p>The accuracy obtained is 0.9632 as observed from the confusion matrix plotted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*sNkMN205DmS2b__i7ycVyg.png" /></figure><ul><li>Support Vector Machine (SVM)</li></ul><p>Support Vector Machine is a supervised learning algorithm that can be used for both classification and regression problems. It works by plotting each data item as a plot in an n-dimensional space (where n is the number of features). Classification is then performed by finding a hyperplane that best differentiates between the two classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254a89b50d6bb9a30f499ad8fc5dbd11/href">https://medium.com/media/254a89b50d6bb9a30f499ad8fc5dbd11/href</a></iframe><p>The accuracy obtained is 0.8609 as observed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*RpJMEgjPO2dgeHwIgHaUMA.png" /></figure><ul><li>Naive Bayes Classifier</li></ul><p>Naive Bayes is a collection of classification algorithms based on the Bayes theorem. The fundamental assumption of the Naive Bayes classifier is that each feature is independent and contributes equally to the outcome. Here we use the MultinomialNB() theorem which is used the guess the tags of textual data and classify it accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06dc6ad7e536525d9fa677efb566c30a/href">https://medium.com/media/06dc6ad7e536525d9fa677efb566c30a/href</a></iframe><p>The accuracy obtained is 0.9704 which is higher than the previous models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*kNxSizsVNm6C9g1TDUCMFw.png" /></figure><ul><li>Random Forest Classifier</li></ul><p>Random Forest is a supervised learning algorithm that utilises an ensemble learning technique where multiple classifiers are combined to improve the performance of the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f3508fa51125c9b487839429ad3bac/href">https://medium.com/media/b0f3508fa51125c9b487839429ad3bac/href</a></iframe><p>The accuracy of the random forest classifier is the best performing out of all the above models with an accuracy of 0.9757.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*_yYE6Ynb8mSlY4fZtALOMg.png" /></figure><p><strong>Saving the Model</strong></p><p>The Random Forest Classifier and the Vectorizer are saved to be deployed as it is the best performing of all the four.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea54bd00c5b31879c8d1b455529de28c/href">https://medium.com/media/ea54bd00c5b31879c8d1b455529de28c/href</a></iframe><h4><strong>Deployment</strong></h4><p>The second step of building the email spam detection classifier is the deployment of the best-performing model using Flask. Flask is a Python-based micro-framework used for deploying small-scale applications.</p><p><strong>Template Creation</strong></p><p>The input required for this application is an email message to be labelled either as spam or ham. To take the input from the user, we require a form with an input field as shown below. This HTML file is stored in a folder named templates which will be rendered using a Flask script. The template used as a reference can be found <a href="https://codepen.io/Anna_Batura/pen/ExKBXdd"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*9Ea59LoL5brAWn-WinEhYg.png" /></figure><p><strong>Flask Script</strong></p><p>The primary Flask script is a function predict() used to render the template created. The model and Vectorizer stored previously are stored in variables and are used to predict the label of the input taken in from the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f4941a8f276a2aa08d48a809f71a49/href">https://medium.com/media/64f4941a8f276a2aa08d48a809f71a49/href</a></iframe><h3>Conclusion</h3><p>In this article, we walked through the creation of a basic email spam filtering application and we found that the Random Forest Classifier was the best-performing model which was deployed using Flask. The source code for the project can be found <a href="https://github.com/Annanya481/Email-Spam-Detection"><strong>here</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2098ea73182" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semi-Supervised Learning]]></title>
            <link>https://medium.com/@AnnanyaPandey/semi-supervised-learning-4b3a4b0f4761?source=rss-81b96b652c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3a4b0f4761</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <dc:creator><![CDATA[Annanya Pandey]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 16:15:19 GMT</pubDate>
            <atom:updated>2022-07-11T16:15:19.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-NjRAODDoaUb9bBS" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine learning is one of the fastest-growing fields in the current technological landscape and it refers to a branch of artificial intelligence that deals with the prediction of outcomes by imitating the way that humans learn and perceive things. When talking about the classification of machine learning, primarily two categories come to mind namely <strong>Supervised Learning and Unsupervised Learning. </strong>In the following article, I’ll be discussing a median path between the two called <strong>Semi-Supervised Learning.</strong></p><h3><strong>Supervised and Unsupervised Learning</strong></h3><p>The primary difference between supervised and unsupervised learning is the type of data used by the algorithms. Supervised learning works on labelled data while unsupervised learning works on grouping or classifying the data based on similarities or differences rather than labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*QzumRuAB-OJqD6QE1myLkg.png" /></figure><p>Take the example of a simple Cat vs Dog Classifier. In the case of supervised learning, the dataset used for training would consist of images of cats and dogs and the model uses these to further classify the input image. In the case of unsupervised learning, no such labelled data is provided. Instead, the model learns by finding similarities between the images and groups them into different categories.</p><p>The advent of Semi-Supervised Learning was brought up to find an intermediate ground between supervised and unsupervised learning. The main drawback of supervised learning is that the dataset must be hand-labelled by data scientists or machine learning specialists in addition to its high processing cost. The main disadvantage of unsupervised learning is its limited applications. To overcome these problems. semi-supervised learning was introduced.</p><h3><strong>What is Semi-Supervised Learning?</strong></h3><p>Semi-Supervised learning refers to algorithms that work on a combination of labelled and unlabelled data, in most cases the unlabelled data is more than the labelled data. The basic working methodology is initially grouping the unlabelled data on the basis of similarities/ differences using unsupervised learning algorithms and then applying labels to classify the rest of the labelled data. The labelled data works towards helping with more accurate classification into different categories while the unlabelled data helps in increasing the volume of data used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*_Qj0ANoi2J9kqQ98s79_NQ.png" /></figure><p>A common example of an application of semi-supervised learning is fraud detection. Suppose you have a dataset with some instances of fraud correctly labelled but there have been instances of fraud slipping unnoticed. Here, semi-supervised learning can be used to build a fraud prediction model without having to spend unnecessary time labelling the unlabelled fraudulent instances.</p><h3><strong>Working</strong></h3><p>Semi-supervised learning seeks to find relations among the data objects through the following assumptions:</p><ol><li><strong>Continuity Assumption: </strong>points closer together fall under the same category or label</li><li><strong>Cluster Assumption:</strong> data are divided into distinct clusters and data points in the same cluster fall under the same label or category</li><li><strong>Manifold Assumption:</strong> allowing the use of distances and densities by assuming that data lie on a <a href="https://en.wikipedia.org/wiki/Manifold">manifold</a> of fewer dimensions than input space</li></ol><p>The working methodology of semi-supervised learning algorithms is as follows:</p><ol><li>First, the labelled data is used for training the model using a supervised learning algorithm until satisfactory results are achieved.</li><li>Next, the unlabelled dataset is used to predict results in the form of pseudo labels.</li><li>The labels from the supervised learning algorithm are linked with the pseudo labels from the unsupervised learning algorithm.</li><li>The inputs from the labelled dataset are linked with the inputs of the unlabelled dataset.</li><li>Finally, the model is trained the same way as with the supervised learning algorithm to obtain higher accuracy and lower error rate.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*6pheqXFJLjU7_KYvM1hGwg.png" /></figure><h3><strong>Applications</strong></h3><ul><li><strong>Speech Recognition: </strong>Semi-supervised learning is used to overcome the time-consuming task of labelling audio samples and enhancing performance.</li><li><strong>Text-Document Classification:</strong> Semi-supervised learning is used for text-document classification to overcome the tedious task of having to read heavily worded texts and assigning an appropriate label.</li><li><strong>Internet Content Classification:</strong> Labelling web pages is impractical and highly time-consuming and hence semi-supervised learning is used to improve performance.</li><li><strong>Protein Sequence Classification:</strong> Owing to the large size of DNA strands, semi-supervised learning has found immense growth in this field.</li></ul><h3><strong>Conclusion</strong></h3><p>In conclusion, semi-supervised learning algorithms have been continuously evolving over the past two decades and are finding increasing applications in today’s world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3a4b0f4761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malware Attacks on IoT Devices]]></title>
            <link>https://medium.com/@AnnanyaPandey/malware-attacks-on-iot-devices-7be780ac7553?source=rss-81b96b652c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be780ac7553</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[iot-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Annanya Pandey]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 10:38:02 GMT</pubDate>
            <atom:updated>2022-07-03T10:38:02.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H-GjzzYokaOx1BEG" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Internet of Things is a vast and ever-growing field referring to the interconnectivity of devices via the internet. They work on sensors and actuators and largely depend on the interchange and processing of large amounts of data. With the advent and increasing usage of IoT devices, there has also been a steadily increasing number of attacks on the same. Recent studies have reported a <strong>70% increase in IoT malware attacks</strong> compared to pre-pandemic accounts. In this article, I’ll discuss some of the recent malware attacks faced and common mitigation steps.</p><h3><strong>What is Malware?</strong></h3><p>Before going into the depth of malware attacks, let’s define what malware is. <strong>Malware is a blanket term used to define any computer software that adversely affects a system.</strong> IoT malware combine common attack techniques such as DDos, passive attacks such as spying or eavesdropping, or brute-force attacks with the functionality of IoT devices to increase the impact of the attack.</p><figure><img alt="Types of malware attacks on IoT Devices" src="https://cdn-images-1.medium.com/max/579/1*wCZZHsVu8-XBVBb_-2WSVQ.png" /></figure><h3><strong>Attack Vectors</strong></h3><p>In order to perform an effective exploit, an attacker first explores all possible attack vectors i.e. all possible vulnerabilities to be found in the target system. Some of the commonly exploited attack vectors of IoT devices are:</p><p><strong>Weak Passwords</strong></p><p>Security is most often found to be given the least priority during the development cycle of a product or software. In the case of IoT devices, manufacturers also take into account the easy setup of devices to make them more user-friendly for non-tech-savvy users. Due to this, most IoT devices come with simple, easy-to-remember default login credentials and passwords that are often left unchanged, making the device an easy target for users. These default credentials are easily accessible to malicious actors since they are most often freely available. A common example of such credentials is admin/admin or user/admin.</p><p><strong>Internet Exposure</strong></p><p>Any device exposed to the internet usually allows all incoming traffic. This can lead to infiltration attacks through services such as SSH, Telnet, FTP, etc. Most IoT devices are particularly susceptible to these attacks due to little or no security.</p><p><strong>Web Interface</strong></p><p>The web interface of IoT devices is vulnerable to all web-based vulnerabilities including but not limited to the <a href="https://owasp.org/www-project-top-ten/">OWASP Top 10</a>.</p><p><strong>Lack of Encryption</strong></p><p>An important part of the working of IoT devices is processing, storing and exchanging user data and trends. These large amounts of data are left exposed due to the lack of data encryption in most IoT devices and are easily accessible by malicious attackers to be used further.</p><h3><strong>Exploitation</strong></h3><p>Attacks on IoT devices usually consist of two phases — scanning and takeover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*PNT4WbBWkoT6JZFapx8DdQ.png" /></figure><p>The scanning phase involves looking for open ports and services on the host which exist due to the constraint of internet connectivity. The attacker can connect several such vulnerable devices to form a botnet. A botnet refers to a set of devices that are remotely controlled by malicious attackers with the help of infected malware. A botnet is more powerful than a single malicious IoT device. Once formed, the attacker carries out the actual attack most commonly by performing DDoS (Distributed Denial of Service) which is an attack designed to cripple a target by bombarding it with traffic.</p><h3>Impact</h3><p>The impacts of malware attacks on IoT devices have been far-reaching. They are often used for disruption of services, launch phishing campaigns, theft of user data and confidential information and in recent years cryptojacking (malware attacks that target computing resources for the purpose of crypto mining).</p><p><strong>Mirai</strong></p><p>The most common example of a botnet attack is the Mirai malware which was a DDoS attack that rendered the internet inaccessible to much of the US east coast. It works by performing a scan to look for open telnet ports (port 23) and using weak password vectors as a method of exploitation for the same. The Mirai malware remains dangerous to date due to its continuously evolving nature.</p><p><strong>BotenaGo</strong></p><p>BotenaGo is an autonomous malware written in Golang i.e. one that does not require human intervention once released. Detected in October 2021, it is known to have over 30 exploit mechanisms. It seeks out and attacks vulnerable targets without human intervention by creating two backdoors on ports 31412 and 19412. It uses the latter for listening and performs a series of looped exploits once a connection has been established.</p><p><strong>TimpDoor</strong></p><p>TimpDoor is malware that creates backdoors on infected devices. The network of infected devices is further used for sending spam/ phishing emails or other profitable purposes. It is specific to Android devices and tricks users into installing a fake voice-message app. Upon installation of the fake app, a Socks proxy is set up in the background that redirects all traffic through an encrypted tunnel to the malicious third party thus bypassing security mechanisms such as firewalls and giving internal network access to malicious actors.</p><h3><strong>Mitigation</strong></h3><p><strong>Regular Updation of Systems and Software</strong></p><p>Security is a constantly evolving field and patches are regularly released for systems and software pertaining to the mitigation of various vulnerabilities. It is thus important to regularly install updates as and when they are released in order to minimize the vulnerability of the system.</p><p><strong>Choose Strong Passwords</strong></p><p>It is crucial to change the default login credentials and passwords and use passwords that are secure and harder to crack. Some common points to keep in mind while deciding upon a password are</p><ul><li>The ideal length of passwords should be 8–15 characters</li><li>Use a combination of uppercase and lowercase alphabets</li><li>Ensure the use of at least one special character</li><li>It is best to randomize the combination of characters rather than use meaningful words</li></ul><p><strong>Avoid Connecting to Public Wifi</strong></p><p>Try not to connect your devices to public Wifi as they tend to have minimal to no security measures or use a VPN.</p><p><strong>Set Up Firewall Rules</strong></p><p>Firewall Rules allow the user to block or allow network traffic from a certain source. Most devices come with an inbuilt firewall but additional rules can add extra layers of security.</p><p><strong>Use of Encryption</strong></p><p>Unencrypted traffic makes it easy for hackers to eavesdrop on communication and gain access to confidential data. VPNs are highly recommended for this purpose as they allow an encrypted channel for communication between the device and the VPN server.</p><p><strong>Disconnect when not in use</strong></p><p>Disconnect IoT devices from the internet when not in use to avoid unwanted access.</p><p><strong>Disable UPnP support</strong></p><p>UPnP stands for Universal Plug and Play and it allows your device to be discoverable on the internet thus making it more susceptible to possible attacks by malicious actors.</p><h3><strong>Conclusion</strong></h3><p>To conclude, in today’s digital era we need to increase awareness of the vulnerabilities our devices possess and I hope this article helped bring you a step further in this direction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be780ac7553" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>