<?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 Heena Sharma on Medium]]></title>
        <description><![CDATA[Stories by Heena Sharma on Medium]]></description>
        <link>https://medium.com/@heena-sharma?source=rss-d1870691308d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e4apj9hHhpxPJl4f-NYNyA.jpeg</url>
            <title>Stories by Heena Sharma on Medium</title>
            <link>https://medium.com/@heena-sharma?source=rss-d1870691308d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:16:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@heena-sharma/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[Custom chatbot for websites using LangChain, Azure OpenAI API, FAISS]]></title>
            <link>https://blog.gopenai.com/custom-chatbot-for-websites-using-langchain-azure-openai-api-faiss-6b9b00240c15?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9b00240c15</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[azureopenai]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 13:57:26 GMT</pubDate>
            <atom:updated>2023-06-10T21:51:34.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*rVspMPdfE5vQqsFIMoelYw.png" /><figcaption>Image by author</figcaption></figure><p>Table of contents:</p><ol><li><a href="#8d42">Introduction</a></li><li><a href="#80ec">Architecture</a></li></ol><ul><li><a href="#5e7c">Provide URLs</a></li><li><a href="#110a">Scrape data from the provided URLs</a></li><li><a href="#dbf6">Split data into chunks</a></li><li><a href="#7942">Get Embeddings</a></li><li><a href="#6934">Store Embeddings</a></li><li><a href="#d5a0">Query Part</a></li></ul><p>3. <a href="#f69e">Python Implementation</a></p><ul><li><a href="#f69e">Install required libraries</a></li><li><a href="#48e3">Define OpenAI Azure API type, version, base, and key</a></li><li><a href="#fe0a">Define the OpenAI LLM model</a></li><li><a href="#6f6e">Give the list of URLs</a></li><li><a href="#9848">Split the text into chunks</a></li><li><a href="#867d">Get Embeddings</a></li><li><a href="#faac">Store Embeddings</a></li><li><a href="#09a0">Generate Answers using context</a></li></ul><p>4. <a href="#d52e">References</a></p><ol><li><strong>Introduction</strong>:</li></ol><p>In today’s digital age, businesses are constantly seeking innovative ways to enhance customer experiences and streamline communication. One such solution that has gained tremendous popularity is the implementation of chatbots on websites. These intelligent conversational agents are revolutionizing the way businesses interact with their online visitors, providing instant support, answering inquiries, and guiding users through their online journey.</p><p>However, it’s important to note that ChatGPT, while proficient in generating replies, has limitations. It can only provide information based on its training data, which extends until November 2022. As a result, it lacks awareness of new or updated information.</p><p>I encountered a specific scenario where I needed to integrate a question-and-answer (Q&amp;A) system into our company’s external websites. However, the output generated by ChatGPT, the underlying technology I utilized, lacks awareness of any recent or updated information. This limitation poses a challenge as it prevents the system from providing accurate and up-to-date responses to user queries. Below is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqNJ2MjMigRtKj7zhFzkMg.png" /></figure><p>And I wanted something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f19be6d6c0c7812909c6d6f7473140/href">https://medium.com/media/a4f19be6d6c0c7812909c6d6f7473140/href</a></iframe><p>For the above output, I used LLM to answer queries based on the given context.</p><p>2. <strong>Architecture: </strong>Below is the overall architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuDNW0fVOQ8KmXV_QOxSuQ.png" /></figure><p><strong>Steps to follow:</strong></p><ol><li><strong>Provide URLs:</strong> A <strong>sitemap</strong> is a file that lists all the important pages on a website. An XML sitemap contains links to different pages on your website. Our chatbot is going to extract information from all the individual URLs on the webpage and generate a response.</li><li><strong>Scrape data from the provided URLs</strong>: To train the chatbot, we are going to use a <strong>Large Language Model</strong> (<strong>LLM</strong>). There are two ways in which we can use LLMs, either from open-source models (for example, hugging faces&#39; pre-trained LLM models) or OpenAI APIs. In this blog, we are doing training using Azure OpenAI APIs.</li><li><strong>Split data into chunks:</strong> The web pages will be further split into chunks to feed them to LLM. Why are we dividing them into chunks? The current LLMs that we have, have a finite context length, which means they can process only a small fixed amount of text, and because of that, we are splitting each page into several documents.</li><li><strong>Get Embeddings:</strong> Now that we cannot feed these chunks directly to LLM, we need to convert the chunks from text to numbers (called vectors containing float numbers) using embedding techniques. It is important to convert text into vectors so that we can later compare documents using mathematical functions. There are several embedding models available like OpenAIEmbeddings from OpenAI or other open-source embedding models like BERT, etc.</li><li><strong>Store Embeddings:</strong> Now we store these embeddings in a semantic index so that they become part of our knowledge base. As a vector store, we have several options to use here, like Pinecone, FAISS, and ChromaDB. In our case, we are going to use FAISS (Facebook Artificial Intelligence Semantic Search). FAISS is a<strong> </strong>library for efficient similarity search and clustering of dense vectors. The below two things are going to be stored in FAISS:</li></ol><ul><li>Embeddings of chunks</li><li>Documents that are split into chunks from original webpages</li></ul><p><strong>6. Query part</strong>: Now that our knowledge base is ready, what happens when a user interacts with our chatbot:</p><ol><li><strong>User Query</strong>: The user asks a query to the chatbot</li><li><strong>Query Embedding</strong>: The query will send to Embedding APIs, and that would result in the embedding vector of the query</li><li><strong>Semantic Search</strong>: The next step is to do a semantic or similarity search. In this, we compare query embedding with embeddings of the documents that we have in the knowledge base. Based on the similarity matrix (like cosine, sine, and Euclidean) we use, we will get the top 4–5 ranking documents from the knowledge base. Remember, in the knowledge base, we know the indices of the documents and embeddings, and we can find the documents corresponding to the top similar-ranked embeddings. We can pass the resulting documents as context to LLM.</li><li><strong>Answer</strong>: LLM has a context (from the chatbot on which we want to perform a query) and a query (from the user). LLM looks into the documents that are supplied as context and generate responses to user queries.</li></ol><p>3. <strong>Python Implementation: </strong>The Python implementation is using LangChain which is an open-source development framework for LLM applications. Below are the steps:</p><ol><li><strong>Install</strong> the required <strong>libraries</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef886db289d088654d79500f4611a471/href">https://medium.com/media/ef886db289d088654d79500f4611a471/href</a></iframe><p>2. Define <strong>OpenAI Azure API</strong> type, version, base, and key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497d1af2c14df1691befda6ed2715808/href">https://medium.com/media/497d1af2c14df1691befda6ed2715808/href</a></iframe><p>3. <strong>Define the OpenAI LLM</strong> model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec2d9fbae579702da44ffb07839b7fb5/href">https://medium.com/media/ec2d9fbae579702da44ffb07839b7fb5/href</a></iframe><p>4. <strong>Give the list of URLs</strong> that I am providing manually, and <strong>loading data</strong> using UnstructuredURLLoader</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5401f3682407436f8fb0b8c5ca1cc100/href">https://medium.com/media/5401f3682407436f8fb0b8c5ca1cc100/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*gij_EwYTd_Yb703owpCNxw.png" /></figure><p>The loaded data is of the type list with all text in document form, which contains page_content and metadata with source.</p><p>5. <strong>Split the text into chunks</strong>, each with a size of 500, and here I kept the overlap at 50. The overlap is important in cases where the same information is delivered in multiple sentences, and the last sentence is dependent on its previous sentence. In normal chunking without overlap, the last sentence will end up in a separate document, and it may not be conveying the information correctly. So we need overlap to have continuity of information. In cases where there is temporal dependency, you can use overlap; otherwise, there is no need to use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9edac9a088834fbd365bead4fb7bf7cd/href">https://medium.com/media/9edac9a088834fbd365bead4fb7bf7cd/href</a></iframe><p>This is the format we are getting the data in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUAPebLfq8l3CioL2sXm9w.png" /></figure><p>Below is the length of the documents after splitting them into chunks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*lBXcPbuSt7OD_vSFLLoRiw.png" /></figure><p>6. <strong>Get Embeddings</strong>: Use OpenAIEmbeddings for generating embeddings using the text-embedding-ada-002 model, there are other embedding models available too to try:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aeab563f985d22b209cfc3405288649/href">https://medium.com/media/9aeab563f985d22b209cfc3405288649/href</a></iframe><p>7. <strong>Store Embeddings</strong>: Use the FAISS vector store to store embeddings generated in previous steps and documents:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4169c1428c42081a8d0c1b61a072249f/href">https://medium.com/media/4169c1428c42081a8d0c1b61a072249f/href</a></iframe><p>8. <strong>Generate Answers using context:</strong> Use LLM to generate answers to the given query along with the sources. Here in the llm parameter, it could be any open-source LLM or OpenAI LLM. Chains allow us to combine multiple components together to create a single, coherent application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eccf1dccc511862a7a2466390c11d455/href">https://medium.com/media/eccf1dccc511862a7a2466390c11d455/href</a></iframe><p>Below is the output we are getting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f19be6d6c0c7812909c6d6f7473140/href">https://medium.com/media/a4f19be6d6c0c7812909c6d6f7473140/href</a></iframe><p>4. References:</p><p>[1].<a href="https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html#">https://python.langchain.com/en/latest/modules/indexes/vectorstores/examples/faiss.html#</a></p><p>[2].<a href="https://www.youtube.com/watch?v=2xxziIWmaSA&amp;list=PLqZXAkvF1bPNQER9mLmDbntNfSpzdDIU5&amp;index=3">https://www.youtube.com/watch?v=2xxziIWmaSA&amp;list=PLqZXAkvF1bPNQER9mLmDbntNfSpzdDIU5&amp;index=3</a></p><p>[3].<a href="https://www.youtube.com/watch?v=RBnuhhmD21U">https://www.youtube.com/watch?v=RBnuhhmD21U</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9b00240c15" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/custom-chatbot-for-websites-using-langchain-azure-openai-api-faiss-6b9b00240c15">Custom chatbot for websites using LangChain, Azure OpenAI API, FAISS</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Chatbots is here: Meet ChatGPT, the AI-Language Model that’s Changing the Game]]></title>
            <link>https://blog.gopenai.com/the-future-of-chatbots-is-here-meet-chatgpt-the-ai-language-model-thats-changing-the-game-6905873cf51d?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6905873cf51d</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 07:35:30 GMT</pubDate>
            <atom:updated>2023-04-08T08:16:39.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Blyj5nw6VLrkI97wbagoig.png" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="#b476">Introduction</a></li><li><a href="#6819">Large Language Models (LLMs)</a></li><li><a href="#dea9">Transformer Encoder-Decoder architecture</a></li><li><a href="#4572">Generative Pre-trained Transformer (GPT)</a></li><li><a href="#280f">Reinforcement Learning</a></li><li><a href="#ae4d">ChatGPT training steps</a></li><li><a href="#2046">Why do we use decoders in GPT?</a></li><li><a href="#2919">But why are only decoders, and why aren’t only encoders, used in GPT?</a></li><li><a href="#e56c">What is the prompt in ChatGPT?</a></li><li><a href="#9bb3">Python example to use OpenAI API</a></li><li><a href="#6952">References</a></li><li><strong>Introduction</strong></li></ol><p>ChatGPT is a ‘Large Language Model’ developed by <strong>OpenAI</strong> based on the <strong>GPT</strong> (Generative Pre-trained Transformer) architecture. It is designed to generate human-like responses to natural language queries and conversations, using deep learning algorithms to understand the context and generate appropriate responses.</p><p>ChatGPT has been fine-tuned by its creators using a blend of Supervised Learning and Reinforcement Learning methods, but it is the latter that sets it apart. The Reinforcement Learning component is distinguished by the use of a specialized technique known as Reinforcement Learning from Human Feedback (RLHF). This approach leverages human feedback within the training process which uses human feedback in the training loop to minimize harmful, untruthful, and/or biased outputs.</p><p>ChatGPT is built on top of the ‘Large Language Model’, ‘Transformer’, ‘GPT’, and ‘Reinforcement Learning’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3tMLkZ4Ek6ct-EFrrxqZQ.png" /></figure><p><strong>2. Large Language Models (LLMs)</strong></p><p>The LLM model is made up of a neural network with numerous parameters (usually billions of weights or more) that was trained using a significant amount of unlabeled text and self-supervised learning. LLMs digest massive text data and infer relationships between words within the text. Pre-training includes the following steps:</p><blockquote><strong>2.1. Next token prediction:</strong> The model is given a sequence of words with the goal of predicting the next word. Example: Heena is a _</blockquote><blockquote>Heena is a girl, Heena is a sister, Heena is a mother</blockquote><blockquote><strong>2.2 Masked Language Modeling: </strong>The model is given a sequence of words with the goal of predicting a masked word in the middle. Example: Heena [mask] travelling</blockquote><blockquote>Heena likes travelling, Heena hates travelling, Heena enjoys travelling</blockquote><p>Examples of LLMs could be GPT (OpenAI), BERT (Google), T5 (Google), and Roberta (FB).</p><p><strong>3. Transformer Encoder-Decoder architecture</strong></p><p>Transformer uses encoder-decoder architecture with attention mechanisms and has an infinite reference window of memory to refer to, unlike RNN, LSTM, and GRU, which have lesser reference window sizes. It is a sequence-to-sequence architecture that takes a sequence and outputs another sequence</p><p><strong>3.1. Encoder:</strong></p><p>The encoder takes every word of a sequence simultaneously and generates a numerical representation (also called a feature or tensor vector) that contains contextualized values for each word used as input simultaneously, by using the self-attention mechanism.</p><p>Encoders are powerful in extracting vectors that carry meaningful information in a sequence and can be used as standalone models in a wide variety of tasks like sequence classification (sentiment analysis), QnA, Masked Language Models (encoders with their bidirectional context are good at guessing words in the middle of a sequence) and natural language understanding. Examples of only-encoder models are <strong>BERT, ALBERT, and RoBERTa</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*IZuyvI0jhL6nmpMHc8IJiQ.png" /><figcaption>Encoder</figcaption></figure><p><strong>3.2. Decoder</strong>:</p><p>In the transformer’s encoder-decoder architecture, the decoder takes all words of a sequence given by the encoder simultaneously and generates a sequence of words one by one.</p><p>Like encoders, decoders can also be used as standalone models. The decoder takes a sequence of words and outputs a numerical representation (feature/tensor vector) for each word. It uses the <strong>Masked Self Attention</strong> mechanism, where words can only see the words on their left side, the right side is hidden.</p><p>Because of this property of decoders, they are good at generating text in a given sequence, this is called casual language modeling or natural language generation. Example: <strong>GPT</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*5RxvPjzJvKbWJmgz_ZaYyg.png" /><figcaption>Decoder</figcaption></figure><p><strong>4. Generative Pre-trained Transformer (GPT)</strong></p><p>The GPT model has stacked decoders from the transformer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*AK_WJ6KEqKrnyYrKsfLaUw.png" /><figcaption>GPT</figcaption></figure><p>Various versions of GPT include:</p><p><strong>GPT 1</strong> (2018) → <strong>GPT 2</strong>(2019) → <strong>GPT 3</strong>(2020) → <strong>GPT4</strong>(2023, multimodal, six times larger than GPT-3, with one trillion parameters)</p><p>The GPT model is trained on internet data, including books, Wikipedia, websites, and articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZ4xEIflqSW6-gCiy2y3Lg.png" /><figcaption>GPT models comparison, source: google search</figcaption></figure><p><strong>5. Reinforcement Learning</strong></p><p>Chat-GPT is further fine-tuned by Reinforcement learning. Reinforcement learning is a method of achieving some goal via rewards.</p><p>Reinforcement learning is a subfield of artificial intelligence that focuses on enabling machines to learn through interaction with their environment. In reinforcement learning, an agent interacts with an environment and learns to make decisions that maximize a reward signal.</p><p>The agent receives feedback in the form of rewards or penalties based on its actions, and its goal is to maximize the cumulative reward over time. The agent learns through trial and error, exploring different actions and observing the rewards or penalties that result.</p><p>Reinforcement learning algorithms are used in various applications, including robotics, gaming, and autonomous decision-making systems. They are often used in situations where there is no pre-existing labelled data, and the agent must learn by interacting with the environment.</p><p><strong>6. ChatGPT training steps</strong></p><p><strong>6.1. Supervised Fine-Tuning</strong>: OpenAI hired 40 contractors to create supervised training datasets (with 13k input/output) and, with that dataset, fine-tune the GPT-3 model to get the GPT 3.5 SFT model. For the recent GPT4-based ChatGPT version, they fine-tuned GPT3.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*iyIhtmPA1ZQuTNT2BQsrEQ.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></figcaption></figure><p><strong>6.2.</strong> <strong>Reward Model</strong>:</p><p>The goal is to learn an objective function (the reward model) directly from the data. The purpose of this function is to give a score to the SFT model outputs, proportional to how desirable these outputs are for humans. In practice, this will strongly reflect the specific preferences of the selected group of human labelers and the common guidelines that they agreed to follow. In the end, this process will extract from the data an automatic system that is supposed to mimic human preferences.</p><p>To train a reward model, the model takes input a series of prompts and responses and the model outputs a scaler value (called a reward). This is to leverage reinforcement learning, in which a model learns to produce outputs to maximize its reward. Steps are:</p><ul><li>A list of prompts is selected and the SFT model generates multiple outputs (anywhere between 4 and 9) for each prompt.</li><li>Labelers rank the outputs from best to worst. The result is a new labeled dataset, where the rankings are the labels. The size of this dataset is approximately 10 times bigger than the curated dataset used for the SFT model.</li><li>This new data is used to train a reward model (RM). This model takes as input a few of the SFT model outputs and ranks them in order of preference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*qVXKswUfvTTfVNs_uMJCjw.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></figcaption></figure><p><strong>6.3.</strong> <strong>Reinforcement Learning: </strong>The model is presented with a random prompt and returns a response. The response is generated using the ‘<strong>policy</strong>’ that the model has learned in step 2. The policy represents a strategy that the machine has learned to use to achieve its goal, in this case, maximizing its reward. Based on the reward model developed in step 2, a scaler reward value is then determined for the prompt and response pair. The reward then feeds back into the model to evolve the policy.</p><p><strong>Proximal Policy Optimization</strong> (PPO), is the method used in updating the model’s policy as each response is generated. PPO incorporates a per-token <strong>Kullback–Leibler</strong> (KL) penalty from the SFT model. The KL divergence measures the similarity of two distribution functions and penalizes extreme distances. In this case, using a KL penalty reduces the distance that the responses can be from the SFT model outputs trained in step 1 to avoid over-optimizing the reward model and deviating too drastically from the human intention dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*aKmAbWLZ3AzQMSniCQ3uSw.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></figcaption></figure><p>In summary, below are the three steps of the chatGPT training process:</p><ol><li><strong>Supervised fine-tuning</strong> step: a pre-trained language model is fine-tuned on a relatively small amount of demonstration data curated by labelers, to learn a supervised policy (the SFT model) that generates outputs from a selected list of prompts. This represents the <strong>baseline model</strong>.</li><li><strong>Reward Model </strong>step: labelers are asked to vote on a relatively large number of the SFT model outputs, this way creating a new dataset consisting of comparison data. A new model is trained on this dataset. This is referred to as the <strong>reward model</strong> (RM).</li><li><strong>Reinforcement Learning </strong>step: the reward model is used to further fine-tune and improve the SFT model. The outcome of this step is the so-called <strong>policy model.</strong></li></ol><p>Step 1 occurs only once, steps 2 and 3 of the process can be iterated repeatedly. After that, the model is evaluated based on its helpfulness, truthfulness, and harmlessness.</p><p><strong>7. Why do we use decoders in GPT</strong>?</p><p>By using decoders from the transformer encoder-decoder architecture, we cut down the calculations of a traditional encoder-decoder transformer to almost half.</p><p><strong>8</strong>. <strong>But why are only decoders, and why aren&#39;t only encoders, used in GPT</strong>?</p><p>The reason GPT is only decoders is that it is designed for <strong>autoregressive</strong> language modeling, where the model generates the output sequence one token at a time, conditioned on the input sequence and the previously generated tokens. In this task, the input sequence is given to the model, and the model generates the output sequence by predicting the next token based on the previous tokens in the output sequence.</p><p>Using only decoder blocks allows the model to attend to all the previously generated tokens and the input sequence to make the next token prediction. Additionally, since GPT is designed for language modeling, it is not necessary to have an encoder, as the input sequence is already a natural language text and does not require any additional processing.</p><p>So, in summary, the reason GPT is only a decoder is that it is optimized for text generation tasks, where a decoder-only architecture is sufficient and allows for more efficient and effective generation of coherent and contextually appropriate sequences of words.</p><p>By focusing on the decoder, GPT can generate high-quality text that is fluent, coherent, and semantically meaningful. However, <strong>it does not have the ability to encode or understand the meaning of the input text</strong>, which limits its applicability to tasks such as text classification, sentiment analysis, and question answering, where both the input and output sequences need to be processed.</p><p><strong>9. What is the prompt in ChatGPT</strong>?</p><p>In ChatGPT, a &quot;prompt&quot; is an input provided by the user that the language model uses to generate a response. The prompt is typically a sentence or a few words that give context or a starting point for the model to generate a response. For example, if a user asks, “What is the capital of France?” the prompt would be “What is the capital of France?”</p><p>The prompt helps the language model understand the user’s intention and generate a response that is relevant and meaningful. ChatGPT uses the prompt to initiate its language generation process, where it analyzes the text and generates a response based on its learned knowledge and understanding of natural language. The prompt plays a critical role in the conversation between the user and ChatGPT, as it sets the tone and direction for the conversation.</p><p>ChatGPT can be optimized with specific prompts to get the most out of its AI writing capabilities. These prompts allow users to receive more accurate and helpful responses and structure their content more efficiently. For example:</p><p><strong>9.1. Rewrite prompt</strong>: type in a paragraph and ChatGPT rewrites it uniquely</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzPFwtTXUxCL2uH-nUbqkg.png" /></figure><p><strong>9.2. Return only the main response prompt</strong>: prompts ChatGPT to shorten its verbose response and provide a concise answer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPJ_ZiFl9pDbcckpsDmTdQ.png" /></figure><p><strong>9.3. Style dictation</strong>: set ChatGPT to return responses in a specific style, such as fifth-grade level or doctoral level, with clear and complicated language and jargon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wmv4VgozRUBbIMNGhFkQxQ.png" /></figure><p><strong>9.4.</strong> <strong>Format your response prompt:</strong> use Markdown, subheadings, headings, bullet points, bold, etc., to structure ChatGPT’s response and avoid a wall of text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZF-7qSfUyddl5g0bmp__MA.png" /></figure><p><strong>10. Python example to use OpenAI API</strong></p><p>As of March 1, 2023, we can only fine-tune base GPT-3 models. Presently the best option for finetuning ChatGPT is prompt engineering.</p><p>The OpenAI API is a cloud platform hosted on Microsoft’s Azure that gives developers access to advanced, pre-trained artificial intelligence models. With the API, developers can easily add cutting-edge AI capabilities to their applications using a variety of programming languages.</p><p>Below are the steps to use OpenAI APIs using Python code:</p><ol><li><strong>Sign up for an OpenAI API account</strong> <a href="https://platform.openai.com/">https://platform.openai.com/</a></li><li><strong>Get API key</strong> <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a></li><li><strong>Install OpenAI</strong></li></ol><pre>pip install openai</pre><p>The<strong> </strong>OpenAI API provides three families of models that differ in terms of capabilities and price:</p><blockquote><strong>GPT-3:</strong> used for text completion, insertion, and editing</blockquote><blockquote><strong>Codex:</strong> allows code completion, insertion, and editing</blockquote><blockquote><strong>Content Filtering:</strong> allows filtering objectionable content</blockquote><p>The GPT-3 and Codex families consist of models from the Davinci, Curie, Babbage, and Ada series.</p><p>Davinci is the most capable and is ideal for understanding complex intentions, identifying causal relationships, and summarizing information for specific audiences. Davinci can perform almost every task with higher accuracy compared to other models.</p><p>The Curie model is quite capable of sentiment analysis and text classification.</p><p>The Babbage and Ada models are ideal for straightforward tasks that don’t require complex reasoning. Babbage and Ada are also the fastest and least expensive.</p><p><strong>4. Go to OpenAI API playground</strong> <a href="https://platform.openai.com/playground">https://platform.openai.com/playground</a> to play with input text to see the output response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onkYU97hLcSAIeETRLvpXQ.png" /><figcaption>Name Entity Recognition using ChatGPT</figcaption></figure><p><strong>5. View code in the openAI playground by selecting python language</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R89oTTKvOQzamp6GJqW5sQ.png" /><figcaption>Python code for Name Entity Recognition (NER)</figcaption></figure><pre>import os<br>import openai<br><br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br><br>response = openai.Completion.create(<br>  model=&quot;text-davinci-003&quot;,<br>  prompt=&quot;Extract Entities from the text.\ntext: New Delhi is the capital of India.\nEntities: \nNew Delhi: City\nIndia: Country\n##\ntext: Sundar Puchai is the CEO of Google\nEntities:&quot;,<br>  temperature=0,<br>  max_tokens=256,<br>  top_p=1,<br>  frequency_penalty=0,<br>  presence_penalty=0<br>)</pre><p><strong>11. References</strong></p><p>[1]. <a href="https://towardsdatascience.com/how-chatgpt-works-the-models-behind-the-bot-1ce5fca96286">https://towardsdatascience.com/how-chatgpt-works-the-models-behind-the-bot-1ce5fca96286</a></p><p>[2]. <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></p><p>[3]. <a href="https://analyzingalpha.com/openai-api-python-tutorial">https://analyzingalpha.com/openai-api-python-tutorial</a></p><p>[4]. <a href="https://www.assemblyai.com/blog/how-chatgpt-actually-works/#shortcomings-of-the-methodology">https://www.assemblyai.com/blog/how-chatgpt-actually-works/#shortcomings-of-the-methodology</a></p><p>[5]. <a href="https://www.youtube.com/watch?v=0_4KEb08xrE">https://www.youtube.com/watch?v=0_4KEb08xrE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6905873cf51d" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/the-future-of-chatbots-is-here-meet-chatgpt-the-ai-language-model-thats-changing-the-game-6905873cf51d">The Future of Chatbots is here: Meet ChatGPT, the AI-Language Model that’s Changing the Game</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdaBoost Ensemble Model]]></title>
            <link>https://heena-sharma.medium.com/adaboost-ensemble-model-f9d71f812d84?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d71f812d84</guid>
            <category><![CDATA[adaboost]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[adaboost-algorithm]]></category>
            <category><![CDATA[boosting]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 13:17:54 GMT</pubDate>
            <atom:updated>2022-06-29T16:58:53.279Z</atom:updated>
            <content:encoded><![CDATA[<p>Table of content:</p><ol><li><a href="#cc3e">Introduction</a></li><li><a href="#b29c">Three main ideas behind AdaBoost</a></li><li><a href="#188d">Steps of AdaBoost</a></li><li><a href="#e567">Reference</a></li><li><a href="#75cf">End Notes</a></li><li><strong>Introduction:</strong></li></ol><p>Adaptive Boosting or AdaBoost is a boosting ensemble technique that takes <strong>low variance and high bias</strong> models and uses the additive combination to <strong>reduce bias while keeping variance low</strong>.</p><p>AdaBoost is most often used in computer vision for face detection and image processing. At every stage of AdaBoost, we are adapting to the errors that were made before, more weight is given to the misclassified points.</p><p><strong>2. Three main ideas behind AdaBoost</strong>:</p><blockquote><strong>Idea 1</strong>. AdaBoost combined a lot of <strong>weak learners</strong> to make predictions, and these weak learners are almost always <strong>stumps</strong>.</blockquote><p><strong>A stump</strong> is a tree with one root node and 2 leaves. Unlike Random Forest which combine fully grown trees with no pre-determined depth. Stump has a high bias (as only one feature is used to predict output) and high variance (as stumps are unable to train on all the data points because of the low depth of the tree).</p><p>Let’s consider the below dataset for the classification problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*HME6lZYKJTorrN4alJ0VVA.png" /><figcaption>Dataset with <strong>inputs</strong>: Chest pain, Blocked Arteries, Patient Weight and <strong>output</strong>: Heart Disease</figcaption></figure><p><strong>Weak learners</strong> are the ML (Machine Learning) models that make predictions based on only one feature. In the below example, only one feature-Chest pain is predicting the output — ‘heart disease’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Y83_1Bwa_6gFCKG7hzBjgQ.png" /><figcaption>If there is Chest Pain → there will be Heart Disease, otherwise Not</figcaption></figure><blockquote><strong>Idea 2</strong>. Some stumps get more <strong>amount of say</strong>/vote in the final prediction than the other stumps, which usually depends of how much errror a stump made. <em>Unlike Random Forest, in which each tree has equal say/vote in final prediction.</em></blockquote><blockquote><strong>Idea 3</strong>. Each stump is made by taking the previous stump’s mistake into account. <em>Unlike in Random Forest each tree is made independently of the other.</em></blockquote><p><strong>3. Steps of AdaBoost</strong>:</p><p><strong>Step 1. Assign weight</strong> to all the samples, which is initially 1/(#samples) to make all samples equally important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQgKeejz-mfYlsAYl-uKIA.png" /><figcaption>Dataset with added Sample weight</figcaption></figure><p><strong>Step 2. Select the stump to start with</strong>: The stump with the lowest Gini index/Entropy will be selected as the stump to start with for the particular stage.</p><p>Note: We can easily create a stump with categorical data (yes/no) but what if data is numerical like ‘patient weight’? Below are the steps:</p><p>a. <strong>Sort</strong> the row in increasing order of patient weight.</p><p>b. Find the <strong>average</strong> between consecutive terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-roWorruiPbvZTOkWLa6fg.png" /></figure><p>c. <strong>Calculate the Gini index</strong> value for each average value calculated in the previous step. In this step we calculate the Gini index of leaves and root node (which is the weighted average of the Gini index of 2 leaves), below is the calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAqQbCX0DDQL1sz5cwhHgw.png" /></figure><p>Similarly, we compute the Gini Index of each Average value of Patient weight. Below are the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*9rifZpzln445vVhZeuLOwA.png" /><figcaption>Gini Index for Numerical value-Patient Weight</figcaption></figure><p>We can see that the Gini Index of Patient weight &lt; 176 is the lowest and hence is the best weight to select.</p><p>Now on comparing the Gini Index of 3 features (Chest Pain-0.47, Blocked Arteries-0.5, Patient Weight-0.2) we select the feature with the lowest Gini Index and that would be our first stump in the forest. In this example, we select Patient weight as it is having the lowest Gini Index as our first stump.</p><p><strong>Step 3.</strong> <strong>Calculate</strong> <strong>Total error and amount of say</strong>: Once the stump is selected, we find out the total error and amount of say for that stump for the incorrectly classified sample point.</p><p>The amount of say depends on how well a stump predicts the data. The <strong>Total Error</strong> of a stump is the <strong>sum of weights associated with incorrectly classified samples</strong>. The total error will always be between 0 (for perfect stump classifying the data correctly) and 1 (not classifying the data at all). ‘Amount of say’ is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ZniqouHnQKDQUGi_XCE-8w.png" /><figcaption>Amount of say formula</figcaption></figure><p><em>When the Total Error made by that stump is low, the amount of say is larger. When the Total Error made by that stump is large, the amount of say is lower. When the Total error is 0.5 (means half the data is classified in one class and half in another class) then the Amount of say will be 0 and this is the worst classification similar to random classification (like flipping a coin).</em></p><p>Amount of say for stump (Patient Weight &lt; 176) is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5decBEZPAHcmxEs4X2OQQ.png" /></figure><p>We calculated the amount of say and total error for incorrectly classified data points. <em>Sample weights are used to calculate the Amount of say for a stump. </em>Basically, the sample weights are used as the error, which is used in the calculation of the Amount of say.</p><p>Note: Total error will be between 0 and 1, and if the total error ends up being 0 or 1 then the equation of ‘Amount of Say’ will approach infinity, to avoid this a small error term is added in the formula.</p><p><strong>Step 4. Update Weight</strong>:</p><p>Once we know the incorrectly classified samples, we need to increase their sample weight and decrease all other sample weights. The formula for increasing the sample weight is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Knvolurhtf2INOq0bpnw_w.png" /><figcaption>Increase sample weight formula</figcaption></figure><p>Below is the graph of e^x where x is the amount of say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjO6JIBtYPAOqEawClYKQQ.png" /><figcaption>Plot e^x, x= Amount of say</figcaption></figure><p>If the amount of say is large → stump did a great job in making the prediction → e^ (amount of say) will be larger → New Sample weight will be large than the older sample weight</p><p>If the amount of say is low → stump didn’t do a good job in making prediction → then previous sample weight increased by very low number →New sample weight will be little larger than older sample weight.</p><p>In the case of stump Patient weight &lt; 176, below is the incorrectly classified weight:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh9IkCsC6r6_cXRyr_0Fiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*S_gdyfx7TvMiQFUawfT_Gg.png" /></figure><p>The new sample weight of the incorrectly classified sample is 0.33 which is more than the older weight (1/8 = 0.125).</p><p>Now we need to decrease the sample weight of all correctly classified samples using the below formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6L5cwvwoxkvzBBKJ-7cwA.png" /></figure><p>Below is the graph of e^-x, where x is the amount of say</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oBPoLTioiVhwgf9SGs_NA.png" /><figcaption>Plot e^-x, x= Amount of say</figcaption></figure><p>If the amount of say is large → we scale weight by a value close to 0 → New sample weight becomes very small</p><p>If the amount of say is small→ we scale weight by a value close to 1 → New sample weight becomes just a little smaller than the older sample weight</p><p>In our example, the new decreased sample weight will be 0.05.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*C4y2JpymNsgPSBlOVBQ-Wg.png" /></figure><p>Below are the new weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAq42Kacyl1vnlfbAsassQ.png" /></figure><p>Below data is used to create the next stump based on the Gini index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghWUldmksTY8aDacgCSyBw.png" /></figure><p>In the new data (above table) more emphasis is given to the sample with more weight as it was wrongly classified last time.</p><p><strong>Step 5: Create the new dataset for the next stage</strong></p><p>In this step, we select n samples (n is the sample size, in our example, it is 8) with replacement from the dataset calculated in step 4, with the odds of picking each of the samples based on their new sample weight.</p><p>The steps are below:</p><p>a. Pick a <strong>random number</strong> (let it is ‘s’) between 0 and 1.</p><p>b. Now <strong>select the sample</strong> based on the number s picked randomly in step ‘a’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLc0ZC3WwIsbatBUUAkC8w.png" /><figcaption>Select sample based on random number ‘s’</figcaption></figure><p>We can see that the sample weight of incorrect classified data points is more than the rest, hence it will be more likely to be selected more often and thus next stump will focus more on classifying the misclassified sample correctly. All misclassified samples (highlighted below) are the same, and they will be treated as a block, creating a large penalty for being misclassified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*mtjfZIS9Uax8DQkm0BtyIw.png" /><figcaption>Randomly selected samples</figcaption></figure><p>Now repeat steps 1–5 several times to <em>make stumps until the number of stumps you asked for, or it has a perfect fit</em>.</p><p><strong>Step 6</strong>.: <strong>How forest of stumps make predictions</strong>:</p><p>There will be several stumps after performing the above steps, some of them predict ‘Yes’ and some of them predict ‘No’ as Heart Disease. In this case, what will be the final prediction? Based on the total amount of say (for Yes and for No) we calculate the sum of the amount of say for both the classed and class with the higher amount of say is the classification of the new point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcFgSsbVXKurq9jSFpmXsA.png" /></figure><p><strong>4. References</strong>:</p><p>[1]. <a href="https://www.youtube.com/watch?v=LsK-xG1cLYA">https://www.youtube.com/watch?v=LsK-xG1cLYA</a></p><p><strong>5. End Notes:</strong></p><p>Thanks for reading this article, I hope it is helpful in understanding the AdaBoost model and the mathematics behind it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d71f812d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbor in Machine Learning]]></title>
            <link>https://heena-sharma.medium.com/k-nearest-neighbor-in-machine-learning-68db26083aaa?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68db26083aaa</guid>
            <category><![CDATA[python-example]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 11:58:06 GMT</pubDate>
            <atom:updated>2022-01-23T11:58:08.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*jQa8doaHr-1b1oOS.png" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#7e38">Introduction</a></li><li><a href="#3838">Properties of KNN</a></li><li><a href="#d992">Steps of KNN algorithm</a></li><li><a href="#ff05">Distance metrics in KNN</a></li><li><a href="#be7f">KNN hyperparameter K</a></li><li><a href="#3848">How to select the value of K</a></li><li><a href="#bfeb">Data Preparation for KNN</a></li><li><a href="#9c55">KNN for Classification</a></li><li><a href="#6552">KNN for Regression</a></li><li><a href="#bdbf">Pros of using KNN</a></li><li><a href="#7e59">Cons of using KNN</a></li><li><a href="#2b66">Applications of KNN</a></li><li><a href="#ae1b">References</a></li><li><strong>Introduction:</strong></li></ol><p>K-Nearest Neighbor or KNN is a supervised machine learning algorithm used for both Classification and Regression tasks. However, most often it is used for classification problems. It is a very useful algorithm in the case of small datasets, as it requires a lot of time and memory.</p><p><strong>2. Properties of KNN:</strong></p><ul><li><strong>Lazy learning algorithm</strong> − KNN is a lazy learning algorithm because it does not explicitly learn the model, but it saves all train data as it is in the training phase and at the testing phase, it uses whole train data for prediction. This means the training process is very fast, but the real concern is with large memory consumption to save all training data. And time complexity at testing phase because it requires to run through all train data</li><li><strong>Non-parametric learning algorithm</strong> − KNN is also a non-parametric learning algorithm because it doesn’t assume anything about the underlying data</li></ul><p><strong>3. Steps of KNN algorithm:</strong></p><p>KNN algorithm uses feature similarity to predict the values of new data points, which means that the new data point will be assigned a value based on how closely it matches the points in the training set. Below are the steps of KNN in the case of Classification and Regression:</p><p><strong>Step 1</strong> − The first step is to load the training as well as test data</p><p><strong>Step 2</strong> − Next, we need to choose the value of K, i.e. the nearest data points. K can be any integer</p><p><strong>Step 3</strong> − For each point in the test data, do the following:</p><ul><li><strong>3.1</strong> − Calculate the distance between test data and each row of training data with the help of the Euclidean, Manhattan, Minkowski, or Hamming distance. The most commonly used method to calculate distance is Euclidean</li><li><strong>3.2</strong> − Now, based on the distance value, sort them in ascending order</li><li><strong>3.3</strong> − Next, it will select the top K rows from the sorted array</li><li><strong>3.4</strong> − Now, based on the type of model-Regression/Classification, follow the below next step:</li><li><strong>3.4.1</strong> — In the case of <strong>Classification</strong>, assign a class to the test point which is equal to the <strong>majority vote</strong> or most frequent class of the K-selected rows. If K is even, then majority votes can result in ties, it is advised to avoid even value for K</li><li><strong>3.4.2</strong> — In the case of <strong>Regression</strong>, assign a value to the test point which is equal to the <strong>mean</strong> of the K-selected rows.</li></ul><p><strong>4. Distance metrics options</strong>:</p><p>Distance metrics used in KNN for Regression and Classification problems are below:</p><ul><li><strong>Euclidean distance</strong></li></ul><p>Euclidean distance is the square root of the sum of squared distance between two points. It is also known as the L2 norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*FOHPQrctnae55VIQN4CpIw.png" /></figure><ul><li><strong>Manhattan distance</strong></li></ul><p>Manhattan distance is the sum of the absolute values of the differences between two points. It is also known as the L1 norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*DAMRMBO20DyRnV3XvrnWog.png" /></figure><ul><li><strong>Minkowski Distance</strong></li></ul><p>Minkowski distance is used to find distance similarity between two points. When p=1, it becomes Manhattan distance, and when p=2, it becomes Euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*T_sQrJ5VbowPeCEHwVB90g.png" /><figcaption>Minkowski distance between 2 points (X1, Y1) and (X2, Y2)</figcaption></figure><ul><li><strong>Hamming Distance</strong></li></ul><p>Hamming distance is used for categorical variables. In simple terms, it tells us if the two categorical variables are the same or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/0*sqaX7jxOv8WLi7Oy.png" /><figcaption>Hamming distance between categorical data: XOR</figcaption></figure><p><strong>5. KNN hyperparameter — K:</strong></p><p>K is a hyperparameter in classification and Regression KNN, which is the number of neighbors to consider while predicting the class/value of a query data-point.</p><p>Depending on the value of K, the <strong>KNN classifier</strong> selects the nearest K data points and assigns the query data point the class which is equal to the majority vote of the K neighbors. In the below example, the query point is assigned class B when K=1 and class A when K=7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*r0PutklD9hmc_6EfuPYSPg.png" /><figcaption>KNN on classification data</figcaption></figure><p>In the case of Regression data, <strong>KNN Regressor</strong> will assign the value to the query data-point which is equal to the average of K-nearest data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*Z5eBStDv0BsdAL6eLO0tJg.png" /><figcaption>KNN on Regression data</figcaption></figure><p>K value determines the decision boundary between classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*nWEZejypzanATXPmD8H0Zw.png" /><figcaption>Decision boundary in case of Classification data when using KNN Classifier and different K</figcaption></figure><p>In the above image of KNN classifier (true in case of KNN Regressor as well):</p><p><strong>K=1</strong> → decision curve is non-smooth on train data → extremely high accuracy on train data → low accuracy on test data → <strong>Overfit</strong> → <strong>High Variance</strong></p><p>K = Neither too large nor too small → Neither overfit nor under fit → Generating smooth decision surface → less prone to noise.</p><p><strong>K=n</strong> (number of train data points) → Not generating any decision surface → classifying all query points with majority class → <strong>Under fit</strong> → <strong>High Bias</strong></p><p><strong>6. How to select the value of K</strong>:</p><p>In KNN, finding the value of K is not easy. A small value of K means that noise will have a higher influence on the result, and a large value makes it computationally expensive. K is a crucial parameter in the KNN algorithm. Some suggestions for choosing K Value are:</p><ol><li>It is recommended to choose an <strong>odd number</strong> for K if the number of classes is 2 and another simple approach to select K=<strong>sqrt(n)</strong> where n = number of data points in the training dataset.</li><li><strong>Domain knowledge</strong> is very useful in deciding the K value.</li><li><strong>Using error curves</strong>: The figure below shows error curves for different values of K for training and test data. At low K values, there is overfitting of data/high variance. Therefore, test error is high, and train error is low. At K=1 in train data, the error is always zero, because the nearest neighbor to that point is that point itself. Therefore, through training error is low, test error is high at lower K values. This is called overfitting. As we increase the value for K, the test error is reduced. But after a certain K value, bias/underfitting is introduced and test error goes high. So we can say initially test data error is high(due to variance) then it goes low and stabilizes and with further increase in K value, it again increases(due to bias). The K value when test error stabilizes and is low is considered as optimal value for K. From the above error curve, we can choose K=8 for our KNN algorithm implementation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*GveNcnxMl8zZWkuG.png" /></figure><p><strong>7. Data Preparation for KNN</strong>:</p><ol><li><strong>Data Scaling</strong>: To locate the data point in multidimensional feature space, it would be helpful if all features are on the same scale. Hence, normalization or standardization of data will help</li><li><strong>Dimensionality Reduction</strong>: KNN may not work well if there are too many features. Hence, dimensionality reduction techniques like feature selection, principal component analysis can be implemented</li><li><strong>Missing value treatment</strong>: If out of M features, one feature data is missing for a particular example in the training set, then we cannot locate or calculate distance from that point. Therefore, deleting that row or imputation is required</li></ol><p><strong>8. KNN for Classification:</strong></p><p>In the python implementation of KNN Classifier, we generate data using sklearn.make_classification and split the data into train and test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab8ab25dc975e481f805c9bd4896efa5/href">https://medium.com/media/ab8ab25dc975e481f805c9bd4896efa5/href</a></iframe><p>Now scale the input features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea6cbccde006ab36608a60339274e46/href">https://medium.com/media/1ea6cbccde006ab36608a60339274e46/href</a></iframe><p>Now, find the value of K, for which we get maximum Accuracy or lowest error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e80313b0be7be81308d1e231d73bf2bb/href">https://medium.com/media/e80313b0be7be81308d1e231d73bf2bb/href</a></iframe><p>The output of the above code is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ebKbEXnXwwaDnarkWAbRQ.png" /><figcaption>Accuracy value for different K</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wulx8LJAjSk1EaCAKvKDKw.png" /></figure><p>We can see that at K=7, we get maximum accuracy of 0.96, and that&#39;s the best value of K.</p><p><strong>9. KNN for Regression:</strong></p><p>In the python implementation of KNN Regressor, we generate data using sklearn.make_regression and split the data into train and test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76fc650a045d89963c344c420a3a233f/href">https://medium.com/media/76fc650a045d89963c344c420a3a233f/href</a></iframe><p>Distance-based algorithms like KNN, K-means, and SVM are most affected by the range of features. This is because they are using distances between data points to determine their similarity and hence perform the task at hand. Therefore, we scale our data before employing a distance-based algorithm so that all the features contribute equally to the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/949b80b857266e9c97aeedb3bc7e6465/href">https://medium.com/media/949b80b857266e9c97aeedb3bc7e6465/href</a></iframe><p>Now, find the value of K, for which we get minimum Root Mean Square Error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f206f16a43d74befcdffe6d3b069aea/href">https://medium.com/media/6f206f16a43d74befcdffe6d3b069aea/href</a></iframe><p>Below is the output for different values of K, we can see that at K=3 RMSE value is minimum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM4lpe_tLHWFwK82VGWK8g.png" /><figcaption>The output of RMSE for different values of K</figcaption></figure><p>Below is the plot for different values of K and RMSE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp7pg-qTQtqb4SGKuNBKdA.png" /></figure><p>We can also apply GridSearchCV to find the best value of parameter K:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a46444d369f5e8a4d9498ff38a66405f/href">https://medium.com/media/a46444d369f5e8a4d9498ff38a66405f/href</a></iframe><p>Below is the output of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*stxQYxt8oztOsHQLUkYy0g.png" /></figure><p><strong>10. Pros of using KNN:</strong></p><ul><li>This algorithm is very easy to understand and interpret</li><li>It is very useful for nonlinear data because there is no assumption about data in this algorithm</li><li>It is a versatile algorithm, as we can use it for classification as well as regression</li><li>Furthermore, it has relatively high accuracy, but there are much better-supervised learning models than KNN</li></ul><p><strong>11. Cons of using KNN:</strong></p><ul><li>It is computationally a bit expensive algorithm because it stores all the training data</li><li>High memory storage is required as compared to other supervised learning algorithms.</li><li>Prediction is slow in the case of large data</li><li>It is very sensitive to the scale of data as well as irrelevant features and outliers</li></ul><p><strong>12. Applications of KNN:</strong></p><p>The following are some areas in which KNN can be applied successfully:</p><ul><li><strong>Banking System</strong>: KNN can be used in banking systems to predict whether an individual is fit for loan approval. Does that individual have characteristics similar to the defaulter&#39;s one?</li><li><strong>Calculating Credit Ratings</strong>: KNN algorithms can be used to find an individual’s credit rating by comparing it with the persons having similar traits</li><li><strong>Politics</strong>: With the help of KNN algorithms, we can classify a potential voter into various classes like “Will Vote”, “Will not vote”, “Will Vote to Party A”, “Will Vote to Party B”</li></ul><p>Other areas in which the KNN algorithm can be used are Speech Recognition, Handwriting Detection, Image Recognition, and Video Recognition.</p><p><strong>13. References</strong>:</p><p>[1] <a href="https://www.youtube.com/watch?v=wTF6vzS9fy4">https://www.youtube.com/watch?v=wTF6vzS9fy4</a></p><p>[2] <a href="https://www.youtube.com/watch?v=HVXime0nQeI">https://www.youtube.com/watch?v=HVXime0nQeI</a></p><p>[3] <a href="https://www.analyticsvidhya.com/blog/2021/04/simple-understanding-and-implementation-of-knn-algorithm/">https://www.analyticsvidhya.com/blog/2021/04/simple-understanding-and-implementation-of-knn-algorithm/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68db26083aaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive Bayes in Machine Learning]]></title>
            <link>https://heena-sharma.medium.com/naive-bayes-in-machine-learning-684e38a96e8d?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/684e38a96e8d</guid>
            <category><![CDATA[naive-bayes-theorem]]></category>
            <category><![CDATA[laplace-smoothing]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[naive-bayes-classifier]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 17:57:36 GMT</pubDate>
            <atom:updated>2022-01-16T18:04:35.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*n1PQZwE-r9QO0fVY.jpg" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#24a2">Introduction</a></li><li><a href="#3836">Assumptions of Naive Bayes</a></li><li><a href="#7cd7">Bayes Theorem</a></li><li><a href="#29cd">Example of Naive Bayes</a></li><li><a href="#a720">Problem with Naive Bayes</a></li><li><a href="#0c5c">Laplace or Additive Smoothing</a></li><li><a href="#c068">Bias Variance Tradeoff in Naive Bayes using hyper-parameter α</a></li><li><a href="#f0b5">Example of Laplace smoothing</a></li><li><a href="#3b23">Applications of Naive Bayes</a></li><li><a href="#c8de">Pros of using Naive Bayes</a></li><li><a href="#eeb1">Cons of using Naive Bayes</a></li><li><a href="#9df1">How to build a basic model using Naive Bayes in Python</a></li><li><a href="#4bc5">Tips to improve the power of the Naive Bayes Model</a></li><li><a href="#f263">References</a></li><li><strong>Introduction:</strong></li></ol><p>Naive Bayes is a supervised machine learning <strong>classifier</strong> based on <strong>probabilities</strong>. The name ‘Naive’ means that the classifier makes a “naive” assumption that each of the input <strong>features</strong> are <strong>conditionally independent</strong>, i.e. changing one feature won&#39;t affect the other features.</p><p>The Naive Bayes model is simple, yet powerful and easy to implement. One of the advantages of this model is that it does not involve complex mathematical computations and thus, it can be used with a large amount of data.</p><p>Naive Bayes is a family of powerful and easy-to-train classifiers, which determine the probability of an outcome, given a set of conditions using the Bayes’ theorem. In other words, the conditional probabilities are inverted so that the query can be expressed as a function of measurable quantities.</p><p><strong>2. Assumptions of Naive Bayes:</strong></p><p>The fundamental Naive Bayes assumption is that each feature makes an <strong>independent</strong> and <strong>equal</strong> contribution to the outcome. This means that for the given outcome variable (y) we assume that the given input features (X) are independent of each other and they possess equal weightage.</p><p>The assumptions made by Naive Bayes do not generally hold in real-world situations. In fact, the independence assumption is almost never correct but often works well in practice.</p><p><strong>3. Bayes Theorem:</strong></p><p>The Naive Baye classifier is based on the Bayes theorem with the above-mentioned assumptions. Bayes theorem provides a way of calculating the posterior probability <em>P</em>(<em>c|x</em>) from <em>P</em>(<em>c</em>), <em>P</em>(<em>x</em>), and <em>P</em>(<em>x|c</em>). Naive Bayes classifier assumes that the effect of the value of a feature/predictor (<em>x</em>) on a given outcome variable/class (c) is independent of the values of other features. This assumption is called <strong>conditional independence</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oE6yH3O0bzYZI7N7xhz0w.png" /></figure><ul><li>P(c|x) is the posterior probability of class (outcome) given predictor (feature).</li><li>P(c) is the prior probability of class.</li><li>P(x|c) is the likelihood which is the probability of the predictor given class.</li><li>P(x) is the prior probability of predictor.</li></ul><p>Now, with regards to the dataset with input (X, y), we can apply the Bayes theorem in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*f6X65RxPIsg7aj-US43T8g.png" /><figcaption>Bayes Theorem on the dataset (X, y)</figcaption></figure><p>where y is the outcome variable and X is input features vector X=(x1, x2, …., xn) of size n. We can also represent this as follows (in terms of component features of the feature vector X):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyDBJaHur8zdXXBmO9uFOw.png" /></figure><p>Note that for a given input, the denominator would be a constant for all outcomes (y), so we can ignore it and re-write as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-_fKejSiZZPs-yVzlr0TA.png" /></figure><p><strong>4. Example of Naive Bayes:</strong></p><p>To find whether a given email is spam or not, let’s consider a small dataset of 12 emails containing 8 non-spam and 4 spam emails with the below words inside them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*JvxqM-uWRV30W12YYDaqIg.png" /></figure><p>In the above image, we calculated the conditional probability or likelihood (P (word | Non-spam) and P (word | spam)) of seeing each word, given we saw the word is in either Non-spam or spam email and the probability of spam and non-spam emails (P (spam) and P (Non-spam) called class probabilities).</p><p>For a new given email containing, ‘Dear Friend’ we want to determine if it belongs to spam or non-spam email we can use the below formula of Naive Bayes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2DUPbnCv2noI3SWwZKiOw.png" /></figure><p>From the above calculation, it&#39;s clear that the email with the phrase ‘Dear Friend’ is identified as Non-Spam because 0.09 &gt; 0.01.</p><p>Naive Bayes ignore all grammar rules because keeping track of every single reasonable phrase in a language would be impossible. It treats language like it is just a bag full of words.</p><p>In Machine learning, we’d say that by ignoring relationships among words, Naive Bayes has a <strong>high bias</strong>. But because it works well in practice and doesn’t change on changing the training dataset, Naive Bayes has <strong>low variance</strong>.</p><p><strong>5. Problem with Naive Bayes:</strong></p><p>The problem with the Naive Bayes classifier is that if a word is not present in the Spam class, it will always be classified as a normal (Non-spam) email even if the email is spam. For example, text containing the word ‘Lunch’ will always be classified as Non-Spam because the word ‘Lunch’ is not present in Spam emails. But in actual it should not be the case, so the resolve this issue solution to use <strong>Laplace/Additive smoothing</strong>.</p><p>If a word is not present in training, then add 1 (or greater number) to every word count, so it never gives 0 when multiplied with Bayes probability.</p><p><strong>6. Laplace or Additive Smoothing:</strong></p><p>At the end of the training, all the likelihoods and priors are computed.</p><p>At test time, say we find a new word W’ for which likelihood is not available (=0), we will use Laplace smoothing, as the word is not present in training data. We will add a smoothing value to the numerator and denominator for the likelihood probability of the new word as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPodcgMfl8KmeUVk_I86hg.png" /><figcaption>Laplace smoothing</figcaption></figure><p>Laplacian smoothing is applied to all words in training data and also to new words that occur in test data.</p><p>We have an additive smoothing and generally, 1 additive smoothing is applied i.e. Laplace smoothing with α = 1. In simple language, Laplace smoothing formula could be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dePJtDBTbSWQ4VD8574AdQ.png" /></figure><p><strong>7. Bias Variance Tradeoff in Naive Bayes using hyper-parameter α:</strong></p><p>In Naive Bayes, there is one hyper-parameter <strong>α</strong> in Laplace smoothing which determines bias and variance tradeoff.</p><p><strong>Bias</strong> is the inability of a Machine Learning method to capture the true relationship. Example: Line instead of a curve which can cause <strong>Underfitting</strong>.</p><p><strong>Variance </strong>is the difference in fits between data sets (train vs test fit performance), It will cause <strong>Overfitting</strong>. ∑∑</p><p><strong>Case1: When there is no Laplace smoothing (α = 0)</strong>. Let’s consider a word that occurs only 2 (a very few) times out of 2000 total words. And we are giving the probability to the rare, occurred word as well and hence overfitting in a way.</p><p>A small change in train data (example: removing 2 words from X) will result in a large change in probability (example: model probability changes from 2/1000 to 0/1000) will result in <strong>high variance</strong> and hence cause <strong>overfitting</strong>.</p><p><strong>Case2: When α is very large</strong>, the model will not be able to distinguish between classes. And result in <strong>under-fitting </strong>or <strong>High Bias</strong>.</p><p>Best α can be identified by using simple <strong>cross-validation</strong> or <strong>k-fold cross-validation</strong> in Naive Bayes.</p><p><strong>8. Example of Laplace smoothing:</strong></p><p>After adding 1 count (α =1) to each word count we get below the probability of each observed word which is never 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*Og-FGYYLP33FN8TeLBSUZw.png" /></figure><p><strong>9. Applications of Naive Bayes:</strong></p><ul><li><strong>Real-time prediction</strong>: Naive Bayes is an eager learning classifier and is quite fast in its execution. Thus, it could be used for making predictions in real-time.</li><li><strong>Multi-class prediction</strong>: The Naive Bayes algorithm is also well-known for multi-class prediction, or classifying instances into one of several classes.</li><li><strong>Text classification or spam filtering or sentiment analysis</strong>: When used to classify text, a Naive Bayes classifier often achieves a higher success rate than other algorithms due to its ability to perform well on multi-class problems while assuming independence. As a result, it is widely used in spam filtering (identifying spam email) and sentiment analysis (e.g. in social media, to identify positive and negative customer sentiments).</li><li><strong>Recommendation Systems</strong>: A Naive Bayes Classifier can be used together with Collaborative Filtering to build a Recommendation System that could filter through new information and predict whether a user would like a given resource or not.</li></ul><p><strong>10. Pros of using Naive Bayes:</strong></p><ul><li>It is easy and fast to predict the class of test data set. It also performs well in multi-class prediction</li><li>When the assumption of independence holds, a Naive Bayes classifier performs better compared to other models like logistic regression, and it needs less training data.</li><li>It performs well in the case of categorical input variables compared to the numerical variables. For numerical variables, the normal distribution is assumed (bell curve, which is a strong assumption).</li></ul><p><strong>11. Cons of using Naive Bayes:</strong></p><ul><li>If the categorical variable has a category (in the test data set), which was not observed in the training data set, then the model will assign a 0 probability and will be unable to make a prediction. This is often known as “Zero Frequency”. To solve this, we can use the <strong>smoothing technique </strong>like<strong> </strong>Laplace estimation.</li><li>On the other side, naive Bayes is also known as a bad estimator, so the probability outputs from predict_proba are not to be taken too seriously.</li><li>Another limitation of Naive Bayes is the assumption of independent predictors. In real life, it is almost impossible that we get a set of predictors which are completely independent.</li></ul><p><strong>12. How to build a basic model using Naive Bayes in Python:</strong></p><p>Using the python library scikit-learn we can build a Naive Bayes model. There are three types of Naive Bayes model under the Scikit-learn library:</p><ul><li><a href="http://scikit-learn.org/stable/modules/naive_bayes.html"><strong>Gaussian:</strong></a><strong> </strong>It is used in classification, and it assumes that features follow a normal distribution. With the iris dataset (which follows Gaussian distribution) GaussianNB model is as follows:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a73d559020b4480093f4c01221651c9/href">https://medium.com/media/1a73d559020b4480093f4c01221651c9/href</a></iframe><p>Output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f26c14d27b067a5c3b374a043aa092c3/href">https://medium.com/media/f26c14d27b067a5c3b374a043aa092c3/href</a></iframe><ul><li><a href="http://scikit-learn.org/stable/modules/naive_bayes.html"><strong>Multinomial</strong></a><strong>: </strong>The multinomial Naive Bayes classifier is suitable for classification with discrete features (e.g., word counts for text classification). The multinomial distribution normally requires integer feature counts. Below is an example of Multinomial Naive Bayes with the MNIST digit dataset. Each sample (belonging to 10 classes) is an 8×8 image encoded as an unsigned integer (0–255):</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/459799bfc996aecd3d6ceb9dac72847e/href">https://medium.com/media/459799bfc996aecd3d6ceb9dac72847e/href</a></iframe><p>If we compare Gaussian and Multinomial NB, we get a higher accuracy score from the MulitnomialNB model.</p><ul><li><a href="http://scikit-learn.org/stable/modules/naive_bayes.html"><strong>Bernoulli</strong></a><strong>: </strong>If X is random variable Bernoulli-distributed, it can assume only two values (Example: 0 and 1) and their probability is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*yGyVe9eBwkmHU2nt.jpg" /></figure><p>Like MultinomialNB, Bernoulli classifier is suitable for discrete data. The difference is that while MultinomialNB works with occurrence counts, BernoulliNB is designed for binary/boolean features.</p><p>Let&#39;s see below example on dummy data generated using sklearn library make_classification with binary classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5c2470ef6c84170c945990b004a259/href">https://medium.com/media/ff5c2470ef6c84170c945990b004a259/href</a></iframe><p><strong>13. Tips to improve the power of the Naive Bayes Model:</strong></p><ul><li>If continuous features do not have a normal distribution, we should use log transformation or different methods to convert them into the normal distribution.</li><li>Remove correlated features, as the highly correlated features are voted twice in the model, and it can lead to overinflating importance.</li><li>Naive Bayes classifiers have limited options for parameter tuning like α=1 for smoothing, fit_prior=[True|False] to learn class prior probabilities or not and some other options. It is recommended to focus on pre-processing of data and feature selection.</li><li>You might think to apply some classifier combination techniques like ensembling, bagging, and boosting, but these methods would not help. Actually, ensembling, boosting, bagging won’t help since their purpose is to reduce variance. Naive Bayes has no variance to minimize.</li></ul><p><strong>14. References:</strong></p><p>[1] <a href="https://www.youtube.com/watch?v=O2L2Uv9pdDA">https://www.youtube.com/watch?v=O2L2Uv9pdDA</a></p><p>[2] <a href="https://scikit-learn.org/stable/modules/naive_bayes.html">https://scikit-learn.org/stable/modules/naive_bayes.html</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">https://en.wikipedia.org/wiki/Naive_Bayes_classifier</a></p><p>[4] <a href="https://www.analyticsvidhya.com/blog/2017/09/naive-bayes-explained/">https://www.analyticsvidhya.com/blog/2017/09/naive-bayes-explained/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=684e38a96e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization in Machine Learning]]></title>
            <link>https://heena-sharma.medium.com/regularization-in-machine-learning-e7445c3166cd?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7445c3166cd</guid>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[l2-regularization]]></category>
            <category><![CDATA[lasso-regression]]></category>
            <category><![CDATA[l1-regularization]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 13:27:36 GMT</pubDate>
            <atom:updated>2022-01-07T13:27:36.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*25B-doIS_3ePVuCP.png" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#0c0b">Overfitting</a></li><li><a href="#95be">Overfitting Examples</a></li><li><a href="#345a">How to overcome Overfitting?</a></li><li><a href="#9008">What parameters (θ’s) to penalize?</a></li><li><a href="#b583">Regularization</a></li><li><a href="#c84b">Types of Regularization</a></li><li><a href="#67e9">Regularization Parameter λ</a></li><li><a href="#e063">Why L1 creates Sparsity?</a></li><li><a href="#6336">References</a></li><li><strong>Overfitting</strong>:</li></ol><p>Sometimes the machine learning model performs well with the training data but does not perform well with the test data. It means the model is not able to predict the output when dealing with unseen data by introducing noise in the output, and hence the model is called <strong>overfitting</strong>. Noise means the data points that do not represent the actual property of the data, but random chance.</p><p><strong>2. Overfitting Examples:</strong></p><p>In Image1, we are trying to fit a model on regression data. We can use one of the linear, quadratic, and polynomial function while fitting a regression model. Many times a linear regression model may under fits the data while a quadratic function form may provide a better fit. To derive a greater performance of fit, we can use a polynomial function which will fit the data very closely. While polynomial function fitting may appear a great model for this dataset, but if we change the dataset, the same model may turn out to be a poor fit for the new data (i.e. high variance). This is because the polynomial function fits the model so close to the original data that it does not generalizable across other similar data, which would result in overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*-poKs3os-lmYNMngeNQoag.png" /><figcaption>Image1: Under fit — Linear function(Left), Just Right — Quadratic function (Center), Overfit — Polynomial function (Right) fitting to the regression data</figcaption></figure><p>In Image2, when we try to fit a model on classification data. Linear function would be too simple to explain variance in the data and hence result in Under fit. Quadratic function form may result in an appropriate fit. The polynomial function form would predict too good to be true, and it might fail to perform well on unseen data and result in overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*buid3HxLpewddlS0lGZNFg.png" /><figcaption>Image2: Under fit-linear function(Left), Just Right-quadratic function(Center), Overfit-polynomial function(Right) fitting on classification data</figcaption></figure><p><strong>3. How to overcome Overfitting?</strong></p><p>One way is to reduce the number of features in the model. But doing so would result in loss of information, and thus the model will not have the benefit of all the information (provided by features) that is available.</p><p>When we have a lot of features and each feature contributes a bit to predict, we can’t remove the features. In this case, the solution is Regularization. Our model needs to be robust to perform well on both train and test data. For that, we try to:</p><ul><li><strong>Shrink the coefficient</strong> (or weight or parameter θ) of the features in the model</li><li><strong>Getting rid of high degree polynomial features</strong> from the model</li></ul><p>The above solution would result in a simpler hypothesis and be less prone to overfitting. This can be achieved using <strong>Regularization</strong>. This technique discourages the learning of a more complex or flexible model, to avoid the risk of overfitting.</p><p><strong>4. What parameters (θ’s) to penalize?</strong></p><p>Now we know that in the Regularization technique we reduce the magnitude/value of features (called θ’s) and penalize/ reduce the impact of higher-degree polynomial terms of features. But we don’t know which parameters (θ’s) are high order degree polynomial terms. So in Regularization, we are going to modify the cost function to shrink all the parameters (θ’s).</p><p><strong>5. Regularization:</strong></p><p>It is a technique to prevent the model from overfitting by adding extra information to it. During Regularization, the predicted output function does not change. The change is only in the cost function.</p><p>The cost function of Linear Regression which is called Residual Sum of Square (RSS) is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*qwHznGEFEBFWMaOgyyBcbQ.png" /></figure><p>Based on the training data, RSS will adjust the coefficient θs to minimize the cost function using Gradient Descent (or other optimization techniques). If there is noise in the training data, the model will not be able to generalize well to the future unseen data and will overfit. Here, Regularization comes into the picture and shrinks these coefficients to zero.</p><p><strong>6. Types of Regularization:</strong></p><p>Regularization could be of types:</p><blockquote>L1 Norm or Lasso Regression</blockquote><blockquote>L2 Norm or Ridge Regression</blockquote><ul><li><strong>L1-Lasso Regression</strong> helps to reduce the overfitting in the model as well as feature selection. The L1 penalty forces some coefficient estimates to be exactly equal to zero, which means there is complete removal of some features for model evaluation when the tuning parameter lambda (λ) is sufficiently large. Therefore, the lasso method also performs <strong>feature selection</strong> and is said to yield <strong>sparse models</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DK-qVzKwL8wWiDmU8c0hQ.png" /></figure><ul><li><strong>L2-Ridge Regression</strong> is mostly used to reduce the overfitting in the model, and it includes all the features present in the model. It reduces the complexity of the model by shrinking the coefficients. The cost function is altered by adding the penalty term (shrinkage term), which multiplies the lambda (λ) with the squared weight (θi) of each individual feature. The penalty term regularizes the coefficients of the model, and hence ridge regression reduces the magnitudes of the coefficients that help to decrease the complexity of the model. The cost function becomes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHCzFJsOpVHaQw8ow0ZbrA.png" /></figure><p><strong>λ </strong>is the regularization parameter, which decides how much to penalize the flexibility of the model. If the model is highly flexible which means the variance of the model is very high, and it changes with a small amount of change in the data → coefficient of the model would be larger. But in order to minimize the cost function (with regularization), these coefficient values should be less. That’s how Ridge Regularization prevents the coefficient values from rising too high.</p><p>Here we are not penalizing θ0 and penalty is starting from θ1, in practice it makes very little difference in the final result, so by convention, we only penalize coefficient starting from θ1 till θp.</p><p>When <strong>λ = 0, </strong>Ridge Regularization will not do any regularization, the model will remain overfitting and with high variance.</p><p>When <strong>λ is very large → infinity </strong>→ loss term is diminished → the training data does not participate in the optimization → we are just optimizing for the regularization term, the cost function is minimized when θ1, θ2, …, θp all = 0 → cost function remains only with bias term-b → results in linear model → <strong>Under fit</strong> → <strong>High Bias</strong></p><p>Selecting the good value of <strong>λ </strong>is critical, the selection is done using cross-validation.</p><p><strong>7. Regularization Parameter λ:</strong></p><p>λ is a regularization parameter that controls overfitting, and It&#39;s the tradeoff between 2 terms:</p><ul><li>Fitting training dataset well</li><li>Keeping parameters θ’s small and keeping hypothesis simple to avoid overfitting</li></ul><p><strong>8. Why L1 creates Sparsity?</strong></p><p>With a sparse model, we think of a model where many of the weights /coefficients (θ’s) are 0. Let us therefore reason about how L1 is more likely to create 0 weights. If we compare the cost function (with regularization term) for L2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*bCxjdzXn02Po68BDonDOAA.png" /><figcaption>Cost Function in case of L2</figcaption></figure><p>and L1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*HIguu734kQ9bCFgseI_Xhg.png" /><figcaption>Cost function in case of L1</figcaption></figure><p>In optimization formulation for comparison, Loss and λ can be ignored as they are the same for both L1 and L2 regularization. So we end up comparing below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWIaH7rir-XDUBGHxliABQ.png" /><figcaption>L2 and L1 norms</figcaption></figure><p>which are of shown diagrammatically as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*72SxQ2V-wX9rsxltcmQCIA.png" /><figcaption>L2 and L1 norm</figcaption></figure><p>Derivative of L2 and L2 is represented as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*W5qKZkgP9aGmrO3LlrxHnw.png" /></figure><p>Weight updates for both L2 and L1 is given by below formula of Gradient Descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*wls4oFYpZUbLyrvCdsR5MQ.png" /><figcaption>Weight update using Gradient Descent with learning rate (<em>α)</em></figcaption></figure><p>Let θ1 is positive (similarly can we can do for negative θ1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*_gCQ0bxWLWBPxLuk_b8PHg.png" /></figure><p>L2 updates occurs less when compared to L1 updates as we reach closer to optimum. That is, the rate of convergence decreases because in L2 regularization we have 2 * θ1 *<em>α</em>, which is less than <em>α</em>. L2 doesn’t change the value of θ1 from one iteration to another. L1 regularization continues to constantly reduce θ1 towards θ1 = 0. This happens because L1 derivative is constant and L2 derivative is not constant. The chance of weights reaching 0 is more for L1 regularization, as the derivative is constant and independent of the previous weight value. L2 regularization has derivatives reducing as the derivative is dependent on the previous iteration weight value, which is converging to optimal.</p><p><strong>9. References:</strong></p><p>[1] <a href="https://stats.stackexchange.com/questions/45643/why-l1-norm-for-sparse-models">https://stats.stackexchange.com/questions/45643/why-l1-norm-for-sparse-models</a></p><p>[2] <a href="https://www.youtube.com/watch?v=Xm2C_gTAl8c">https://www.youtube.com/watch?v=Xm2C_gTAl8c</a></p><p>[3] <a href="https://www.youtube.com/watch?v=IXPgm1e0IOo">https://www.youtube.com/watch?v=IXPgm1e0IOo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7445c3166cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression-python implementation from scratch without using sklearn]]></title>
            <link>https://heena-sharma.medium.com/logistic-regression-python-implementation-from-scratch-without-using-sklearn-d3fca7d3dae7?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3fca7d3dae7</guid>
            <category><![CDATA[stochastic-gradient]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[python-implementation]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 10:58:43 GMT</pubDate>
            <atom:updated>2022-07-06T14:30:38.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*HXBl0POqACJ_qZ0C.png" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#do7d">Generate data</a></li><li><a href="#d2d1">Split data into the train (75%) and test (25%)</a></li><li><a href="#b6db">Standardize the data</a></li><li><a href="#4dba">Initialize the weight_vector and intercept</a></li><li><a href="#241f">Compute Sigmoid</a></li><li><a href="#c461">Compute Log Loss</a></li><li><a href="#3092">Calculate Gradient w.r.t. ‘w’</a></li><li><a href="#377c">Calculate Gradient w.r.t. ‘b’</a></li><li><a href="#808a">Train the custom model</a></li><li><a href="#d257">Compare custom model with sklearn SGDClassifier model</a></li><li><a href="#fc0b">End Notes</a></li><li><a href="#130f">References</a></li></ol><p>In my previous <a href="https://medium.com/@heena.sharma.iiitb/logistic-regression-7773c76522d6">article</a>, I explained Logistic Regression concepts, please go through it if you want to know the theory behind it. In this article, I will cover the python implementation of Logistic Regression with L2 regularization using SGD (Stochastic Gradient Descent) without using sklearn library and compare the result with the sklearn library SGDClassifier.</p><p>Let’s get started with python implementation. Below are the steps:</p><p><strong>1</strong>. <strong>Generate data</strong>: First, we use sklearn.datasets.make_classification to generate n_class (2 classes in our case) classification dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d33c769dd939e88f22f35191ffdbf3/href">https://medium.com/media/77d33c769dd939e88f22f35191ffdbf3/href</a></iframe><p><strong>2</strong>. <strong>Split data into train (75%) and test (25%)</strong>: using sklearn.model_selection.train_test_split</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4244509067d45230c8197bb02d8233f4/href">https://medium.com/media/4244509067d45230c8197bb02d8233f4/href</a></iframe><p><strong>3. Standardize the data:</strong> using sklearn.preprocessing.StandardScaler. StandardScaler Standardize features by removing the mean and scaling to unit variance. The standard score of a sample x is calculated as: z = (x — u) / s. Where u is the mean of the training samples and s is the standard deviation of the training samples</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dba9d3f650cb7552b8dd0d836d1c749/href">https://medium.com/media/1dba9d3f650cb7552b8dd0d836d1c749/href</a></iframe><p><strong>4.</strong> <strong>Initialize the weight_vector and intercept</strong> term to zeros:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42826431aa041e90200486d0c3aeac17/href">https://medium.com/media/42826431aa041e90200486d0c3aeac17/href</a></iframe><p><strong>5.</strong> <strong>Compute Sigmoid</strong>: Sigmoid(z) = 1/(1 + exp^-z):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dabd7d88558154905c7e74bfd0851e2/href">https://medium.com/media/5dabd7d88558154905c7e74bfd0851e2/href</a></iframe><p><strong>6.</strong> <strong>Compute Log Loss </strong>using below formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*CRYCD0ymhrH-TdUAIaLuHQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f3a671c317a8296ac1ebf2b8c47f2e/href">https://medium.com/media/03f3a671c317a8296ac1ebf2b8c47f2e/href</a></iframe><p><strong>7. Calculate Gradient w.r.t. ‘w’</strong>: We now examine the Gradient arising from a single data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*jU2AW52D1G-7QjgrhDmccg.png" /></figure><p>There are two below good identities to know about the logistic function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hbfmx7GiDJf296yRLlscg.png" /></figure><p>We can use the above identities to get an intuitive form for the gradient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeXJpKy3ITFwK9pe9wyTOA.png" /><figcaption>gradient w.r.t. ‘w’</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb49bc28923a24e9336ff419db21951/href">https://medium.com/media/feb49bc28923a24e9336ff419db21951/href</a></iframe><p><strong>8. Now compute gradient with respect to ‘b’:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9y9p1gM-Xdwf1OrvjTJAA.png" /><figcaption>Gradient w.r.t. ‘b’</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bafa5537f943d415c43e404380189c18/href">https://medium.com/media/bafa5537f943d415c43e404380189c18/href</a></iframe><p><strong>9.</strong> <strong>Train the custom model: </strong>using the below steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Wj_tSnxCBCGjvXMYt1XNQ.png" /></figure><p>Lambda (λ) is the regularization parameter. Please check the <a href="https://medium.com/@heena.sharma.iiitb/regularization-in-machine-learning-e7445c3166cd">link</a> to get more idea about the λ parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95d26304b4189f96efd85f656265160f/href">https://medium.com/media/95d26304b4189f96efd85f656265160f/href</a></iframe><p>We train the model with the below parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f38a0700583278db4849b06f6d4b617/href">https://medium.com/media/3f38a0700583278db4849b06f6d4b617/href</a></iframe><p>Let’s print the weight w, intercept b, train, and test log loss values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7228d87e89168331fb1cf28fbfaad9cc/href">https://medium.com/media/7228d87e89168331fb1cf28fbfaad9cc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTPzCXuAHWtwn-_uYlNNIg.png" /><figcaption>The output of the custom model</figcaption></figure><p><strong>10. Compare custom model with sklearn SGDClassifier model:</strong> Now let’s compare these values with sklearn library if they are same or different:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/707ebb2c08a53c1f5c142fe61fe921bb/href">https://medium.com/media/707ebb2c08a53c1f5c142fe61fe921bb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxUuEYgp_98oKKtcYexwDg.png" /><figcaption>sklearn SGDClassifier output for intercept b and weight w</figcaption></figure><p>We can see that values of weight and intercept are more or less the same.</p><p><strong>11. End Notes:</strong></p><p>For full code please refer to my <a href="https://github.com/heena-sharma-sys/Machine-Learning/blob/main/Blog/LogisticRegressionFromScratch.ipynb">GitHub</a> link.</p><p><strong>12. References:</strong></p><p>[1] <a href="https://drive.google.com/file/d/1nQ08-XY4zvOLzRX-lGf8EYB5arb7-m1H/view">https://drive.google.com/file/d/1nQ08-XY4zvOLzRX-lGf8EYB5arb7-m1H/view</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3fca7d3dae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://heena-sharma.medium.com/logistic-regression-7773c76522d6?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7773c76522d6</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[predicted-probability]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[corrected-probability]]></category>
            <category><![CDATA[log-loss]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 10:54:34 GMT</pubDate>
            <atom:updated>2022-01-05T06:48:41.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpcK-yqyF_08lqwh.jpg" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#6e82">Introduction</a></li><li><a href="#bc8e">Use of Linear Regression for classification issue</a></li><li><a href="#8bcd">Why Logistic Regression has term Regression in it</a></li><li><a href="#3661">The cost function for Logistic Regression</a></li><li><a href="#eb96">Log Loss with example</a></li><li><a href="#4e1d">Log Loss cost function for Logistic Regression</a></li><li><a href="#9215">End Notes</a></li><li><a href="#c5fd">References</a></li><li><strong>Introduction:</strong></li></ol><p>Logistic Regression is one of the most popular statistical models which is used for classification. It comes under a supervised machine learning model, which learns from the labeled data (i.e. given input and output for training).</p><p>Logistic Regression can be used to do either <strong>Binary</strong> (with 2 classes, for example, pass/fail, spam/not-spam) classification or <strong>Multi-Class</strong> (with 3 or more classes, example Food texture: Crunchy, Mushy, Crispy or Income level: low income, middle income, high income) classification.</p><p>In this article, I will focus on binary classification using Logistic Regression.</p><p><strong>2. Use of Linear Regression for classification issue:</strong></p><p>You might be thinking, why can’t we use Linear Regression for classification issues as well?</p><p>Let’s consider an example where x: age and y: owns a house or not. This is a classification problem in which we need to predict whether a person owns a house or not based on his age.</p><p>Can we use Linear Regression in such a classification problem?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*N1Yfax38Pb7pBK_NiMACTA.png" /><figcaption>Age vs owns a house dataset</figcaption></figure><p>Let’s use Linear Regression to separate the data into 2 groups with thresholds. All the data points below the threshold (0.5) will be classified as not owning the house, and all data points above the threshold (0.5) will be classified as owning the house.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*bdJkXxlWbnKJaQXjLIjV5g.png" /><figcaption>Linear Regression on Classification data</figcaption></figure><p>Is the above solution working correctly or not, let’s test with some scenarios:</p><ol><li>Suppose we got some new data-point on the extreme right side, suddenly we see that the slope of the line changes and which changes the threshold of the model. So this is the issue that our threshold of Age can not be changed in a predicting algorithm.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*VrYhvogoA7igRX0yHw4sUQ.png" /><figcaption>Effect of outliers in Linear Regression</figcaption></figure><p>2. The second issue with applying Linear Regression to classification issues is that when we extend the linear regression line, it gives values more than 1 or less than 0, and we don’t know what does values are greater than 1 and smaller than 0 means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*GOD1fcoYeOCUw0Dv4W75rA.png" /><figcaption>No boundary in the linear regression line</figcaption></figure><p><strong>3.</strong> <strong>Why Logistic Regression has term Regression in it:</strong></p><p>Logistic regression is a generalized linear model and it uses the same basic formula of linear regression. Even though the name suggests regression, but Logistic Regression is a classification model, because the underlying assumption for Linear Regression and Logistic Regression is the same. We need a squashing function that can convert the continuous values into 1, 0. And which is not affected by outliers. For which, we use Logistic or Sigmoid function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*qDbhe28_MpXHfofInEvROg.png" /><figcaption>Linear line and sigmoid curve to fit data</figcaption></figure><p><strong>4. The cost function for Logistic Regression:</strong></p><p>For Linear Regression, the cost function we use is the Mean Squared Error, which is the average of the summation of the square of the difference between predicted(ŷi) and the actual(yi) values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*YCeneuFnP6DnecAGDUFl1Q.png" /><figcaption>Linear Regression cost function: Least Square Error</figcaption></figure><p>This is a continous and convex function as shown below, and it can be optimized using the Gradient Descent algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Y9V13DtckOsNVRnt7IV0rg.png" /><figcaption>Convex cost function</figcaption></figure><p>In Logistic Regression the optimization function Q(z) is a nonlinear function(Q(z)=1​/1+ e-z), if we put this in the above Mean Squared Error equation, it will give a non-convex function.</p><p>If we try to use the cost function of the linear regression in Logistic Regression then it would be of no use as it would end up being a <strong>non-convex</strong> function with multiple local minimas, in which it would be very difficult to minimize the cost value and find the global minimum using Gradient Descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*y2rpM-K06U7bPCEtYXA2sw.png" /><figcaption>Non-convex cost function</figcaption></figure><p>Hence, we use different cost functions for Logistic Regression, which is <strong>Log Loss </strong>or<strong> Binary Cross Entropy</strong>.</p><p><strong>5. Log Loss with an example:</strong></p><p>Below are the 3 steps to find Log Loss:</p><ol><li>Find corrected probabilities</li><li>Take a log of corrected probabilities</li><li>Take the negative average of the values we get in the 2nd step</li></ol><p>Log Loss is the negative average of the log of corrected predicted probabilities for each instance in the dataset.</p><p>By default, the output of the logistics regression model is the probability of the sample being positive (or class 1), for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*koo-nbcESK9aUpkc7RwbTQ.png" /><figcaption>Example: Logistic Regression, Input: X, output: y</figcaption></figure><p><strong>Step1: Calculate Corrected Probabilities:</strong></p><p>If the actual class is 1, the corrected probability will be the same as the predicted probability otherwise, it would be (1 - predicted) probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*IvR7XthsTn1N_Bnhm9IdFg.png" /></figure><p><strong>Step2: Calculate the log of corrected probabilities for each row:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*7AiOk07gBqDXIiji62-vVA.png" /></figure><p><strong>Step3: Take the negative average of the values we get in the 2nd step</strong> using the below formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*pE1lDbNDrzyRQR9rKtK9GQ.png" /><figcaption>Log loss with n: #training dataset</figcaption></figure><p>Log values are negative, so to handle a negative sign, we take the<strong> </strong>negative average of these values to maintain a common convention that <strong>lower loss scores are better</strong>.</p><p><strong>6. Log Loss cost function for Logistic Regression:</strong></p><p>Intuitively, we want to assign more punishment when predicting 1 while the actual is 0 and when predicting 0 while the actual is 1. The same thing happened in the log loss function. Below is the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CRYCD0ymhrH-TdUAIaLuHQ.png" /><figcaption>Log Loss or Binary Cross-Entropy</figcaption></figure><blockquote>When the actual class (y) = 1, second term in the formula would be 0</blockquote><blockquote>When the actual class (y) = 0, first term in the formula would be 0</blockquote><p>In the below diagram left side, when the actual class (y) = 1 and the predicted probability (ŷ) is close to 1, the loss is less and when the predicted probability (ŷ) is close to 0, the loss approaches infinity.</p><p>In the diagram right side, when the actual class (y) = 0, and the predicted probability (ŷ) is close to 0, the loss is less and when the predicted probability (ŷ) is close to 1, the loss approaches to infinity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*0ivCf4oEz9v58PMj_7D0JA.png" /></figure><p><strong>7. End Notes:</strong></p><p>Please check my next blog for more details on the practical implementation of <a href="https://medium.com/@heena.sharma.iiitb/logistic-regression-from-scratch-without-using-sklearn-d3fca7d3dae7">Logistic Regression from scratch without using sklearn</a>, that would give you more understanding of how this model actually works.</p><p><strong>8. References:</strong></p><p>[1] <a href="https://www.youtube.com/watch?v=jrgaI-0mRbE">https://www.youtube.com/watch?v=jrgaI-0mRbE</a></p><p>[2] <a href="https://www.youtube.com/watch?v=HIQlmHxI6-0">https://www.youtube.com/watch?v=HIQlmHxI6-0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7773c76522d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression on Boston House Pricing dataset using python]]></title>
            <link>https://heena-sharma.medium.com/linear-regression-on-boston-house-pricing-dataset-using-python-ef1148c52c4e?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1148c52c4e</guid>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[boston-housing]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 05:02:39 GMT</pubDate>
            <atom:updated>2022-07-06T14:27:20.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*L8uvjPbf-jhJLeFz" /><figcaption>Source: Google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#4cba">Introduction</a></li><li><a href="#ceee">Assumption in Linear Regression</a></li><li><a href="#38a5">Hypothesis</a></li><li><a href="#5642">Cost Function</a></li><li><a href="#e091">Gradient descent</a></li><li><a href="#faab">Role of derivative term and learning rate</a></li><li><a href="#0a3c">Python example of Linear Regression using Boston House pricing dataset</a></li><li><a href="#c2d2">References</a></li></ol><p>In my previous <a href="https://medium.com/@heena.sharma.iiitb/linear-regression-4b73db5aad62">article</a>, I explained Linear Regression concepts. Please go through it if you want to know the theory behind Linear Regression. In this article, I will mainly focus on the python implementation of Linear Regression on the Boston House pricing dataset.</p><ol><li><strong>Introduction:</strong></li></ol><p>Linear Regression is all about finding an equation of a line(in 2-d)/plane (in 3-d)/hyperplane (in n-d) that almost fits the given data so that it can predict the future (unseen) values.</p><p><strong>2. Assumptions in Linear Regression:</strong></p><p>Regression is a parametric approach, which makes it restrictive in nature. So data should fulfill certain assumptions in order to deliver good results using Linear regression. These assumptions are:</p><ol><li>There should be a <strong>Linear and Additive relationship</strong> between dependent (output: y) and independent (inputs: X’s) variables. The linear relationship creates a straight line when plotted on a graph. An additive relationship means that the effect of X’s on y is independent of other variables.</li><li>There should be <strong>no correlation</strong> between the error or residual terms. The absence of this phenomenon is known as Autocorrelation.</li><li>The independent (X’s) variables should not be correlated, the absence of phenomena is called multi-collinearity.</li><li>The error term must have<strong> constant variance</strong>. The phenomenon is known as homoskedasticity. The presence of non-constant variance is referred to as heteroskedasticity.</li><li>The error term must be <strong>normally distributed</strong>.</li></ol><p><strong>3. Hypothesis:</strong></p><p>Hypothesis in Linear Regression is the equation of a line/plane/hyperplane that fits the data. Basically, the hypothesis mapping input features to the output value. By using the equation of the line (in 2-d) (y=c + m.x) our hypothesis will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*BN4-S-bTTWxH0YzEr5DW1w.png" /><figcaption>Linear Regression Hypothesis</figcaption></figure><p>Here the question is, how do we select the optimal values of θ₀<em> </em>and<em> </em>θ₁, because based on different values of θ’s, a different hypothesis is formed, and we get a different line that fits the data. Which line is the best?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*eV4Ezq8jvt3WmC5p2d58YQ.png" /><figcaption>Different hypotheses based on different values of θ’s</figcaption></figure><p>So we select θ₀<em> </em>and<em> </em>θ₁, such that hypothesis h(x) or the predicted value is close to the actual value y in the training dataset (xi, yi).</p><p><strong>4. Cost Function:</strong></p><p>The cost function (or loss function) is used to measure the performance of a machine learning model or quantifies the error between the actual values and the values predicted by our hypothetical function. The cost function J for Linear Regression is represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*K5ZSzM7zN8bte7zDI7kh5Q.png" /><figcaption>The cost function of Linear Regression</figcaption></figure><p>Cost function J is the summation of the square of the difference between predicted and actual values, this method is called the <strong>Least square method</strong>.</p><p>Linear Regression tries to minimize this cost function by finding the optimal values of θ₀<em> </em>and<em> </em>θ₁<em>. </em>How? By using techniques like <strong>Gradient Descen</strong>t (GD) or <strong>Stochastic Gradient Descent</strong> (SGD) or <strong>mini-batch SGD</strong>. But in this article, we focus only on Gradient Descent.</p><p><strong>5. Gradient Descent (GD):</strong></p><p>GD is an iterative algorithm, in which we initially make a guess on the solution, and we move towards the solution iteratively through solution correction. Gradient descent is an optimization algorithm that follows the negative gradient of an objective function in order to locate the minimum of the function. It is widely used, from Linear Regression to Neural Networks. Below are the steps of GD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*LFpQyLEXewfOPa8TCSXqAw.png" /><figcaption>Gradient Descent Algorithm with m: training dataset size</figcaption></figure><p>Let’s understand what 2 terms learning rate (<em>α)</em> and derivative terms actually doing?</p><p><strong>6. Role of derivative term and learning rate:</strong></p><p>Consider cost function J(θ₁) with only 1 parameter, θ₀ is 0 means line passing through the origin. Let θ₁ is initialized as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*dnDYSR8oDxo-6jqh_wo37A.png" /></figure><p>θ₁ is updated using below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*0kEVbpgBo0Y5XLLeso6-0g.png" /><figcaption>Weight update</figcaption></figure><p>Update in θ₁ is done by subtracting the derivative of the cost function with respect to the θ₁ multiplied by some constant. A derivative is the slope of the cost function at the given point θ₁. In this case, the slope at θ₁ is positive, and hence the θ₁ is subtracted with a positive value, which will force the θ₁ to move (next update) in the left direction (towards minima, where slope = 0).</p><p>Here comes the role of <strong>learning rate or <em>α</em></strong>. It is the learning rate that decides <strong>how much we want to descent in one iteration</strong>. Also, as we are moving to the minimum, the slope of the curve is also getting less steep than the means, as we are reaching the minimum value, we will be taking smaller and smaller steps.</p><p><strong>Learning rate</strong> gives the rate of speed with which the gradient moves during gradient descent. Setting it too high would make your path unstable, too low would make convergence slow. Putting it to zero means your model isn’t learning anything from the gradients.</p><p>Now, let&#39;s consider θ₁ is initialized on the left side of the minima as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*NtdVAoRU9_1VfIO2lY28IQ.png" /></figure><p>The slope at this point will be negative and hence we are updating θ₁ by subtracting the negative value, which means we are adding some value to the weight which forces θ₁ to move towards the right (towards minima, where slope = 0).</p><p><strong>7. Python example of Linear Regression using Boston House pricing dataset:</strong></p><p>Boston House pricing Dataset was originally part of the UCI Machine Learning Repository and has been removed now. This data also comes with the Scikit-learn library. There are 506 samples and 13 feature variables in this dataset. The objective is to predict the value of prices of the house using the given features.</p><p>Let&#39;s get started, first we load the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b75be09eb898cba82e1696dfcc78be31/href">https://medium.com/media/b75be09eb898cba82e1696dfcc78be31/href</a></iframe><p>Let’s check what values in boston_dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e6b8b142d59fa1bcdeee7ef37c4c68/href">https://medium.com/media/c0e6b8b142d59fa1bcdeee7ef37c4c68/href</a></iframe><p>which gives below keys:</p><ul><li><strong><em>data</em></strong>: contains the information for various houses</li><li><strong><em>target</em></strong>: prices of the house</li><li><strong><em>feature_names</em></strong>: names of the features</li><li><strong><em>DESCR</em></strong>: describes the dataset</li></ul><p>boston_dataset.DESCR gives below, description of the dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3bedc670a6d625317eb84a81ff738d8/href">https://medium.com/media/a3bedc670a6d625317eb84a81ff738d8/href</a></iframe><p>The prices of the house indicated by the variable MEDV is our <strong>target variable (y),</strong> and the remaining are the <strong>feature variables (X) </strong>based on which we will predict the value of a house.</p><p>We will now load the data into a pandas data frame using pd.DataFrame</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/186f3b6a0d1964e5995f79091b3c777e/href">https://medium.com/media/186f3b6a0d1964e5995f79091b3c777e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*an9D9lHrR8miwHwjssN5Ug.png" /><figcaption>boston.head()</figcaption></figure><p>We can see that the target column is missing, let&#39;s add that using the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f11b5008d93b3b173a743aaf0bf23bc6/href">https://medium.com/media/f11b5008d93b3b173a743aaf0bf23bc6/href</a></iframe><p>Let’s do the <strong>data Pre-processing</strong> to check for any <strong>missing</strong> values in any of the columns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e87ec20e431bbaa0429e902e5b0f1bd4/href">https://medium.com/media/e87ec20e431bbaa0429e902e5b0f1bd4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/0*WtAhfeQlA4QnKRWk.png" /></figure><p>From the above output, we can see that there are <strong><em>no missing values</em></strong>.</p><p>In <strong>data visualization</strong> for the target variable MEDV using distplot from the seaborn library, let’s check how the distribution looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cddad14ed99e89408d1c537be48e5009/href">https://medium.com/media/cddad14ed99e89408d1c537be48e5009/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEZ8Uzwuf2As2IH2kTip2A.png" /></figure><p>From the above output, we can see that the target variable MEDV is distributed normally, with a few outliers.</p><p>Correlation is a statistical term describing <strong>the degree to which two variables move in coordination with one another</strong>. If the two variables move in the same direction, then those variables are said to have a <strong>positive correlation</strong>. If they move in opposite directions, then they have a <strong>negative correlation</strong>.</p><p>Now let’s check the <strong>correlation </strong>among different features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a78cea12bc217252f77c835c226786/href">https://medium.com/media/27a78cea12bc217252f77c835c226786/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VwgZ1E9cSvDEnIni1xOWQ.png" /><figcaption>Correlation matrix</figcaption></figure><p>From the above output, we can see that MEDV is positively correlated with RM(0.7) and MEDV is negatively correlated with LSTAT(-0.74).</p><p>Based on the above observation, we select RM and LSTAT as our features to predict MEDV. Let&#39;s create scatter plots for the selected features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e89fe14e88280c1eeac187c2da89ce2/href">https://medium.com/media/1e89fe14e88280c1eeac187c2da89ce2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*Wxkq_3qWLGRoG-CVThGrIA.png" /></figure><p>From the above plots, we can see that RM is following a linear relationship with MEDV but not LSTAT, we will select RM for training the linear regression model.</p><p>Now split the data into train and test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f4d219fbf83aae85114115319dc2b9/href">https://medium.com/media/e1f4d219fbf83aae85114115319dc2b9/href</a></iframe><p>Train the model using train data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87965948e7c0d3402c05b7e536b25801/href">https://medium.com/media/87965948e7c0d3402c05b7e536b25801/href</a></iframe><p><strong>Evaluation of the model</strong> for train and test data using <strong>RMSE</strong>, and <strong>R²</strong> matrices:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf5bff3a0f3c9c0ed285cdeb4b7ce4e/href">https://medium.com/media/ebf5bff3a0f3c9c0ed285cdeb4b7ce4e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*IE9bl-kP_Di6ZXgRIOtq4w.png" /></figure><p>For full code, please refer to the GitHub <a href="https://github.com/heena-sharma-sys/Machine-Learning/blob/main/Blog/LinearRegressionOnBostonHousePriceDataset.ipynb">link</a>.</p><p><strong>8. References:</strong></p><p>[1] <a href="https://www.youtube.com/watch?v=kHwlB_j7Hkc&amp;list=PLJs7lEb1U5pYnrI0Wn4mzPmppVqwERL_4">https://www.youtube.com/watch?v=kHwlB_j7Hkc&amp;list=PLJs7lEb1U5pYnrI0Wn4mzPmppVqwERL_4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1148c52c4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression]]></title>
            <link>https://heena-sharma.medium.com/linear-regression-4b73db5aad62?source=rss-d1870691308d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b73db5aad62</guid>
            <category><![CDATA[multiple-vs-simple-lr]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[p-value]]></category>
            <category><![CDATA[r-squared]]></category>
            <dc:creator><![CDATA[Heena Sharma]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 06:27:30 GMT</pubDate>
            <atom:updated>2021-12-25T05:07:57.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*UNvSS6yGSeC_1JD3.png" /><figcaption>Source: google images</figcaption></figure><p>Table of contents:</p><ol><li><a href="#24ec">Introduction</a></li><li><a href="#931b">Steps in Linear Regression</a></li><li><a href="#ad9f">Fitting a line to data using the least square method</a></li><li><a href="#7424">Calculate R²</a></li><li><a href="#c5a3">Calculate p-value for R²</a></li><li><a href="#f20f">End Notes</a></li><li><a href="#be8b">References</a></li><li><strong>Introduction:</strong></li></ol><p>Linear Regression is a Supervised Machine learning model (where training data with the label is provided) which is used for Regression tasks (to predict the values within a continuous range. e.g. sales, price).</p><p>The aim of Linear Regression is to find a line (in 2-d)/plane (in 3-d)/hyperplane(in n-d) that best fits the data.</p><p>Linear Regression could be of 2 types:</p><ol><li><strong>Simple Linear Regression</strong>: there is only one independent variable for the model to find the relationship.</li><li><strong>Multiple Linear Regression:</strong> there are more than one independent variables for the model to find the relationship.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*a2qASAG3wLazV9ADVEmGbg.png" /><figcaption>Simple (left) Vs Multiple Linear Regression (right)</figcaption></figure><p>The linear Regression algorithm tries to learn the correct value for intercept and slope. At the end of the training, the model will approximate the line/plane/hyperplane that best fits the data.</p><p><strong>2. Steps in Linear Regression: </strong>below are the steps to follow in Linear Regression:</p><ol><li>Fitting a line(in 2-d)/plane (in 3-d)/hyperplane(in n-d) to the data using the Least Square method</li><li>Calculate R²</li><li>Calculate p-value for R²</li></ol><p>Let&#39;s discuss these steps one by one to understand how the Linear Regression model actually works. Here I am taking a simple example of 2-d data and trying to find an optimal line that best fits the data.</p><p><strong>3. Fitting a line to data using the least square method:</strong></p><p>How to determine what line fits the data best? We try with a basic line which is always predicting the mean value as output and also try multiple rotations of the mean line, each time we check how far the line is from data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-gAUP9ygAV9rAIuaL4JsQ.png" /><figcaption>Various rotations of a line</figcaption></figure><p>Below are the details 3 steps of least square or fitting the line to the data:</p><ol><li>Start with a line and calculate the sum of squared residuals, which is the sum of the square of the distance of each data point from the line:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jskZwmIkTyP269esuBea-w.png" /><figcaption>Sum of squared residuals</figcaption></figure><p>2. Now try a few more rotations of the line and calculate the sum of squared residuals.</p><p>3. Plot a graph between the <strong>sum of squared residuals</strong> vs different <strong>rotations </strong>of the line. Take the derivative of this function, the derivative tells us the slope of the function at every point. Optimal rotation is the one where slope=0. Thus, the technique is called the least square method, where we select the optimal line that gives the least sum of square residuals or least error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*jVrnR_EsnVZo4mbcu0g7Bw.png" /><figcaption>Line rotations Vs Sum of squared residuals</figcaption></figure><p>At the end of the least square method technique, we will get an optimal line that best fits the data. We can superimpose the data on the selected line.</p><p>Now the next step is to determine, how good is the guess we made using the best fit line. There are several matrices to evaluate the performance of the Regression model such as <strong>R²</strong>, <strong>Adjusted R²</strong>,<strong> Mean Squared Error (MSE)</strong>,<strong> Root Mean Squared Error (RMSE) </strong>but here in this blog we will use R².</p><p>R² is also known as the coefficient of determination, which basically quantifies how much better a line fits the data.</p><p><strong>4. Calculate R²:</strong></p><p>R² is the ratio of variation explained by the model to the total variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*lpruSPvnu-cmsY2P" /></figure><p><strong>R² value is between 0-1</strong>:</p><ul><li>0 represents a model that does not explain any of the variations in the response variable around its mean. The mean of the dependent variable predicts the dependent variable as well as the regression model.</li><li>1 represents a model that explains all the variations in the response variable around its mean.</li></ul><p><strong>R² value can also be negative</strong> in some cases, R² compares the fit of the chosen model with that of a horizontal (or mean) straight line (the null hypothesis). If the chosen model fits worse than a horizontal line, then R² is negative. Note that R² is not always the square of anything, so it can have a negative value without violating any rules of math. R² is negative only when the chosen model does not follow the trend of the data, so fits worse than a horizontal line.</p><p>In the below figure, let L2 is the regression line we got using the least square method, we can see that L2 fits data better than the mean, but how to quantify that using R²?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*_tQS0nR_U0fMfZDUMtjAjg.png" /><figcaption>L2: regression line</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*Rgn0WCMNqNTyynysfldMsQ.png" /></figure><p>Let variance (mean) =32, variance (L2) = 6</p><p>R² = variance(L1) — variance(L2) / variance(L1) = 32 — 6/32 = 0.81</p><p>There is 81% less variation around the L2 than mean, or the relationship between two variables (X, y) accounts for 81% of the variation.</p><p>Now, once we have R² calculated for our regression line, we need a way to <strong>determine if the R² value is statistically significant or not</strong>. What does statistically significant mean?</p><ul><li>Statistical significance is a determination made by an analyst that the results in the data are not explainable by chance alone.</li><li>Statistical <strong>hypothesis testing </strong>is the method by which the analyst makes this determination.</li><li>This test provides a <strong>p-value</strong>, which is the probability of observing results as extreme as those in the data, assuming the results are truly due to chance alone.</li><li>A p-value of 5% or lower is often considered to be statistically significant.</li></ul><p>Let’s see how to calculate the p-value for R². The null hypothesis in the case when determining p-value for R² would be that the selected line from the least squared method best fits the data (and obviously better than the mean line).</p><p><strong>5. Calculate p-value for R²:</strong></p><p>P-value is not probability value, but it is obtained by adding up probabilities. We can calculate the p-value for <strong>discrete</strong> and for <strong>continuous</strong> values as well. To calculate the p-value of discrete values we add up 3 probabilities:</p><ol><li>The probability that random chance would result in the observation</li><li>The probability of observing something else that is equally rare</li><li>The probability of observing something rarer or more extreme</li></ol><p><strong>Example</strong>: In an experiment of tossing a coin 2 times, sample space would be {HH, HT, TH, TT}, where H means heads and T means tails. Here, we assume that the coin is fair (which is our Null hypothesis H₀). The reason we calculate the p-value is to test our null hypothesis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*z1AcX6-7YcZJwHvjK7ZG0A.png" /><figcaption>p-value to decide the statistical significance</figcaption></figure><p>p-value for getting 2 heads would be:</p><p>p-value (2 heads) = probability(random chance would result in the observation like HH) + probability(observing something else that is equally rare like TT)+ probability(observing something rarer or more extreme)</p><p>p-value (2 heads) = p (HH) + p(TT equally rare as HH) + p(extreme rare observation than HH or TT) = 0.25 + 0.25 + 0 = 0.5</p><p>Here, the probability of getting 2 heads (0.25) and the p-value of getting 2 heads (0.5) is different. The p-value of getting 2 heads is greater than the threshold (0.05) so we fail to reject the Null Hypothesis and our coin is fair, not biased even after getting 2 Heads in a row.</p><p>Calculating p-value in the case of discrete values is easy because we can list all possible outcomes, but what about the case of <strong>continuous</strong> values, if we want to measure the p-value of how tall or short people are? In practice, we use statistical distribution in the case of continuous values, for example- Normal Distribution. Below is the distribution of height measurement of Indian women (of age 15–49 years) in 1990. The whole area under the below curve indicates the probability that a person’s height is within the range of possible values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*_J5NoK1tSXzMDhyE47P_UQ.png" /><figcaption>Height measurement of Indian women (15–49 years old) in 1990</figcaption></figure><p>To calculate the p-value of the distribution, we add up the percentage of area under the curve. Suppose, we want to calculate the p-value of someone who is 142 cm tall and our Null hypothesis (H₀) is that the same distribution (with an average of 155.5 cm) explains the height of 142 cm. We want to check if the 142 cm height is so far from the mean of the distribution that we reject the idea that it came from that distribution. For this, we calculate the p-value of someone who is 142 cm tall and if it is less than the threshold we can reject the Null hypothesis which means, there is some other distribution that explains the 142 cm tall height in a better way.</p><p><strong>Also, when we are working with a distribution, we are interested in adding more extreme value to the p-value rather than the rarer value</strong>.</p><p>p-value of someone who is 142 cm tall = 2.5% area of people ≤ 142 cm of height are extreme rare + 2.5% area of the people ≥ 169 cm height are also considered as extreme rare</p><p>= 2.5% + 2.5% = 5% = 0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*5nCX_W7yJoerQifrruA04Q.png" /></figure><p>The p-value of someone who is 142 cm tall is 0.05 which is equal to the threshold value, so we can’t decide to reject or fail to reject Null Hypothesis.</p><p>Let’s calculate p-value of someone who is 141 cm tall is: 0.016 + 0.016 = 0.032 &lt; 0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ydae7bE-w3IWRrSHt2a01A.png" /></figure><p>We can say that since the p-value of people with height 141 cm is smaller than the threshold, we reject the null hypothesis that it is explained by the original distribution, and It&#39;s special (not normal case) to measure someone with that small height and that suggests that a different distribution of heights make more sense. For example, the below green distribution makes more sense for height 141 cm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*MU3C_78ANYK_fZeJxRg7YA.png" /></figure><p><strong>6. End Notes:</strong></p><p>I have covered most of the concepts behind the Linear Regression model in this blog. If you wish to know about more the mathematics behind the model and see a practical implementation using python on the Boston House Pricing Dataset, check my <a href="https://medium.com/@heena.sharma.iiitb/linear-regression-on-boston-house-pricing-dataset-using-python-ef1148c52c4e">blog</a>.</p><p><strong>7. References:</strong></p><p>[1]. <a href="https://www.youtube.com/watch?v=PaFPbb66DxQ&amp;list=PLblh5JKOoLUIzaEkCLIUxQFjPIlapw8nU&amp;index=1">https://www.youtube.com/watch?v=PaFPbb66DxQ&amp;list=PLblh5JKOoLUIzaEkCLIUxQFjPIlapw8nU&amp;index=1</a></p><p>[2]. <a href="https://www.youtube.com/watch?v=nk2CQITm_eo&amp;list=PLblh5JKOoLUIzaEkCLIUxQFjPIlapw8nU&amp;index=2">https://www.youtube.com/watch?v=nk2CQITm_eo&amp;list=PLblh5JKOoLUIzaEkCLIUxQFjPIlapw8nU&amp;index=2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b73db5aad62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>