<?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 gopi sumanth on Medium]]></title>
        <description><![CDATA[Stories by gopi sumanth on Medium]]></description>
        <link>https://medium.com/@bgsumanth8?source=rss-24975abceeb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Ja1BosZsAA5XAMRgZpT0cw.jpeg</url>
            <title>Stories by gopi sumanth on Medium</title>
            <link>https://medium.com/@bgsumanth8?source=rss-24975abceeb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:30:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bgsumanth8/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[Unraveling the Mystery of Large Language Models: A Peek Behind the Curtain]]></title>
            <link>https://medium.com/@bgsumanth8/unraveling-the-mystery-of-large-language-models-a-peek-behind-the-curtain-80fff23bb68c?source=rss-24975abceeb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/80fff23bb68c</guid>
            <category><![CDATA[supervised-fine-tuning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[gopi sumanth]]></dc:creator>
            <pubDate>Sat, 17 May 2025 09:06:05 GMT</pubDate>
            <atom:updated>2025-05-17T09:12:19.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VN44DXibqd6Luy9LBa-fTA.png" /><figcaption>The Luminous Lattice of Language Learning.</figcaption></figure><p>Large Language Models (LLMs) have revolutionized how we interact with technology, powering the chatbots we’ve all heard about, like <strong>ChatGPT</strong>, <strong>Claude</strong>, and <strong>Gemini</strong>. But how do these complex digital brains actually come to life? It’s a journey that involves far more than just neural networks; it’s about massive amounts of data, careful training, rigorous evaluation, and overcoming significant computational hurdles.</p><p>While the core architecture — <strong>the Transformer</strong> — is famous (and readily available online), the real magic and the focus of practical development lie in other crucial components: the training loss and algorithm, the data used for training, the methods for evaluation, and the underlying systems that make it all possible at scale.</p><p>The process can be broadly divided into two main acts: <strong>Pre-training</strong>, where the model learns the fundamental structure and patterns of human language by reading the vast internet, and <strong>Post-training</strong> (or Alignment), where it’s refined to become a helpful and safe AI assistant. Let’s dive into this journey.</p><h3>Act 1: Teaching the Model to “Read” the Internet — Pre-training</h3><p>At its heart, pre-training teaches a language model to understand and model the probability distribution of sequences of words or tokens. Imagine feeding it countless sentences, and its task is to learn the likelihood of seeing a particular sequence, like “the mouse ate the cheese” (high likelihood) versus “the cheese ate the mouse” (low likelihood, reflecting semantic knowledge).</p><p>The most common approach is using <strong>Auto-regressive Language Models</strong>. This breaks down the complex task of understanding a whole sentence into a series of simpler predictions: what is the probability of the second word given the first, the third given the first two, and so on. In essence, the model becomes an expert at predicting the **next word or token** based on the context that came before it.</p><p>This prediction task is framed as a classic machine learning problem. Given a sequence of tokens, the model outputs a probability distribution over the <strong>entire vocabulary</strong> of possible next tokens. The model is then trained using a <strong>cross-entropy loss</strong>. This loss function simply pushes the model to increase the probability of generating the <strong>actual</strong> next token that appeared in the training data and decrease the probability for all other tokens. Minimizing this loss is mathematically equivalent to maximizing the likelihood of the training text occurring, which is the core objective of pre-training.</p><h3>The Crucial Role of Tokenization</h3><p>Before any words can be fed into the model, they must be converted into a numerical format the computer can understand. This is done through <strong>tokenization</strong>. While it might seem simple, tokenization is extremely important.</p><p>Why not just use individual words? Because of issues like typos (an unseen word would have no representation) and handling languages that don’t use spaces between words. Why not just use individual characters? Because that would make sequences incredibly long, which is computationally expensive for Transformer models whose complexity grows <strong>quadratically with sequence length</strong>.</p><p>Tokenizers find a middle ground by identifying common sequences of characters and treating them as single units, or tokens. A popular algorithm is <strong>Byte Pair Encoding (BPE)</strong>, which iteratively merges the most frequent adjacent pairs of characters or tokens in a large text corpus. This process creates a vocabulary of tokens, where each token gets a unique ID. The output layer of the language model then predicts the next token from this specific vocabulary.</p><p>While effective, tokenizers aren’t perfect and can introduce quirks, especially with numbers or code formatting, which is why some researchers hope future architectures might move away from them.</p><h3>The Raw Material: Data</h3><p>Training LLMs requires truly colossal amounts of text data. The common refrain is training on “all of internet,” but the reality is far more complex. The internet is messy, containing everything from high-quality articles to boilerplate text, harmful content, and vast duplication.</p><p>Raw data from sources like Common Crawl (around 250 billion pages and a petabyte of data) needs extensive processing. This involves multiple steps:</p><ul><li>Extracting text from web pages, handling complex formats like math.</li><li>Filtering undesirable content, including harmful material and personal information (PII), often using large blacklists or classifiers.</li><li>Deduplication to remove repetitive headers, footers, or identical articles found on multiple URLs.</li><li>Heuristic filtering using rules to remove low-quality documents based on token distribution, word length, or document length.</li><li>Model-based filtering, training a classifier to identify high-quality documents, perhaps by learning characteristics of text linked from reputable sources like Wikipedia.</li><li>Domain classification and weighting to categorize data (e.g., code, books, entertainment) and then strategically emphasize certain domains (like code or books, which have been found to improve reasoning) while downweighing others.</li><li>Training on extremely high-quality data like Wikipedia at the very end, almost “overfitting” the model on pristine text as the learning rate decreases.</li></ul><p>Collecting and cleaning this data is a monumental task, arguably one of the most critical and challenging aspects of building LLMs in practice. It’s also an area where companies are often secretive due to competitive advantages and copyright concerns. The scale of training data has grown dramatically, with current cutting-edge models being trained on datasets reaching up to <strong>15 trillion tokens</strong>.</p><h3>The Predictable Climb: Scaling Laws</h3><p>A surprising discovery made around 2020[<a href="https://arxiv.org/pdf/2001.08361">1</a>] is that, unlike smaller models where overfitting is a concern, for large language models, <strong>more data and larger models consistently lead to better performance</strong>. This is a fundamental shift in thinking for the field.</p><p>Even more remarkably, the improvement in performance (measured by test loss, related to perplexity) is predictable. On a log-log scale, the relationship between the amount of compute used (a function of model size and data size) and the test loss is surprisingly linear. These are known as scaling laws.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ytEldQvGHFvAwet-zb8qA.png" /><figcaption>Scaling Laws for Neural Language Models</figcaption></figure><p>Scaling laws have fundamentally changed how large model training is planned. Instead of tuning hyperparameters on the final, massive model (which would be prohibitively slow), researchers train many smaller models across different scales. By fitting scaling laws to the performance of these smaller models, they can accurately <strong>extrapolate</strong> how a much larger model will perform and determine the optimal hyperparameters and resource allocation (how many parameters vs. how much data) for the final, massive training run.</p><p>The Chinchilla paper[<a href="https://arxiv.org/abs/2203.15556">2</a>] famously suggested an optimal ratio of 20 tokens per parameter for minimizing training loss. However, considering the significant cost of inference (running the model after training), a more common practical ratio is around <strong>150 tokens per parameter</strong>, favoring slightly smaller models that are cheaper to deploy repeatedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5adkNILPEEBuAwgF1ynIQ.png" /><figcaption>Training Compute-Optimal Large Language Models</figcaption></figure><p>Scaling laws also reveal that minor architectural tweaks matter less than the fundamental ability of the architecture (like the Transformer) to leverage computation, along with the quality and quantity of data and the efficiency of the underlying systems.</p><h3>The Price Tag</h3><p>Training these models is incredibly expensive. Using the LLaMA 3 400B model as an example (405 billion parameters, trained on 15.6 trillion tokens), the estimated computational cost is around <strong>3.8e25 flops</strong>. This required using 16,000 H100 GPUs for about 70 days, totaling an estimated <strong>26 to 30 million GPU hour</strong>s.</p><p>Calculating the cost based on renting H100s at a lower bound of $2 per hour puts the GPU cost alone at over $50 million. Including salaries for the large team involved, the total cost for training a single state-of-the-art open-source model can easily exceed <strong>$75 million</strong>. While carbon emissions are present, they are currently less significant in the “grand scheme of things” compared to, say, air travel, though this could change as models continue to grow exponentially (targeting 10x flops increase per generation).</p><h3>The Silent Partner: Systems</h3><p>All this computation is only possible because of advanced computing <strong>systems</strong>, particularly the use of powerful GPUs. GPUs are designed for high throughput and parallelization, optimized for the massive matrix multiplications inherent in neural networks.</p><p>However, compute power has been improving faster than the ability to efficiently move data to and from the GPU memory. This means GPUs can often be idle if the data pipeline isn’t optimized. Achieving even 50% Model Flop Utilization (MFU) — the ratio of observed throughput to theoretical maximum — is considered very good.</p><p>Engineers employ clever tricks to maximize GPU utilization. One common technique is <strong>Low Precision trainin</strong>g. Instead of using 32-bit floating-point numbers for calculations, they use 16-bit floats. This halves the amount of data that needs to be moved and stored, speeding up computation and reducing memory footprint. While weights are often stored in 32 bits to preserve precision during updates, the heavy matrix multiplications are done in 16 bits. Another trick is <strong>Operator Fusion</strong>. Standard code might perform operations step-by-step, requiring data to be moved back and forth from GPU memory for each step. Fusion combines multiple operations into a single sequence that is sent to the GPU processor, reducing redundant memory trips.</p><h3>Act 2: Becoming a Helpful Assistant — Post-training (Alignment)</h3><p>A model purely trained on internet text (like GPT-3) is great at predicting the next word, but not necessarily at being a helpful assistant. If you asked it to explain the moon landing to a six-year-old, it might just predict *another* question it saw frequently online. The goal of post-training or **alignment** is to make LLMs reliably follow user instructions and align with desired behaviors, including avoiding harmful content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoJ8czZCU0E4eBffib5mQQ.png" /><figcaption>GPT-3 Completion Model</figcaption></figure><h3>The First Step: Supervised Fine-Tuning (SFT)</h3><p>The initial and simplest post-training step is <strong>Supervised Fine-Tuning (SFT)</strong>. This involves taking the massive pre-trained model and training it further, but this time, on a relatively small dataset of high-quality examples of instructions and the *desired* outputs written by humans. It’s called supervised fine-tuning because it still uses the same <strong>language modeling loss</strong> as pre-training (predicting the next token of the desired human answer).</p><p>SFT was key to the leap from models like GPT-3 to ChatGPT[<a href="https://arxiv.org/pdf/2203.02155">3</a>]. However, collecting high-quality instruction-response pairs from humans is <strong>slow and expensive</strong>.</p><p>This led to the idea of using LLMs themselves to generate synthetic training data. Projects like <strong>Alpaca</strong> demonstrated that a smaller model could be fine-tuned on synthetic data generated by a larger, more capable LLM, achieving impressive results. While generating synthetic data is faster and cheaper, there are concerns about whether the model can truly learn anything *new* if it’s just learning from itself across generations. Future approaches might involve humans in the loop, editing LLM-generated text.</p><p>Interestingly, SFT doesn’t seem to require a massive amount of data; performance gains plateau quickly after just a few thousand examples. The intuition is that the pre-trained model already “knows” how to generate different types of text found online (like answers to questions); SFT simply teaches it which “style” or “persona” (the helpful assistant) to prioritize.</p><h3>Refining Behavior: RLHF and DPO</h3><p>While SFT is powerful, it’s essentially just <strong>behavioral cloning</strong> — trying to imitate the human-written responses. This has limitations: it’s capped by human writing ability, it’s still expensive to get human examples, and some hypothesize it might even contribute to <strong>hallucinations</strong> if the human examples contain information the model didn’t truly learn during pre-training.</p><p>This is where <strong>Reinforcement Learning from Human Feedback (RLHF)</strong> comes in. Instead of simply cloning behavior, RLHF aims to <strong>maximize human preference</strong>. The core idea is to collect data not on what the *perfect* response is, but on which of two generated responses a human *prefers*.</p><p>The RLHF pipeline involves:</p><ol><li>Generating multiple responses for a given instruction.</li><li>Having humans compare and rank or choose the best response.</li><li>Using this human preference data to train a Reward Model. This is a separate model that takes an input and a generated response and outputs a score indicating how highly a human would likely rate that response.</li><li>Using a Reinforcement Learning algorithm (like PPO: Proximal Policy Optimization) to fine-tune the language model. The model becomes an RL agent (a “policy”) that learns to generate responses that maximize the reward score given by the reward model. Regularization is crucial to prevent the model from drifting too far from the original pre-trained behavior.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Q5wSaI0GGIX5JBW9N3U8jQ.png" /><figcaption>InstructGPT</figcaption></figure><p>PPO was the technique used for the original ChatGPT breakthrough and is very effective. However, PPO is notorious for being <strong>complex and unstable</strong> to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyHVGxzeRaeU-7lkHOaTbA.png" /><figcaption>DPO replaces the RL. It is simplier and easier than PPO</figcaption></figure><p>This complexity led to the development of <strong>Direct Preference Optimization (DPO)</strong>[<a href="https://arxiv.org/pdf/2305.18290">4</a>]. DPO is a much simpler algorithm that achieves the same goal as RLHF but without needing a separate reward model or a complex RL training loop. It directly optimizes the language model’s policy by formulating a single loss function that encourages the model to increase the likelihood of preferred responses and decrease the likelihood of disfavored ones, based on the human preference data. DPO has become the standard in the open-source community and likely much of the industry due to its simplicity and comparable performance to PPO.</p><p>Similar to SFT data collection challenges, getting human preference data for RLHF/DPO is also slow, expensive, and complex. Humans can be biased by factors like response length, and the ethics of crowdsourcing labeling on potentially toxic data are a concern. Again, using LLMs to generate and label preference data has emerged as a solution, being significantly cheaper and faster, and surprisingly achieving high agreement with the *mode* of human preferences.</p><h3>How Do We Know If It’s Good? Evaluation</h3><p>Evaluating these powerful, open-ended models is incredibly challenging. Standard metrics used in pre-training don’t work:</p><ul><li>Validation loss is not comparable between models trained with different post-training methods like PPO or DPO.</li><li>Perplexity is meaningless because models trained with RLHF/DPO are optimized to be policies that generate preferred outputs, not accurate probability distributions of all possible human text.</li></ul><p>Given the diversity and open-ended nature of the tasks users ask LLMs to perform (question answering, summarization, creative writing, etc.), the most reliable evaluation method is <strong>human assessment</strong>. This involves showing human annotators the output of two different models for the same prompt and asking them to judge which one is better. Platforms like <strong>Chatbot Arena</strong> collect crowd-sourced human preferences, providing valuable rankings of models.</p><p>However, human evaluation is slow and expensive, making it difficult to use rapidly during the development cycle. This has spurred the development of <strong>LLM-based evaluation</strong>, where a powerful LLM is used as the judge to compare the outputs of two other models. Benchmarks like <strong>AlpacaEval</strong> showed high correlation with human judgments while being dramatically faster and cheaper.</p><p>Despite the promise, LLM evaluators have their own biases, such as preferring longer outputs or being sensitive to minor changes in prompting. Researchers are developing statistical methods to mitigate these biases.</p><h3>The Journey Continues</h3><p>Building large language models is a complex, multi-faceted endeavor. It begins with teaching the model the probabilistic landscape of language through massive pre-training on carefully processed data, guided by scaling laws to manage computational resources. It then involves refining this raw ability into a helpful and safe AI assistant through post-training techniques like SFT and DPO, leveraging human preferences (either directly or mediated by other LLMs). All of this is underpinned by sophisticated systems engineering to maximize the use of scarce and expensive hardware.</p><p>From predicting the next token to engaging in nuanced conversation, the journey of building LLMs is an ongoing epic of data wrangling, algorithmic innovation, and computational optimization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80fff23bb68c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing NLP Models: How Checklist Reveals Critical Bugs in State-of-the-Art Systems]]></title>
            <link>https://medium.com/@bgsumanth8/testing-nlp-models-how-checklist-reveals-critical-bugs-in-state-of-the-art-systems-d407078d90a9?source=rss-24975abceeb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d407078d90a9</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[gopi sumanth]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 05:39:57 GMT</pubDate>
            <atom:updated>2025-04-15T05:48:52.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66aQmS2abM5LqQ_Piuo8LQ.jpeg" /></figure><p>Microsoft Research’s Marco Tulio Ribeiro unveiled a powerful new approach to testing natural language processing (NLP) models. His work on “<a href="https://github.com/marcotcr/checklist">Checklist</a>,” which earned the best paper award at ACL 2020, addresses a critical question in machine learning: <strong>How do we know if our models actually work in the real world?</strong></p><h3>The Problem: Benchmarks Don’t Equal Real-World Performance</h3><p>Despite impressive accuracy scores on standard benchmarks, NLP models often fail in surprising ways when deployed in production environments. As Ribeiro explained, “The gap between being super good on a benchmark and actually working is so large.” This disconnect poses serious risks for organizations implementing these technologies.</p><p>Traditional evaluation methods like cross-validation and test sets have well-documented limitations. Models can achieve high accuracy while relying on shortcuts that don’t generalize to real-world scenarios. While researchers often publish in-depth analysis papers examining model behavior, this approach is too time-consuming for most practical applications.</p><h3>Checklist: Bringing Software Testing Principles to NLP</h3><p>Checklist applies established software engineering testing principles to NLP models. Instead of treating models as black boxes evaluated only by overall accuracy, Checklist encourages testing specific linguistic capabilities through targeted test cases.</p><p>“We should test NLP models just like we test software,” Ribeiro emphasized. “No one would bat an eye if you say ‘I want to unit test whatever system we’re writing.’ I don’t know why people don’t do the same for NLP or machine learning.”</p><h3>The Testing Matrix: Capabilities × Test Types</h3><p>Checklist introduces a structured approach using a matrix with two dimensions:</p><ol><li><strong>Linguistic Capabilities</strong>: What specific language features should your model handle?</li><li>Vocabulary</li><li>Named Entities</li><li>Negation</li><li>Semantic Role Labeling</li><li>Temporal awareness</li><li>Coreference and many more</li></ol><p><strong>Test Types</strong>: How should these capabilities be tested?</p><ul><li><strong>Minimum Functionality Tests (MFTs)</strong>: Simple examples that any competent model should handle correctly</li><li><strong>Invariance Tests</strong>: Perturbations that shouldn’t change the model’s prediction</li><li><strong>Directional Expectation Tests</strong>: Perturbations that should change predictions in specific ways</li></ul><h3>Testing Tools for Increased Coverage</h3><p>To facilitate extensive testing, Checklist provides several tools:</p><ul><li><strong>Templating with RoBERTa suggestions</strong>: Automatically generate variations of test cases</li><li><strong>Lexicons</strong>: Pre-built lists of names, locations, and other entities in multiple languages</li><li><strong>Perturbation libraries</strong>: Ready-made functions to modify text systematically</li><li><strong>Visualizations</strong>: Clear interfaces to analyze test results</li></ul><h3>Surprising Failures in Leading Models</h3><p>When applied to state-of-the-art NLP systems (including commercial APIs from Google, Amazon, and Microsoft), Checklist revealed alarming failures in seemingly basic scenarios:</p><h3>Sentiment Analysis Models</h3><ul><li><strong>Negation</strong>: Google’s API failed 54% of the time on simple negations like “The cabin crew was not good”</li><li><strong>Temporal awareness</strong>: 40% failure rate on examples like “I used to hate this airline, now I like it”</li><li><strong>Robustness</strong>: Adding random URLs or @ symbols changed predictions 25% of the time</li></ul><h3>Question Pair Detection (QQP)</h3><p>Despite claims of “superhuman performance,” BERT and RoBERTa models:</p><ul><li>Failed to recognize that “Is Patrick Thomas a teacher?” and “Is Patrick Thomas an accredited teacher?” are different questions (78% failure rate)</li><li>Incorrectly identified questions as duplicates simply because they contained the same named entities (33% failure rate)</li><li>Couldn’t handle semantic role switches like “Does Anna love Benjamin?” vs. “Does Benjamin love Anna?” (65–98% failure rate)</li></ul><h3>Question Answering (SQuAD)</h3><p>BERT, another model touted for superhuman performance, showed:</p><ul><li>82% failure rate on basic property questions like identifying the size of an object from context</li><li>100% failure rate on simple antonym questions</li><li>83% failure rate on temporal questions (before/after relationships)</li><li>67% failure rate on basic negation questions</li><li>Concerning bias patterns in gender-related questions</li></ul><h3>Real-World Impact: Finding and Fixing Bugs</h3><p>Checklist isn’t just an academic exercise. When Microsoft’s sentiment analysis team spent five hours using the tool, they discovered numerous previously unknown issues in their production model — despite it being extensively tested through traditional methods.</p><p>In a controlled user study, participants with Checklist:</p><ul><li>Created more tests in less time</li><li>Generated more test cases per capability</li><li>Found almost three times as many serious bugs compared to unaided testers</li></ul><h3>Adoption and Future Directions</h3><p>Initially met with skepticism (“This won’t work for our model”), teams quickly change their minds once they see Checklist uncovering critical bugs in their systems. Ribeiro noted that he’s successfully applied the approach to various domains beyond those in the original paper, including language modeling and translation.</p><p>The tool continues to evolve with:</p><ul><li>Multilingual support</li><li>Improved guidance for non-NLP experts</li><li>More pre-built test templates</li></ul><h3>Conclusion: A Call for Better Testing</h3><p>Ribeiro’s work represents a paradigm shift in how we evaluate NLP models. By focusing on specific capabilities rather than aggregate metrics, Checklist provides actionable insights about model weaknesses before deployment.</p><p>“I haven’t found a model yet that passes all the tests,” Ribeiro admitted. This sobering reality underscores the importance of thorough testing, especially as NLP systems play increasingly critical roles in real-world applications.</p><p>As the field moves forward, methodologies like Checklist will be essential for bridging the gap between benchmark performance and real-world reliability. The message is clear: before deploying a model in production, we need to verify not just that it performs well on benchmarks, but that it actually works as expected across a diverse range of realistic scenarios.</p><p><em>For more information, visit the </em><a href="https://github.com/marcotcr/checklist"><em>Checklist GitHub repository</em></a><em> to access the open-source tool and test suites described in this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d407078d90a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is machine learning?]]></title>
            <link>https://medium.com/thecyphy/what-is-machine-learning-ba7dc77575eb?source=rss-24975abceeb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba7dc77575eb</guid>
            <category><![CDATA[regression-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <dc:creator><![CDATA[gopi sumanth]]></dc:creator>
            <pubDate>Fri, 08 May 2020 17:44:10 GMT</pubDate>
            <atom:updated>2020-05-08T17:44:10.868Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of us are very much aware of the demand for ML across industries. This has brought a unique change in the recruitment of candidates. An ML aspirant must be well versed with the basics of linear algebra, probability and statistics, optimization theory, and many more. This leaves a unique opportunity for aspirants from various fields to have equal opportunities to compete for jobs in industry irrespective of their background. However, we find people from different backgrounds approaching distinctively for the same set of problems. In this blog, I try to elaborate on the “learning process” in ML which is core and universal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UUqw3E_ZYYS55vN3Fojlpg.gif" /><figcaption>Photo from <a href="https://recro.io/blog/history-of-machine-learning/machine-learning-gif-min/">recro</a></figcaption></figure><p>Machine Learning is defined in many ways from different people from different backgrounds. The essence of machine learning can be pinned down to three main parts:</p><ol><li>We have the dataset.</li><li>A pattern must exist in the dataset.</li><li>We cannot pin down the pattern existing in the dataset mathematically.</li></ol><h3>Dataset</h3><p>ML can be applied to the problems of core engineering disciplines, pure and applied sciences, and many fields of computer science like computer vision, NLP, robotics, and bioinformatics, etc. However, fundamentally we need datasets to apply ML. Because data is the core of any learning process.</p><h3>Pattern and its aesthetics</h3><p>The second most important thing to apply ML is there must be a pattern within the dataset. Be it prediction or clustering or forecasting we need to create models, that can learn that pattern. Also, it is highly advisable to have a pattern that cannot be pinned down mathematically because if we want to kill a scourge of mosquitoes it is not optimal to kill them with a bomb when a simply poisonous gas can do it.</p><p>Let us clearly understand this with the help of some examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*2SxQtl-a17_3zn4iG5mToQ.png" /><figcaption>the plot of cost function 2*sin(x²)+sqrt(5*x)</figcaption></figure><p>The above plot is a complex function that can be modeled by advanced ML models. Unlike simple functions like log(X) that can be modeled using simple mathematical and statistical models ML models can model both simple and complex functions.</p><p>Let’s look at another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*vrdfzlI-5E-R8HIQ.jpg" /><figcaption>Source: <a href="https://www.nasa.gov/centers/ames/research/technology-onepagers/evolvable_systems.html">NASA</a></figcaption></figure><p>In radio communications, an evolved antenna is an antenna designed fully or substantially by an automatic computer design program that uses an evolutionary algorithm that mimics Darwinian evolution. This procedure has been used in recent years to design a few antennas for mission-critical applications involving stringent, conflicting, or unusual design requirements, such as unusual radiation patterns, for which none of the many existing antenna types are adequate.[1] If we closely observe the antenna, we can infer that these kinds of design making it highly impossible for humans to imagine.</p><p><strong>References:</strong></p><ol><li><a href="https://en.wikipedia.org/wiki/Evolved_antenna">https://en.wikipedia.org/wiki/Evolved_antenna</a></li><li><a href="http://www.amlbook.com/">http://www.amlbook.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7dc77575eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecyphy/what-is-machine-learning-ba7dc77575eb">What is machine learning?</a> was originally published in <a href="https://medium.com/thecyphy">TheCyPhy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Illustrative Example of Principal Component Analysis(PCA) vs Linear Discriminant Analysis(LDA): Is…]]></title>
            <link>https://medium.com/analytics-vidhya/illustrative-example-of-principal-component-analysis-pca-vs-linear-discriminant-analysis-lda-is-105c431e8907?source=rss-24975abceeb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/105c431e8907</guid>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[lda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apc]]></category>
            <dc:creator><![CDATA[gopi sumanth]]></dc:creator>
            <pubDate>Wed, 11 Dec 2019 12:22:12 GMT</pubDate>
            <atom:updated>2021-02-19T05:08:51.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>Illustrative Example of Principal Component Analysis(PCA) vs Linear Discriminant Analysis(LDA): Is PCA good guy or bad guy ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXQ5sgMF0XmiY4Jc6gJVwA.png" /><figcaption>source: <a href="https://sebastianraschka.com/Articles/2014_python_lda.html">sebastian</a></figcaption></figure><p>Hi, in this post I am gonna explain how dimensionality reduction techniques affect the prediction model. Here we are using Iris dataset and K-NN classifier. We are going to compare PCA and LDA on Iris dataset.</p><p>Before jumping into the experiments, It would be better to brush up the concepts of PCA and LDA. So I will try to explain them in short notes. Lets us start with PCA.</p><h3><strong>Principal component analysis (PCA)</strong></h3><p>PCA is a statistical tool often used for dimensionality reduction. It helps to convert higher dimensional data to lower dimensions before applying any ML model. It is an unsupervised learning Algorithm. Let me start by explaining with an example of what PCA does. In the below image we see an object from the top, bottom and side views. Note that, an object can have 360 views. If this mug(object) is the data then PCA helps us to find the views(directions) where the largest portion of the cup is seen. For example, if there are only side and bottom views, PCA gives us a side view because a large area of tea is visible. Here the side view is considered as the first principal component. After getting the first principal component, we rotate the cup in directions <strong>perpendicular </strong>to the first principal component. The direction that covers the largest portion and perpendicular to the first principal component is called the second principal component. We can find third, fourth and so on in this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FLxOv5OdAg5L0dYZ_gQ36Q.jpeg" /><figcaption>Image 1: Different views of an object (source: google search)</figcaption></figure><h4>Steps to perform PCA:</h4><p>Normalize the data and find the co variance matrix. Then find the eigen vectors and respective eigenvalues. The first principal component is nothing but the eigen vector with the largest eigenvalue and so on.</p><h3>Linear Discriminant Analysis(LDA):</h3><p>LDA is a supervised dimensionality reduction technique. It makes assumptions on data. It is the generalization of Fischer’s Linear Discriminant. The LDA doesn&#39;t find the principal components. Instead, it increases the inter-class distance and decreases the intraclass distance. A detailed explanation about LDA can be found <a href="http://www.sci.utah.edu/~shireen/pdfs/tutorials/Elhabian_LDA09.pdf">here</a>.</p><h4>Load necessary libraries</h4><pre>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from tqdm import tqdm<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>import seaborn as sn<br>from sklearn.metrics.pairwise import euclidean_distances<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><h4><strong>Load the IRIS data and perform standardization</strong></h4><pre>dataset = pd.read_csv(&#39;iris.csv&#39;) #read the data into dataframe<br>X = dataset.iloc[:, :-1].values   #store the dependent features in X<br>y = dataset.iloc[:, 4].values   #store the independent variable in y<br>X = StandardScaler().fit_transform(X)</pre><h4><strong>Perform PCA and visualize the data</strong></h4><pre># initializing the pca<br>from sklearn import decomposition<br>pca = decomposition.PCA()</pre><pre># configuring the parameteres<br># the number of components = 2<br># we have taken only 2 components as it is easy to visualize<br>pca.n_components = 2<br># pca_reduced will contain the 2-d projects of simple data<br>pca_data = pca.fit_transform(X)<br>print(&quot;shape of pca_reduced.shape = &quot;, pca_data.shape)</pre><pre>#&gt;&gt;&gt;   shape of pca_reduced.shape =  (150, 2)</pre><pre># attaching the label for each 2-d data point<br>pca_data = np.vstack((pca_data.T, y)).T</pre><pre># creating a new data from which help us in ploting the result data<br>pca_df = pd.DataFrame(data=pca_data, columns=(&quot;1st_principal&quot;, &quot;2nd_principal&quot;, &quot;label&quot;))</pre><pre>sn.FacetGrid(pca_df, hue=&quot;label&quot;, size=4).map(plt.scatter, &#39;1st_principal&#39;, &#39;2nd_principal&#39;).add_legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*WuAwcwsB_fI9toSu5hkfEA.png" /><figcaption>PCA for Visualizing IRIS data using two priciple components</figcaption></figure><h4><strong>Plot number of principle components vs cumulative maximum variance explained</strong></h4><pre># PCA for dimensionality redcution (not-visualization)<br>pca.n_components = 4<br>pca_data = pca.fit_transform(X)</pre><pre>percentage_var_explained = pca.explained_variance_ / np.sum(pca.explained_variance_)</pre><pre>cum_var_explained = np.cumsum(percentage_var_explained)</pre><pre># Plot the PCA spectrum<br>plt.figure(1, figsize=(6, 4))<br>plt.xticks(np.arange(0, 4, step=1),(1,2,3,4))<br>plt.plot(cum_var_explained, linewidth=2)<br>plt.axis(&#39;tight&#39;)<br>plt.grid()<br>plt.xlabel(&#39;n_components&#39;)<br>plt.ylabel(&#39;Cumulative_explained_variance&#39;)<br>plt.show()</pre><p>If we take 1-dimensions, approx. 72% of variance is explained and if we take 2-dimensions, approx. 95% of variance is explained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*_Ltue020GvQk-CuI8LkRmA.png" /><figcaption>plot depicting the variance explained by features</figcaption></figure><h4>Perform LDA and visualize the data</h4><pre>from sklearn.discriminant_analysis import LinearDiscriminantAnalysis<br>lda = LinearDiscriminantAnalysis(n_components=2)<br>lda_data = lda.fit(X, y).transform(X)</pre><pre># attaching the label for each 2-d data point<br>lda_data = np.vstack((lda_data.T, y)).T</pre><pre># creating a new data fram which help us in ploting the result data<br>lda_df = pd.DataFrame(data=lda_data, columns=(&quot;1st_principal&quot;, &quot;2nd_principal&quot;, &quot;label&quot;))</pre><pre>sn.FacetGrid(lda_df, hue=&quot;label&quot;, size=4).map(plt.scatter, &#39;1st_principal&#39;, &#39;2nd_principal&#39;).add_legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*r5zyUVji_uRPVfOE8zSsjw.png" /><figcaption>LDA for visualizing IRIS data using linear discriminant’s</figcaption></figure><h4><strong>Applying K-NN on original IRIS DATA</strong></h4><pre>def divide_training_dataset_to_k_folds(x_train,y_train,folds):<br> temp = len(x_train)/folds<br> x_train = x_train.tolist()<br> y_train = y_train.tolist()<br> group = []<br> label = []<br> end = 0.0<br> while end &lt; len(x_train):<br>  group.append(x_train[int(end):int(end + temp)])<br>  label.append(y_train[int(end):int(end + temp)])<br>  end += temp<br> return group,label</pre><p>Define Random Cross Validation Technique:</p><pre>from sklearn.metrics import accuracy_score<br>def RandomSearchCV(x_train,y_train,classifier, param_range, folds):<br> # x_train: its numpy array of shape, (n,d)<br> # y_train: its numpy array of shape, (n,) or (n,1)<br> # classifier: its typically KNeighborsClassifier()<br> # param_range: its a tuple like (a,b) a &lt; b<br> # folds: an integer, represents number of folds we need to devide the data and test our model<br> params = list(range(1,51))<br> #1.divide numbers ranging from  0 to len(X_train) into groups= folds<br> # ex: folds=3, and len(x_train)=100, we can devide numbers from 0 to 100 into 3 groups i.e: group 1: 0-33, group 2:34-66, group 3: 67-100<br> temp = len(x_train)/folds<br> temp = int(temp)<br>groups,labels = divide_training_dataset_to_k_folds(x_train,y_train, folds)</pre><pre> #2.for each hyperparameter that we generated in step 1 and using the above groups we have created in step 2 you will do cross-validation as follows:<br> # first we will keep group 1+group 2 i.e. 0-66 as train data and group 3: 67-100 as test data, and find train and test accuracies<br> # second we will keep group 1+group 3 i.e. 0-33, 67-100 as train data and group 2: 34-66 as test data, and find train and test accuracies<br> # third we will keep group 2+group 3 i.e. 34-100 as train data and group 1: 0-33 as test data, and find train and test accuracies<br> # based on the &#39;folds&#39; value we will do the same procedure<br> # find the mean of train accuracies of above 3 steps and store in a list &quot;train_scores&quot;<br> # find the mean of test accuracies of above 3 steps and store in a list &quot;test_scores&quot;</pre><pre> train_scores = []<br> test_scores  = []<br> for k in tqdm(params):<br>  trainscores_folds = []<br>  testscores_folds = []  <br>  for i in range(folds):<br>   X_train = [groups[iter] for iter in range(folds) if iter != i]<br>   X_train = [j for sublist in X_train for j in sublist]<br>   Y_train = [labels[iter] for iter in range(folds) if iter != i]<br>   Y_train = [j for sublist in Y_train for j in sublist]<br>   X_test  = groups[i]<br>   Y_test  = labels[i]<br>   classifier.n_neighbors = k<br>   classifier.fit(X_train,Y_train)<br>   Y_predicted = classifier.predict(X_test)<br>   testscores_folds.append(accuracy_score(Y_test, Y_predicted))<br>   Y_predicted = classifier.predict(X_train)<br>   trainscores_folds.append(accuracy_score(Y_train, Y_predicted))<br>  train_scores.append(np.mean(np.array(trainscores_folds)))<br>  test_scores.append(np.mean(np.array(testscores_folds)))<br>#3. return both &quot;train_scores&quot; and &quot;test_scores&quot;<br> return train_scores, test_scores,params</pre><p>K NN classifier</p><pre>from sklearn.metrics import accuracy_score<br>from sklearn.neighbors import KNeighborsClassifier<br>import matplotlib.pyplot as plt</pre><pre>classifier = KNeighborsClassifier()<br>param_range = (1,50)<br>folds = 3</pre><pre>X = dataset.iloc[:, :-1].values#store the dependent features in X<br>y = dataset.iloc[:, 4].values  #store the independent variable in y<br>X_train, X_test, y_train, y_test = train_test_split(X, y,stratify=y, random_state=42,test_size=0.30)<br>trainscores,testscores,params=RandomSearchCV(X_train,y_train,classifier, param_range, folds)</pre><pre>#  plot hyper-parameter vs accuracy plot as shown in reference notebook and choose the best hyperparameter</pre><pre>plt.plot(params,trainscores, label=&#39;train curve&#39;)<br>plt.plot(params,testscores, label=&#39;test curve&#39;)<br>plt.title(&#39;Hyper-parameter VS accuracy plot&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*EbmfuIVsfhyf35oBkF5_cQ.png" /><figcaption>max test accuracy is approx. 97%</figcaption></figure><h4>Applying K-NN on modified IRIS DATA using PCA</h4><pre>X = pca_df.iloc[:, :-1].values#store all the dependent features in X<br>y = pca_df.iloc[:, -1].values   #store the independent variable in y</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y,stratify=y, random_state=42,test_size=0.30) #training data = 70% and test data = 30%</pre><pre>trainscores,testscores,params=RandomSearchCV(X_train,y_train,classifier, param_range, folds)</pre><pre>#  plot hyper-parameter vs accuracy plot as shown in reference notebook and choose the best hyperparameter</pre><pre>plt.plot(params,trainscores, label=&#39;train curve&#39;)<br>plt.plot(params,testscores, label=&#39;test curve&#39;)<br>plt.title(&#39;Hyper-parameter VS accuracy plot&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*x_zjf0noPjn-xywTSDhV8Q.png" /><figcaption>max test accuracy is approx. 91%</figcaption></figure><h4>Applying K-NN on modified IRIS DATA using LDA</h4><pre>X_train, X_test, y_train, y_test = train_test_split(X,y,stratify=y, random_state=42,test_size=0.30)</pre><pre>trainscores,testscores,params=RandomSearchCV(X_train,y_train,classifier, param_range, folds)</pre><pre>#  plot hyper-parameter vs accuracy plot as shown in reference notebook and choose the best hyperparameter</pre><pre>plt.plot(params,trainscores, label=&#39;train curve&#39;)<br>plt.plot(params,testscores, label=&#39;test curve&#39;)<br>plt.title(&#39;Hyper-parameter VS accuracy plot&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*nEeYBdM6L6jgln5--AzEyw.png" /><figcaption>max test accuracy is approx. 97%</figcaption></figure><h3><strong>Conclusion:</strong></h3><p>To sum it up, We can observe from the above results that PCA performed poorly on labelled data. On the other hand, LDA haven&#39;t decreased the performance of K NN model and also, it reduced the complexity of data set. Since PCA is unsupervised technique, it doesn&#39;t take into account the class labels. Therefore, we can conclude that LDA is better dimensionality reduction technique than PCA for labelled data.</p><p>Link for code: <a href="https://github.com/GopiSumanth/MachineLearning/blob/master/PCA_%2B_K_NN_on_IRIS.ipynb">github</a></p><p>Note: reduced dataset using LDA gave same accuracy as original dataset i.e: 97%. However, reduced dataset using PCA gave an accuracy of 91% which is very less!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=105c431e8907" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/illustrative-example-of-principal-component-analysis-pca-vs-linear-discriminant-analysis-lda-is-105c431e8907">Illustrative Example of Principal Component Analysis(PCA) vs Linear Discriminant Analysis(LDA): Is…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>