<?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 Anjali Sharma on Medium]]></title>
        <description><![CDATA[Stories by Anjali Sharma on Medium]]></description>
        <link>https://medium.com/@anjalisharma_47802?source=rss-552a2836d8fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P6u6xhHfFCJ8BjKhrIr3IQ.jpeg</url>
            <title>Stories by Anjali Sharma on Medium</title>
            <link>https://medium.com/@anjalisharma_47802?source=rss-552a2836d8fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:00:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anjalisharma_47802/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[How to handle leading, trailing, and multiple spaces between words]]></title>
            <link>https://medium.com/@anjalisharma_47802/how-to-handle-leading-trailing-and-multiple-spaces-between-words-06b4b18fb734?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/06b4b18fb734</guid>
            <category><![CDATA[string-manipulation]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 10:11:44 GMT</pubDate>
            <atom:updated>2026-11-02T10:13:19.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>I am currently practicing medium-level LeetCode problems based on the two-pointers technique.</p><p>I came across problems like <a href="https://leetcode.com/problems/reverse-words-in-a-string/">Reverse Words in a String</a> while removing leading and trailing spaces, as well as multiple spaces between words</p><p>Below is an example:</p><pre>Input: s = &quot;the sky is blue&quot;<br>Output: &quot;blue is sky the&quot;</pre><p>I understood this concept. It is a very simple problem, and we can reverse a string using [::-1]. However, I came across the following example, which helped me understand how to handle extra spaces between words.</p><pre>Input: s = &quot;a good   example&quot;<br>Output: &quot;example good a&quot;</pre><p>I need to remove multiple spaces between words and need to reverse it</p><p><strong>There is a split() function that automatically handles leading, trailing, and multiple spaces between words</strong></p><p>I have used the split function as below:</p><ol><li>I used the s.split() method to split the sentence into a list of individual words.</li></ol><p>[‘the’, ‘sky’, &#39;is&#39;, ‘blue’]</p><p>2. Then, I used [::-1], which reverses the list of words.</p><p>[&#39;blue&#39;, &#39;is&#39;, ‘sky’, ‘the’]</p><p>3. Next, I used the join() method to combine the words in the list and convert them back into a sentence, with exactly one space between each word.</p><p><strong>Below is the complete code</strong></p><p>class Solution:</p><p>def reverseWords(self, s: str) -&gt; str:</p><p>reverse_str = “ “.join(s.split()[::-1])</p><p>return reverse_str</p><p>Please try this approach; if you like, please applaud</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06b4b18fb734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a PDF Question-Answering RAG Application Using LangChain, Chroma, Hugging Face & Groq]]></title>
            <link>https://medium.com/@anjalisharma_47802/build-a-pdf-question-answering-rag-application-using-langchain-chroma-hugging-face-groq-a8511ff1ecf2?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8511ff1ecf2</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[rag-pipeline]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[first-rag-prject]]></category>
            <category><![CDATA[rag-beginner]]></category>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 06:26:37 GMT</pubDate>
            <atom:updated>2026-11-02T06:26:37.171Z</atom:updated>
            <content:encoded><![CDATA[<p>What is RAG:</p><p>RAG = Retrieval-Augmented Generation</p><p>A traditional LLM answers based on what it learned during training</p><p>Suppose I upload my company’s internal PDF, the LLM does not automatically know what is inside my PDF</p><p>RAG solves this problem by doing two things:</p><ol><li><strong>Retrieval</strong> : find relevant information from the document</li><li><strong>Generation</strong>: Give that information to LLM and ask it to generate an answer</li></ol><p>Question<br> ↓<br>Retrieve relevant document chunks<br> ↓<br>Send chunks + question to LLM<br> ↓<br>Generate answer</p><p><strong>3. Technologies used: </strong>I have used the technologies below to complete my RAG project</p><p>Python : Application development</p><p>Streamlit : User interface</p><p>LangChain : RAG orchestration</p><p>PyPDF : PDF text extraction</p><p>RecursiveCharacterTextSplitter : Text chunking</p><p>Hugging Face Embeddings: Convert text into vectors</p><p>Chroma: Vector database</p><p>Groq: LLM interface</p><p>Llama 3.3 70B: Answer Generation</p><p>The goal was to understand how a RAG pipeline works end-to-end rather than simply using an existing chatbot.</p><p><strong>The basic idea is simple</strong>:</p><blockquote><em>Instead of asking the LLM to answer a question only from its pretrained knowledge, we first retrieve relevant information from our own documents and provide that information to the LLM.</em></blockquote><p>The overall flow looks like this:</p><pre>PDF<br> ↓<br>Load Document<br> ↓<br>Split into Chunks<br> ↓<br>Generate Embeddings<br> ↓<br>Store in Chroma<br> ↓<br>User Question<br> ↓<br>Retrieve Relevant Chunks<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>This allows us to build applications that can answer questions based on our own data.</p><h3>Project Architecture</h3><h3>1. Document Ingestion</h3><p>When the user uploads a PDF:</p><pre>PDF<br> ↓<br>PyPDFLoader<br> ↓<br>Text Chunks<br> ↓<br>Hugging Face Embeddings<br> ↓<br>Chroma Vector Database</pre><h3>2. Question Answering</h3><p>When the user asks a question:</p><pre>User Question<br> ↓<br>Retriever<br> ↓<br>Relevant Document Chunks<br> ↓<br>Llama 3.3<br> ↓<br>Answer</pre><p><strong>Project setup</strong></p><p>This is my project Structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*TdkrIxM2xKweMQz10JUcOA.png" /></figure><p>app.py : -&gt; Streamlit UI</p><p>rag_utility.py : -&gt; RAG Pipeline</p><p>.env: -&gt; API Credentials</p><p>doc_vectorstore : -&gt; Chroma Vector Database</p><p><strong>6. Building the Streamlit Application</strong></p><p>I am uploading my code snippet as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*roXQmbGNWQU4RKSKhmJVnw.png" /></figure><p>I have imported the functions “process_document_to_chroma_db” and “answer_question” from the rag_utility.py file. created the working directory where the uploaded document will be saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*DuhOIPZM5regD0YJGMduUA.png" /></figure><p>Using st.file_uploader(), I uploaded the PDF and saved it locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*G67vwxg0CH8bTn8OR4Om2Q.png" /></figure><p>Created the text_area() where the user enters the question</p><p>7. <strong>Loading the PDF</strong></p><p>Imported the necessary Python packages and class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYhn6829MvqFHo3KzmP74A.png" /></figure><ul><li><strong>langchain_community</strong> → package</li><li><strong>document_loaders</strong> → module/package containing document loader classes</li><li><strong>UnstructuredPDFLoader</strong> → <strong>class</strong></li></ul><p>Similarly, RecursiveCharacterTextSplitter is used to split the document into smaller, manageable chunks.</p><p>Using the HuggingFaceEmbeddings class, we convert the text chunks into numerical vector representations called <strong>embeddings</strong>. These embeddings, along with the corresponding text chunks and metadata, are stored in a vector database. In this project, I have used <strong>Chroma</strong> as the vector database.</p><p>I imported the ChatGroq class from the langchain_groq Python package, which provides integration with <strong>Groq-hosted LLMs</strong>. I use it ChatGroq to interact with the selected LLM for generating responses based on the retrieved context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*SOWIn98CUqvm-O_-NTmrUw.png" /></figure><p>In my project, I used the <strong>llama-3.3-70b-versatile</strong> model through Groq to generate responses based on the context retrieved from the vector database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9ya06780ni32DRwaHdXJg.png" /></figure><p>Unstructured PDF Loader reads PDFs and converts their content into LangChain Document objects</p><p>We generally don’t send the entire PDF to the LLM. Instead, we divide the document into smaller pieces called chunks. And for that, I have RecursiveCharacterTextSplitter()</p><p>PDF<br>│<br>├── Chunk 1<br>├── Chunk 2<br>├── Chunk 3<br>├── Chunk 4<br>└── …</p><p>I have set chunk_size = 2000, which means each chunk can contain up to 2,000 characters. I have also setchunk_overlap = 500, which means 500 characters from the previous chunk are repeated in the next chunk. This overlap helps preserve context between consecutive chunks and reduces the risk of losing important information when the document is split.</p><p>Example:</p><p>Chunk 1:<br>A B C D E F G H I J</p><p>Chunk 2:<br>F G H I J K L M N O</p><p><strong>9. Creating embeddings</strong></p><p>embedding = HuggingFaceEmbeddings()</p><p>Computers cannot directly perform semantic similarity searches on normal text. Embedding models convert text into numerical vectors.</p><p>“How can I reset my password?”<br> ↓<br> Embedding Model<br> ↓<br>[0.12, -0.42, 0.73, …]</p><p><strong>10. Storing embeddings in Chroma:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*yvWnA2RAyk2YV1s2JcUQsA.png" /></figure><p>Chroma acts as a vector database. it stores the document chunks along with their vector representation so that we can perform similarity search</p><p>Document chunk<br> ↓<br>Embedding model<br> ↓<br>Vector<br> ↓<br>Chroma</p><p>Using the above code, we are storing embeddings into ChromaDB</p><p><strong>10. Question answering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*-XEjct4o6QOnb5H2uh4UBA.png" /></figure><p>The above code loads the existing database; then the code below converts the vector database into a retriever</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JPcdjmzEE7-vCLLuORIEXA.png" /></figure><p>The retriever’s job is to find the document chunks that are most relevant to the user’s question.</p><p><strong>11. Connecting the LLM</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*mOa1TE9j94ZygQAvYcY_zg.png" /></figure><p><strong>llm=llm</strong> → Uses your Llama 3.3 70B model to generate the answer.</p><p><strong>chain_type=&quot;stuff&quot;</strong> → Combines the retrieved chunks and sends them to the LLM as context.</p><p><strong>retriever=retriever</strong> → Retrieves relevant chunks from the Chroma vector database.</p><p><strong>return_source_documents=True</strong> → Also returns the source chunks used for the answer.</p><p>Sends the user’s question to the RAG chain. Extracts the final answer generated by the LLM.</p><p><strong>Question → Retrieve relevant PDF chunks → Send chunks + question to LLM → Generate answer.</strong></p><p>return_source_documents=True (this tells , Don’t return only the generated answer. Also keep the document chunks that were used to generate the answer.)</p><h3>Conclusion</h3><p>Building this PDF RAG application helped me understand how different GenAI components work together to create a practical application. From document loading and chunking to embeddings, vector storage, retrieval, and LLM-based response generation, I was able to understand the complete RAG workflow end-to-end.</p><p>This project also gave me a strong foundation to explore more advanced concepts such as <strong>hybrid search, reranking, query rewriting, RAG evaluation, and Agentic RAG</strong>.</p><p>For me, this project was not just about building a chatbot — it was about understanding what happens behind the scenes when an LLM answers questions using our own data.</p><p><strong>This is just the beginning of my journey into RAG and Generative AI.</strong></p><p>Below is my github link</p><p><a href="https://github.com/anjaleana/Streamlit-RAG-Based-Chatbot">https://github.com/anjaleana/Streamlit-RAG-Based-Chatbot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8511ff1ecf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is RAG (Retrieval-Augmented Generation)?]]></title>
            <link>https://medium.com/@anjalisharma_47802/what-is-rag-retrieval-augmented-generation-e519d6b27863?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e519d6b27863</guid>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 06:20:17 GMT</pubDate>
            <atom:updated>2026-09-25T06:20:17.408Z</atom:updated>
            <content:encoded><![CDATA[<p>We hear a lot about <strong>Generative AI</strong> and <strong>Large Language Models (LLMs)</strong> such as GPT, Gemini, and Llama.</p><p>But there is an important question</p><p>What if I want an AI application to answer questions using my own documents?</p><p>For example, I have a PDF containing company policies.</p><p>I ask:</p><p><em>“What is the company’s leave policy?”</em></p><p>A normal LLM may not know the information inside my private PDF.</p><p>This is where <strong>RAG</strong> comes in.RAG stands for Retrieval—Augmented Generation. In simple words, RAG allows an AI application to</p><p><strong>Find relevant information → Give it to the LLM → Generate an answer</strong></p><p>Instead of asking the LLM to answer everything from its existing knowledge, we first retrieve relevant information from an external knowledge source.</p><h3>A simple example</h3><p>Imagine you have 100 company documents.</p><p>An employee asks:</p><p><em>“How many days of parental leave are available?”</em></p><p>RAG system can:</p><ol><li>Search the company’s documents.</li><li>Find the relevant information.</li><li>Send that information to the LLM.</li><li>Generate an answer for the employee.</li></ol><p>So the basic idea is:</p><pre>User Question<br>      ↓<br>Search Relevant Information<br>      ↓<br>Retrieved Information<br>      ↓<br>LLM<br>      ↓<br>Answer</pre><h3>Why is RAG useful?</h3><p>RAG is particularly useful when an application needs to work with information that is <strong>outside the LLM’s original training data</strong>, such as:</p><ul><li>Company documents</li><li>Product documentation</li><li>PDFs</li><li>Internal knowledge bases</li><li>Customer support documents</li></ul><p>For example, instead of training an LLM whenever a new company document is added, we can add the document to our knowledge base and retrieve the relevant information when a user asks a question.</p><h3>RAG in one sentence</h3><p><strong>RAG gives an LLM access to relevant external information before generating an answer.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e519d6b27863" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between Generative AI And Descriminative AI]]></title>
            <link>https://medium.com/@anjalisharma_47802/difference-between-generative-ai-and-descriminative-ai-ae5ebb8d0731?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5ebb8d0731</guid>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 07:05:25 GMT</pubDate>
            <atom:updated>2024-03-20T07:05:25.832Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Difference between Generative AI And Descriminative AI</strong></p><p>As we know Artificial Intelligence is a trending topic in today’s era. Research is going on. We are having very powerful pre-trained models that we get as a robust model that works on a huge amount of data.</p><p>Coming to generative ai It’s a subset of Deep Learning. Generative ai is the type of AI that can create new contents such as images, videos, music, stories, conversation etc. It is powered by the foundation model which is a Large AI model such as GPT 3, GPT 3.5, GPT 4 , GPT 4.5 Llama, Bloom, Lamda etc. LLM is based on Transformer architecture.</p><p>There are some applications :</p><ol><li>Text to text generation.</li><li>Text to video generation.</li><li>Sentence completion.</li><li>Text Summarization.</li><li>Language Translation.</li></ol><p>LLM is a state -of- art model. We don’t need to train the model , we just use the api key from the openai platform and call the API to append the LLM model on our tasks.</p><p>The collection of tokens(words) which give as input to the LLM model is known as input prompt and in response, we get output prompt. The whole process is called prompt design.</p><p>Descriminative AI is a classical machine learning model that learns the boundary between different classes or categories in the datasets. They make predictions for unseen data based on conditional probability.</p><p>We need to feed structured data to model, do fine tuning, train the model and apply performance metrics to get good accuracy.</p><p>Real-world application of Descriminative AI:</p><ol><li>Sentiment analysis.</li><li>Spam detection.</li><li>Flight price prediction.</li><li>Credit card fraud detection.</li></ol><p>There are many classification and regression problems which are resolved by using the classical ML model. Descriminative models cannot generate new data.</p><p>If you like the post please subscribe and do like.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5ebb8d0731" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In this blog, we will discuss data analysis using the Pandas library and we will be using the car…]]></title>
            <link>https://medium.com/@anjalisharma_47802/in-this-blog-we-will-discuss-data-analysis-using-the-pandas-library-and-we-will-be-using-the-car-87fd184365ac?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/87fd184365ac</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-manipulation]]></category>
            <category><![CDATA[dataframes]]></category>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 12:52:28 GMT</pubDate>
            <atom:updated>2023-10-01T12:52:28.939Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will discuss data analysis using the Pandas library and we will be using the car dataset as below</p><p><a href="https://github.com/anjaleana/Pandas-and-Numpy-/blob/main/car_data.csv">Pandas-and-Numpy-/car_data.csv at main · anjaleana/Pandas-and-Numpy-</a></p><p>There are lists of questions that we have taken and implemented data analysis.</p><p><strong>Question1</strong>. Read the car data set CSV file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*DWLN-523WucxQ9LNm3Ys7g.png" /></figure><p><strong>Question 2</strong>: Find the total number of purchases for each gender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9W4WdAdNIZJKLwkZyyARQ.png" /></figure><p><strong>Description:</strong> We applied the ‘group by’ operation on the ‘Gender’ column to find the total number of purchased cars by males and females.</p><p><strong>Question 3</strong>: Find the total number of user IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*QfDZkRQeKrhCBHeAHPHbgw.png" /></figure><p><strong>Question 4: </strong>Find the user ID of the individual with the highest annual salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*yru_gWUBhsZnAfYvXclvhw.png" /></figure><p><strong>Question 5</strong>: Find the user ID of the individual with the lowest annual salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*ramtd_Ze6fk5-Ma9bWBmWQ.png" /></figure><p><strong>Question 6: </strong>Retrieve<strong> </strong>the records that were grouped by Age and apply the filter option to get user-id of the individual with an age is greater than 40.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*sd17VCo3L7hI8MrF-9CohA.png" /></figure><p><strong>Question 7: </strong>Determine the earnings ratio between males and females.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*nzwcOuvTYrKldWnhSNoyPA.png" /></figure><p><strong>Question 8: </strong>Convert the purchased status to ‘Yes’ or ‘No’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Z8WlKqh73yZ10e00JnsYgQ.png" /></figure><p>In conclusion, pandas is a powerful and versatile library for data analysis and data manipulation in Python. In this blog, we have explored some of its essential features, including data loading, cleaning, filtering, and aggregation.</p><p>If you like the Blogspot, please subscribe and share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87fd184365ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Confusion Matrix]]></title>
            <link>https://medium.com/@anjalisharma_47802/confusion-matrix-1eee9eace7c8?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eee9eace7c8</guid>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 09:36:57 GMT</pubDate>
            <atom:updated>2022-07-17T15:58:21.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*fCyQ2emPq5_l6y1X6s7EVA.png" /></figure><p>Yes, of course, the confusion matrix makes us confused. But It is a very important part while building the machine learning model. When we get the data, first we do preprocessing, clean the data, and do Exploratory Data Analysis. Using sklearn.model_selection doing train-test split(). To know how effective the model works, the confusion matrix comes into the picture.</p><p><strong>Let’s cover the following contents</strong></p><ol><li>What is a Confusion Matrix?</li><li>How to calculate confusion matrix for 2-class classification problem.</li><li>Precision, Recall, Accuracy, and F1-score.</li></ol><p><strong>Confusion Matrix:</strong></p><p>It is a performance measurement for a Machine learning classification problem which is having two or more dependent variables.</p><p>Let’s take the example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*5uZwIsfCUt0Rb9LYJ53yKQ.jpeg" /></figure><p>TP = True Positive, FN = False Negative, FP = False Positive , TN = True Negative.</p><p><strong>2. How to calculate the confusion matrix for a 2-class classification problem?</strong></p><p>There are two ways of calculating the confusion Matrix:</p><ol><li>From scratch, we can calculate the confusion matrix.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut3YThrzyymI_WhuRZTGZQ.png" /></figure><p>2. Using sklearn.metrics import classification_report</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gh87Y5Lg_QOnISigofC0SA.png" /></figure><p>Let’s understand TP, FP, FN, and TN in terms of heart disease</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*rCReIduLR7SScyoyLD2vbQ.png" /></figure><p>We have taken spam as a positive class and Not-spam as a negative class</p><p>TP =45, Model predicted as positive and it’s true.</p><p>Model correctly classified 45 emails as spam.</p><p>FN = 20, Model predicted as negative but it’s false.</p><p>Model incorrectly classified 20 spam emails as non-spam.</p><p>FP =5, Model predicted as positive but it‘s false</p><p>Model incorrectly classified 5 non-spam emails as spam.</p><p>TN =30, Model predicted as negative and it’s true</p><p>Model correctly classified 30 emails as non-spam.</p><p><strong>3. Precision, Recall, Accuracy and F1-score</strong></p><p>Precision: It indicates the quality of a positive prediction made by the model. In another word, how precise a model is able to predict positive labels, Precision refers to the number of true positives divided by the total number of true positives and false positives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*52WhUmCp6TykJVoD0ybNUA.png" /></figure><p>Let’s take the above heart disease example to calculate the precision</p><p>precision = 45/(45+5) = 0.9</p><p>Recall: Quantifies the number of positive class predictions made out of all positive in the example dataset. Recall refers to the true positive divided by the total number of true positive and false negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*7rLRQT1pVv-ozTN8ZPs4OQ.png" /></figure><p>Let’s take the above heart disease example to calculate the recall</p><p>recall = 45/(45+20) = 0.69230.</p><p>Accuracy: It’s an evaluation metrics that describes how model performs accross all the classes. It is useful when all classes are equal importance.It is calculated as ratio between number of correct prediction to the total number of predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*h6uA2wkl3OWkF7dYQZ7ZZg.png" /></figure><p>let’s take above heart disease example</p><p>Accuracy = (45+30)/(45+30+20+5)=0.75.</p><p>Using accuracy for imbalanced dataset,is not a good idea.</p><p>F1-Score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*8b-J8K5Z-IglJntHI_dYmQ.png" /></figure><p>It’s very difficult to compare two models based on high precision and low recall. To make them comparable,F1-score help us to measure precision and recall at same time.F1-score is harmonic mean of precision and recall.Using F1-score in case of imlanaced dataset, is good idea.</p><p>I hope , I have given some basic understanding for confusion matrix. If you like the post and feel that it is useful for you. please do some claps. I am always open for your questions and suggessions.</p><p>You can reach out to me</p><p><a href="https://www.linkedin.com/feed/">https://www.linkedin.com/feed/</a></p><p><a href="https://github.com/anjaleana">https://github.com/anjaleana</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eee9eace7c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kaggle Dataset- SQL Injection Attack]]></title>
            <link>https://medium.com/@anjalisharma_47802/kaggle-dataset-sql-injection-attack-d8c956b77518?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8c956b77518</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[word2vecs-gensim]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[tfidf-vectorizer]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 19:11:49 GMT</pubDate>
            <atom:updated>2022-02-09T19:11:49.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7ep0iSGmSuIgbDX_.jpg" /></figure><p>Today, I started the kaggle problem — SQL Injection attack. The main goal of this problem is to classify the SQL injection attack using ML/DL algorithm.</p><p>Before proceeding ahead. I listed the content that is going to explain here.</p><p>Let’s start</p><ol><li>Business Problem</li><li>Source of Data</li><li>Mapping to ML/DL Problem</li><li>Existing Approach</li><li>Exploratory Data Analysis</li><li>My First Cut Approach</li><li>Featurization</li><li>Modeling</li><li>Quantization</li><li>Experiment and Result</li><li>Model Deployment</li><li>Conclusion</li><li>Future Work</li><li>References</li></ol><blockquote><strong>1.Business Problem:</strong></blockquote><p>SQL injection attacks are the most common attack on web applications. It is among the top 10 security risks on web applications. SQL injection is an attack in which attacker gives SQL tokens as an input when such input is used to form query, it changes the structure of the query and allows the attacker to get access to confidential data or modify the database. SQL injection exploits the confidentiality and integrity of the application</p><p>Most of the applications that we use every day are web-based applications. With the growth of the internet, we are performing various kinds of transactions. Data are entered by users during transactions on the web applications or websites is stored in some kind of database. A relational database can be communicated with a language called Structured Query Language(SQL). Using SQL to launch attacks on databases and manipulate them to do what the user wants is a form of a web hacking technique called SQL Injection Attack.</p><p>SQL injection attacks are considered as the one among foremost vulnerabilities that exploit in terms of privacy exposure also as money loss. SQL injection attack is known as SQLI, is a common attack vector that uses malicious SQL code for manipulating the backend database to access information that is not intended to be displayed. The information may include bank details, company data, private data, or any sensitive data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*t_ZGStgO_g7PcclV.png" /></figure><p>SQL injection attacks can be broadly classified into the following three categories</p><ol><li>Union Based SQL Injection</li><li>Error Based SQL Injection</li><li>Blind SQL Injection</li></ol><p><strong>Union Based SQL Injection</strong></p><p>In union-based SQL injection, the attacker uses the Union operator. This is achieved by another query in place of plain text and using union at beginning of the query.</p><p>Let’s take an example of the Students database, We want to search Students&#39; names from the database. The following query is found</p><p>SQL Query : Select * from Students where name = ‘ABC’</p><p>However, a malicious user might enter the following SQL query to exploit the database</p><p>SQL Query : select * from Students where name = ‘ABC’ Union drop table Students</p><p>Using this approach, the second part of the query can be used to perform any desired unauthorized action on the database. This might end up in deleting the entire student&#39;s table.</p><p><strong>Error Based SQL Injection</strong></p><p>This is achieved by forcing the database to perform an action that can trigger an error in the database. The user can get error-generated output and use those errors to get information on how to further manipulate the database by exploiting SQL queries.</p><p><strong>Blind SQL Injection</strong></p><p>A blind SQL injection attack does not reveal any data directly from the database. Rather, the attacker closely examines indirect clues in behavior. Details within HTTP responses, blank webpages for certain user input, and how long it takes the database to respond to certain user input are all things that can be clues depending on the goal of the attacker.</p><blockquote><strong>2.Soure of Data</strong></blockquote><p><a href="https://www.kaggle.com/sajid576/sql-injection-dataset">SQL Injection Dataset</a></p><p>We have a dataset with 30920 rows. It has labeled data 0 and 1</p><blockquote><strong>3.Mapping to ML/DL</strong></blockquote><p>In machine learning, the performance metric is an essential task to measure our model that how well our model is working. The kaggle Sql injection dataset defines as classification problem. We have counted <strong>AUC-ROC </strong>as the evaluation metric. ROC summarizes the trade-off between true-positive rate and false -positive rate using different thresholds settings. The false-positive rate is on X-axis and the true positive rate is on Y-axis. AUC represents the degree or measure of separability.</p><p>If AUC is high that means the model is better and the model works as expected. If AUC is 0.8 that’s the mean mode has an 80% chance to separate the binary classification.</p><blockquote><strong>4.Existing Approach</strong></blockquote><p>1. A number of solutions are proposed to prevent SQL injection attacks. Almost all the solution requires either the developer to check the injection parameters during the development phase of the application or the application is modified to prevent SQL injection attacks. SQLrand protects from SQL injection by randomizing the SQL Statement, creating instances of the language that are unpredictable to attackers. It is implemented as database server proxy.</p><p>There are different -2 tools found in the research paper as follows:</p><p><strong>WAVES Tool: </strong>It identifies all the input points where SQL injection attacks are possible. It uses machine learning algorithm to test SQL injection vulnerabilities.</p><p><strong>CANDID Tool:</strong> It intended query by dynamically evaluating runs over the benign candidate and detects attacks by comparing it against the structure of the actual query issued.</p><p><strong>AMNESIA Tool</strong>: It combines static analysis and runtime monitoring. In the static phase, it builds the query model and in the dynamic phase, it checks the dynamic query with the static model. Our approach is also based on static and dynamic analysis. AMNESIA tool is developed to prevent SQL injection attacks on java. It uses Java String Analyzer for static analysis.</p><p>2. Program contains the structure of the query. The approach is to extract query structure from the programs using static analysis and at the runtime capture the dynamic query and validate it against the static query model. SQL injection attack will add tokens to the user input and hence change the query structure. If the dynamic query contains malicious code then it will not match the static query model then it will be rejected.</p><p>(REF — <a href="https://scholarworks.sjsu.edu/cgi/viewcontent.cgi?article=1727&amp;context=etd_projects">SQL Injection Detection Using Machine Learning (sjsu.edu)</a></p><p>REF — ojsadmin,+1939.pdf</p><p>(REF-<a href="https://www.imperva.com/learn/application-security/sql-injection-sqli/">What is SQL Injection | SQLI Attack Example &amp; Prevention Methods | Imperva</a>)</p><p>(REF — <a href="https://www.interscience.in/cgi/viewcontent.cgi?article=1026&amp;context=ijcsi">Model Based Approach to Prevent SQL Injection Attacks on .NET Applications (interscience.in)</a></p><blockquote><strong>5. EDA(Exploratory Data Analysis)</strong></blockquote><p>The primary goal of this case study is to classify SQL injection attack.</p><p>We have 30920 sample data and 1 class label(0/1). The 0 indicates “<strong>No SQL injection</strong>” found and 1 indicates “<strong>SQL Injection found</strong>”.</p><p>As per data analysis, we found 19537 rows as “No SQL Injection attack” and 11382 found as SQL Injection attack.</p><p><strong>Univariate Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThefWkz7qhtGVfYDslf9Ug.png" /></figure><p>We found the data points belonging to class label 0 is 63.2% and 1 is 36.8%.</p><p><strong>Word Cloud Visualization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6jN1gPeEwrBYTS088UnAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*zki1zifw_NhxOROyWrXJDA.png" /></figure><p><strong>Observation</strong>: The word Select, Union, Char, Count, and Null occurs more frequently.</p><blockquote><strong>6.My First Cut Approach</strong></blockquote><p>The dataset consists of plain-text queries and has around 30920 rows. The dataset consists of numerical data, special characters, spaces, and textual data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*O3DizR8vmJruor87y4SCVw.png" /></figure><p>First, we need to do text pre-processing as follows</p><ol><li><strong>Tokenization:</strong></li></ol><p>In tokenization, a sequence of characters is broken into small pieces called ‘tokens’. Tokenization also includes removing certain characters sometimes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*n-18QM7-wk2Gyr3uwyzYFQ.png" /></figure><p><strong>2. Remove Punctuation:</strong></p><p>We remove all the special characters e.g how are you? → how are you</p><p><strong>3. Remove Stop Words:</strong></p><p>Stop words are common words that will likely appear in any text. Which we need to remove.</p><p>E.g.: silver or lead is fine for me -&gt; silver, lead, fine.</p><p><strong>Preprocessing Data</strong></p><p><strong>Stemming:</strong></p><p>Stemming helps reduce a word to its stem form. It removes the suffix, like “ing”, “ly”,”s” , etc by a simple rule-based approach.</p><p>E.g. Entitled, Entitling-&gt;Entitl</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*7aTvzxt9PDtmYCs02CEktw.png" /></figure><p><strong>Lemmatizing</strong></p><p>Lemmatization also reduces the word but it takes a dictionary-based approach. i.e a morphological analysis to the root word. eg: Entitling, Entitled-&gt;Entitle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*UHtW_gsgPde-SHzEzRqQ6Q.png" /></figure><p><strong>Vectorizing Data:</strong></p><p>Vectorizing is the process of encoding text as integers i.e. numeric form to create feature vectors so that machine learning algorithms can understand our data.</p><p><strong>a. Bag-of-words:</strong></p><p>Bag-of-words(BOW) or Count Vectorizer describes the presence of words within the text data. It gives a result of 1 if the word is present in text or 0 if not present.</p><p><strong>b. N-Grams:</strong></p><p>N-grams are simply all combinations of adjacent words or letters of length n that we can find in our source text. Ngrams with n = 1 are called unigrams. Similarly, bigrams(n=2), trigrams(n=3), and so on also can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wUTHiLIwfONmoLZTGeCvA.png" /></figure><p><strong>TF-IDF Vectorizer:</strong></p><p>TF-IDF is an abbreviation for Term Frequency Inverse Document Frequency. This is the very common algorithm that covert text to numeric data which is used to fit machine learning algorithms for prediction.</p><p>TF — IDF = TF(d,t) + lDF(t)</p><p>TF(d,t) →Number of times term t appears in document d</p><p>IDF(t) = log(1+n)/(1+df(d,t))+1</p><p>Where n = number of documents, df(d,t)-&gt; Document frequency where term t appears.</p><p><strong>Word2Vec</strong></p><p>In this specific model, each word is basically represented as a vector of 32 or more dimensions instead of a single number.</p><p>Here, the semantic information and relation between different words are also preserved.</p><p>Step to Create word2vec</p><ol><li>Tokenization of the sentences</li><li>Create Histograms</li><li>Take most frequent words</li><li>Create a matrix with all unique words. It also represents the occurrence relation between words.</li></ol><blockquote><strong>7.Featurization:</strong></blockquote><p><strong>Bag-of-words:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ss2KJb25NtX29s5h3y77dg.png" /></figure><p>Observation : We have initialized the variable count_vect using CountVectorizer() . Using that count_vect variable, transformed the text to vector and printed the top 10 features.</p><p><strong>Unigrams and bi-grams</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrT6hMek0JNfbtNaj6u2Ww.png" /></figure><p>Observation: Here, we have used CountVectorizer() with ngram_range=(1,2) which represents unigram and bigram, min_df=10 and covert text to vector features.</p><p><strong>TF-IDF Vectorizer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8JLlBi4IZx0qU8TSe2EiQ.png" /></figure><p>Observation: Here, we have used the TF-IDF idea to convert from text to vector features.</p><p><strong>TF-IDF Weighted Word2Vec</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTUmARceSO5FjSHjyp2oKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VY9N-VyooqEXhn8Xz3coNQ.png" /></figure><p>Observation: Here, we have used word2vec to convert from text to vectorizer.</p><blockquote><strong>8. Modelling</strong></blockquote><p>I have used 8 Models using hyper-parameter</p><ol><li>KNN(K-Nearest Neighbors)</li><li>Logistic Regression</li><li>Naive Bayes Classifier</li><li>Support Vector Machine</li><li>Decision Tree Classifier</li><li>Gradient Boosting Algorithm</li><li>Stacking Classifier</li><li>LSTM Model</li></ol><blockquote><strong>9.Post Training Quantization:</strong></blockquote><p>Post-training quantization is a conversion technique that can reduce model size while also improving CPU and hardware accelerator latency, with little degradation in model accuracy.</p><p>Import useful library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BinmSZnTQJ99jMpQ-EcljA.png" /></figure><p>let’s load the Keras model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-liG5l1-45bCnxXg6png0g.png" /></figure><p>Before Post Training Quantization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfD_mH84F_W_B61Vyepwww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2umScJ-I4dYTfrpeFmQTMw.png" /></figure><p>Observation:</p><p>Size of model in bytes before quantization = 30545388</p><p>After Post Training Quantization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtl6dksNjtyA476kGGw1yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*h2rS2XvOkf6MTDFSX94-wA.png" /></figure><p>Observation:</p><p>Size of Model in bytes after Post Training Quantization — 7647648</p><blockquote><strong>9. Experiment and Result</strong></blockquote><ol><li>Text-preprocessing + Bag-of-words + ML Classification</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*IAdljNETqqtfwjxnQ4d-Lg.png" /></figure><p>2. Text Pre-processing+Bigram + ML Classification Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*0Uu3DyWVkvAOgj8Pgn5Azg.png" /></figure><p>3. Text Pre-processing +TF-IDF Vectorizer + ML Classification Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*r34A1HCyqMejCzqqoqqE7Q.png" /></figure><p>4. Text Pre-processing + Word2Vec + ML Classification Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*C1SHTs48MnJEErBCKkWr6w.png" /></figure><p>5. Text Pre-processing+Word2Vec Embedding+ LSTM Deep Learning Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*kEAB3tjFgkFUo4K_GhGS-g.png" /></figure><p><strong>Observation</strong></p><p><em>We found LSTM as the best model as per the experiment.</em></p><blockquote><strong>10.Model Deployment</strong></blockquote><p>We have deployed the model using streamlit library.</p><p>let’s install the necessary library</p><p>!pip install -q pyngrok</p><p>!pip install -q streamlit</p><p>!pip install -q streamlit_ace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKtcOHgo0_DMD7WOZlssNA.png" /></figure><p>run the below code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*_HZNPXnhp-6L5jK9H9uiWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQ9i617YhaHN-cUFPCTleQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*_Xf_FSVEiIFJvGC8OpeuNg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVomTUU_Im_o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVomTUU_Im_o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVomTUU_Im_o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/593f7bf68b6388d96d6bbf2a2d7eb42c/href">https://medium.com/media/593f7bf68b6388d96d6bbf2a2d7eb42c/href</a></iframe><blockquote><strong>11.Conclusion</strong></blockquote><p>1. We have done text pre-processing and EDA on the feature to know how data is performing.</p><p>2. We have applied the featurization technique - Bag-of-words, Bi-gram and n-gram, TF-IDF vectorizer, and weighted word2vec to convert text to vector.</p><p>3. We have applied word2vec embedding with LSTM deep learning model.</p><p>4. As per experiment 1, we have applied bag-of-word with text pre-processing and found Naive Bayes as the best model with AUROC — 0.95.</p><p>5. As per experiment 2 and 3, we have applied bi-gram and Tf-IDF vectorizer found all model works as expected for test data with good AUROC score.</p><p>6. As per experiment 4, we have applied word2vec and found all model works good except the naive bayes algorithm</p><p>7. As per experiment 5, we have applied word2vec embedding and applied the LSTM model on top of that. We found a better score — 0.99 and an F1 score — 0.98.</p><blockquote><strong>12. Future Work</strong></blockquote><p>1. Try to perform simple neural network architecture with TF-IDF vectorizer.</p><p>2. Try to perform the BERT algorithm on the dataset and check AUROC, F1-score.</p><blockquote><strong>13. References</strong></blockquote><ol><li>ojsadmin,+1939.pdf</li><li>For featurization — (<a href="https://medium.com/@aliyaser78691/featurization-f63be523644">https://medium.com/@aliyaser78691/featurization-f63be523644</a>)</li><li>For word2vec embedding -(<a href="https://www.analyticsvidhya.com/blog/2021/07/word2vec-for-word-embeddings-a-beginners-guide/">https://www.analyticsvidhya.com/blog/2021/07/word2vec-for-word-embeddings-a-beginners-guide/</a>)</li><li>Most Voted Kaggle -(<a href="https://www.kaggle.com/syedsaqlainhussain/sql-injection-dectection-using-neural-network">https://www.kaggle.com/syedsaqlainhussain/sql-injection-dectection-using-neural-network</a>)</li><li>For post-training quantization -(<a href="https://www.tensorflow.org/lite/performance/post_training_quantization">https://www.tensorflow.org/lite/performance/post_training_quantization</a>)</li><li>AppliedAICourse: <a href="http://www.appliedaicourse.com/">www.appliedaicourse.com</a>/</li><li><a href="https://stackoverflow.com/questions/42064690/using-pre-trained-word2vec-with-lstm-for-word-generation">https://stackoverflow.com/questions/42064690/using-pre-trained-word2vec-with-lstm-for-word-generation</a></li></ol><p><strong>Thank you for reading the blog. Please find my </strong><a href="https://www.linkedin.com/in/anjali-sharma-98b85411a/"><strong>LinkedIn </strong></a><strong>Profile and </strong><a href="https://github.com/anjaleana/SQL-Injection-Attack"><strong>Github Code</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8c956b77518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kaggle Competition — Don’t Overfit ||]]></title>
            <link>https://medium.com/@anjalisharma_47802/kaggle-competition-dont-overfit-b88647c9c2bd?source=rss-552a2836d8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88647c9c2bd</guid>
            <dc:creator><![CDATA[Anjali Sharma]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 14:00:45 GMT</pubDate>
            <atom:updated>2022-06-23T03:34:04.230Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Kaggle Competition — Don’t Overfit ||</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*dzgdNqGlh21ZZ44Ij4lezw.png" /></figure><p>Hi Learners,</p><p>I just started my first Kaggle competition problem — Don’t Overfit ||. Kaggle is good website to learn Machine Learning/Deep Learning algorithm. There are different kinds of problem available based on different technique and we can adapt to learn on which scenarios we can apply which technique.</p><p>Before proceeding the blog, I listed the content that is going to be explained here. Let’s start</p><ol><li>Business Problem</li><li>Source of Data</li><li>Mapping to ML/DL Problem</li><li>Existing Approach</li><li>Exploratory Data Analysis</li><li>Feature Engineering</li><li>My First Cut Approach</li><li>Modeling</li><li>Experiment and Results</li><li>Future work</li><li>References</li></ol><blockquote><strong>1.Business Problem</strong></blockquote><p>Overfitting is one of the common problem with Machine Learning Models especially when we have few data points with training dataset and comparably more data points with test dataset. Model would not be able to generalize the unseen data or test datasets.</p><p>The process of creating a model in machine learning. The first step is to clean and visualize the data, understand the behavior of data. After that, we are splitting into training and test dataset. Let’s assume <strong>80%</strong> for training and <strong>20%</strong> for test. We used any machine learning algorithm like <strong>Logistic Regression, Kneighbors Classifier </strong>etc. and trained the model on training set. Used evaluation metrics <strong>precision, recall and accuracy</strong>.</p><p>To Understand the overfit problem, If we get <strong>90 %</strong> accuracy on training but <strong>50% </strong>accuracy on test data(unseen data), this is called as “<strong>Overfitting</strong>” . Overfitting is also known as “<strong>high — variance</strong>”. It happens many time due to unbalanced data set, few features on training data, lots of parameters in Neural Network Model.</p><blockquote><strong>2. Source Of Data</strong></blockquote><p>Dataset can be downloaded here</p><p><a href="https://www.kaggle.com/c/dont-overfit-ii">Don&#39;t Overfit! II</a></p><p><strong>What I am Predicting</strong></p><p>You are predicting the binary target associated with each row, without overfitting to the minimal set of training examples provided.</p><p><strong>Files</strong></p><ul><li>train.csv — the training set. 250 rows.</li><li>test.csv — the test set. 19,750 rows.</li><li>sample_submission.csv — a sample submission file in the correct format</li></ul><p><strong>Columns</strong></p><ul><li>id- sample id</li><li>target- a binary target of mysterious origin.</li><li>0-299- continuous variables.</li></ul><p><strong>Note:</strong></p><p>Data Set that is available on Kaggle website is a new version but evaluation is still being done on original version . you may get older dataset</p><p><a href="https://www.kaggle.com/anjali191/original-data-set-for-dont-overfit">Original Data Set for Don&#39;t Overfit ||</a></p><blockquote><strong>3. Mapping to ML/DL Problem</strong></blockquote><p>In machine learning, performance measurement is an essential task. So when it comes to classification problem, We count the AUC-ROC for evaluation metric. It is one of the important performance metric for any classification model. ROC summarizes the trade-off between <strong>true positive rate and false positive rate</strong> using different thresholds settings. The false positive rate is on X-axis and true positive rate is on Y-axis.</p><p>ROC represents the probability curve and AUC represents the degree or measure of separability. It tells how much our model is able to distinguishing between classes. If AUC is high that’s means model is better, the better model is predicting 0s classes as 0 and 1s classes as 1. When AUC is 0.5 , model has no capacity to separate the positive and negative class.</p><p>When AUC is 0.7 that’s means model has 70% chance to separate the binary classification.</p><blockquote><strong>4.Existing Approach</strong></blockquote><p>Because of existence of overfitting, the model performs perfectly on training data but poorly on test data. This is due to overfitted model has difficulty coping with pieces of information in the test data set.</p><p>We have observed solutions for avoiding overfitting problems based on my research</p><p><strong>4.1 Regularization</strong></p><p>A large number of features make the model more complex. Instead of discarding some features randomly, we can add regularization terms into the cost function that would cut down the effect of less important features by minimizing their weights. The regularization parameters, known as penalty factors, are introduced which control the parameters and ensure that model is not over-trained itself on the training data. These parameters are set to smaller values to eliminate the overfitting. When the coefficients take large value then regularization parameters penalize the optimization function.</p><p>L1 regularization is set to “0” for less important features. L2 regularization is set to close to “0” weights for less important features. L1 regularization knowns as <strong>Lasso</strong>, it is feature selection tools and it can completely eliminate non-important features. The penalty term is absolute of magnitude of coefficient which ensures that features don’t end up applying high weight on the prediction of the algorithm. L2 regularization is known as <strong>Rigde</strong>, the definition of L2 penalty term is to square of magnitude of coefficients. It makes the weights which is having less important feature is set to close to zero. But not exactly Zero. L1 creates sparsity but L2 creates the Dense matrix.</p><p><strong>4.2 Feed More Data</strong></p><p>We should have more relevant data so that models are trained, validated and tested. We should have proper balanced data, while training the model, need to split 60% data to train,20% to validate and 20% for test.</p><p><strong>4. 3Early Stopping</strong></p><p>This strategy is used in neural network. If we apply early stopping, it will stop learning on validation data if the accuracy of the algorithm is not increasing. Including paper, early stopping proposing the idea to find out the exact point after this, or before this, if we won’t stop learning the model, the overfitting/underfitting problem happens. Practically, to find out the exact point, we need to keep track of accuracy on test data. We compute the accuracy at the end of each epoch and stop training when accuracy on test data stops improving. Instead of test data, we can keep track of validation data which figure out a set of hyperparameters that can be used to evaluate the accuracy for unseen data(test data).</p><p><strong>4.4 Feature Selection</strong></p><p>Feature selection is more important when number of features are very large. We can assist our algorithm by feeding in only those features that are really important. Feature selection enables machine learning algorithm to train faster, it reduces the complexity of model and makes it easier to interpret. It improves accuracy of model and reduces the overfitting.</p><p><strong>4. 5 Network-Reduction</strong></p><p>The complexity of model can be reduced by eliminating the irrelevant data (i.e. Noise), which in turn, would aid model to prevent overfitting and perform on unseen data, this is called as pruning, which is widely used in decision tree. There are two types of pruning, pre-pruning and post pruning. Pre- pruning method tries to stop tree-building process early before it produces the leaves with very small samples. At each stage of tree, we are checking cross validation error. If the error decrease significantly, we stop. This is call Early Stopping in the learning algorithm. It reduces the overfitting problem in decision tree.</p><p>(ref -<a href="https://iopscience.iop.org/article/10.1088/1742-6596/1168/2/022022/pdf">https://iopscience.iop.org/article/10.1088/1742-6596/1168/2/022022/pdf</a>)</p><blockquote><strong>5.EDA(Exploratory Data Analysis)</strong></blockquote><p>The primary goal of this case study to avoid overfitting problem of given small amount of training sample</p><p>We have 250 samples data and 300 features and 1 id and 1 class label(0/1). We have 19750 features and 300 features and 1 id, So, with small amount of training data set, We must to do task carefully to avoid overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZ6pZJSJy9Bog_1IthwHzQ.png" /></figure><p>As expected, There are 302 columns in train.csv as we mentioned in problem statement.</p><p>Describe Training Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7k3otjaJ3UJnPYRj7INNug.png" /></figure><p>Train data has 300 independent features(0–299) and one dependent feature(target) along with unique id. All the values of feature are continuous and have same distribution from distribution table.</p><p>Info of training data (Just to check whether there is any missing value)</p><p>train_data.info()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*9VwT9l5m3R9WpsGyyuZtSw.png" /></figure><p><strong>Univariate Analysis</strong></p><p><strong>target</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVofkri5ZaIURSWnsEf_yg.png" /></figure><p><strong>Observation:</strong></p><p>It is clearly said that data is imbalanced, where data points belonging to target 0 is 73.2% and 1 is 26.8%. Thus , it is imbalanced.</p><p><strong>Distribution Plot for all (0–299) independent features in a single frame</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhAs23nkJlbkuUIqJd8L2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Pij_EsqNMG4DDbnC5-gqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Bez1o64F7Ywi5_Vbla8yuQ.png" /></figure><p><strong>Observation</strong></p><p>Based on above distribution, We have found skewness range between -0.5 to 0.5 and kurtosis range is less than 3. The distribution for all 300 features are showing almost Symmetric distribution.</p><p>The mean for all 300 features are almost close to 0. And the standard deviation for all 300 features are almost close to 1. The Distributions are very close to Standard Gaussian Distribution.</p><p><strong>Box Plot of all 300 features in single frame</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajRvWRjlBWe5b9GyRPyjFQ.png" /></figure><p><strong>Observation:</strong></p><p>From the above plot it is clearly mentioned that distribution of all 300 features are almost identical. All the features have same mean and standard deviation.</p><p>seem like, median of both target 0 and 1 have somewhat same.</p><p><strong>Scatter Plot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*jaW15fA1fQCLMxPMl2KNNw.png" /></figure><p><strong>Observation:</strong></p><p>We are unable to interpret using scatter plot.</p><p><strong>Contour Plot</strong></p><p>Let’s observe the density of region rather than points. One of the seaborn toolkit called Contour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*WODEcYxFyun_r98o_1NiwQ.png" /></figure><p><strong>Observation:</strong></p><p>More density region is in range between -1 to 1.</p><p><strong>Violin Plot of all 300 features in single frame</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFlfjj_viGPepvhb_k1-7g.png" /></figure><p><strong>Observation:</strong></p><p>It seems like median of both target 0 and 1 have somewhat same.</p><p><strong>Correlation Among Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*oFid7W6X1_WXORYB5jcvKQ.png" /></figure><p><strong>Observation:</strong></p><p>From above heatmap, it is really difficult to get exact correlation value between the features</p><p><strong>Top 20 correlated features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcnJZMuCRn00ugotQtC4AQ.png" /></figure><p><strong>Observation:</strong></p><p>The Blue color is showing positive feature and red color negative features. Based on correlation values , we are see that features are not highly correlated with target.</p><p>Feature 127 and 176 most correlated with target.</p><p><strong>Correlation among 300 features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*xzesmE4F-5eOVYzAF08e-A.png" /></figure><p>From above heatmap, it is really difficult to get exact correlation value between the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SwfkSl8f3BclcJWcvRUXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OaX4u9OZ__NiEHQNWBpwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK9X08EmWFoy7o_DHE1c8g.png" /></figure><p>We have set threshold value for correlation value between feature is 0.5 but features are not highly correlated to each other. So we are not deleting any features here.</p><blockquote><strong>6.Feature Engineering</strong></blockquote><p>The intension of feature engineering is to achieve two primary goals:</p><ol><li>Create the input dataset that should be compatible and best fit with machine learning algorithm.</li><li>Feature engineering improve the performance of machine learning model</li></ol><p>We have applied the <strong>basic statistic</strong> on this problem. Let’ s have a look</p><ol><li>Mean and Standard deviation</li><li>Trigonometric Function</li><li>Hyperbolic function</li><li>Exponents function.</li></ol><ul><li>*Mean and Standard deviation value of each row**</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FNunfZ_LgOLUnByUUVMHg.png" /></figure><ul><li>***Trigonometric Function***</li></ul><p>Here, I have applied <strong>sin, cos and tan</strong> function , The function -feature_function() to plot actual features vs after applied feature engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpieExcJbL8wUgh0d4ccSg.png" /></figure><p><strong>Fox Sin(X) function,</strong></p><p>Plot After applying sin function in Feature Engineering for 60 column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXagm-Zz-iYMv1QtBya9kA.png" /></figure><p>plot comparison based on target after applying sin function for feature 60</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXagm-Zz-iYMv1QtBya9kA.png" /></figure><p><strong>For Cos(X) function</strong></p><p>Plot After applying cos function in Feature Engineering for 78 column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEhvZqzocOiYS-Vgnzo-2Q.png" /></figure><p>plot comparison based on target after applying cos function for feature 78</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zEFcSpIGetordbMTdbVLw.png" /></figure><p><strong>Fox tan(X) function,</strong></p><p>Plot After applying tan function in Feature Engineering for 80 column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48ZfldcaBLtSWCIqFN7gmA.png" /></figure><p>plot comparison based on target after applying tan function for feature 80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJm4qlFTyTgzyjFOznlANQ.png" /></figure><ul><li>**Applied Mean on top of trigonometric function**</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIZeap-y9i8lIYNNrmgTTQ.png" /></figure><ul><li>**Applied Hyperbolic function**</li></ul><p><strong>For Sinh(X)</strong></p><p>Plot after applying Sinh function in Feature Engg for 242 Feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uf33zR9IyAfvPY9sV2Oeag.png" /></figure><p>plot comparison based on target after applying <strong>Sinh</strong> function for feature 242</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDzyCelW0f_xeqyM0gci2g.png" /></figure><p><strong>For Cosh(X)</strong></p><p>Plot after applying cosh function in Feature Engg for 227 Feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cNHjg2RtjcBm1PDnkAlqA.png" /></figure><p>plot comparison based on target after applying cosh function for feature 227.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA_2xRLe0e6-BoxP-owaHg.png" /></figure><p><strong>For tanh(X) function</strong></p><p>Plot after applying tanh function in Feature Engg for 167 feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHzjJK7kYeeAIKz3twv4aA.png" /></figure><p>plot comparison based on target after applying tanh function for feature 167.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyhHQk9luUoLOYa5O8bPNA.png" /></figure><ul><li>***Apply Mean on top of hyperbolic function***</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEJYzyg016rd4uyhXTd1uA.png" /></figure><ul><li>** Applied Exponential function **</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*hzuIDXtGLGXy56tbyDsqng.png" /></figure><p><strong>For exp(x)</strong></p><p>Plot after applying <strong>exp(x)</strong> function in Feature Engg for 20 feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvYHYRmXu2BWdpRa8EwVPg.png" /></figure><p>plot comparison based on target after applying <strong>exp(x)</strong> function for feature 20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgSa4aGQa93ZzXmEpoqTMw.png" /></figure><p><strong>For exp(x) -1</strong></p><p>Plot after applying <strong>exp(x) -1</strong> function in Feature Engg for 21 feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYAChBFXVfguggt4i3CYVQ.png" /></figure><p>plot comparison based on target after applying<strong> exp(x) -1</strong> function for feature 21.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUfx-1ixuYbn72FN8BDVSA.png" /></figure><p><strong>For 2**x</strong></p><p>Plot after applying <strong>2**x</strong> function in Feature Engg for 81 feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILD6y354w_87vuQmfC9-OA.png" /></figure><p>plot comparison based on target after applying <strong>2**x</strong> function for feature 81.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEvgV_BPJUz6_OuPXK4P6A.png" /></figure><ul><li>** Applied Mean on top of Exponential data**</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fE32Q-GKK0U7bRkDHIjOw.png" /></figure><ul><li>** Some Polynomial operation is applied**</li></ul><p>Let’s apply<strong> x²,x³,x⁴ </strong>and take mean of <strong>each resultant polynomial features</strong></p><p>Let’s wrap feature engineering code in single function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZDo0wfC9pSIq2HRaZwnlw.png" /></figure><blockquote><strong>7.First Cut Approach</strong></blockquote><p>We need to read the data and understand the behavior of each feature by applying EDA technique. How each feature is followed which type of distribution, is dataset balanced or not, etc. All the features are continuous(Measured), use some basic feature engineering applied using mathematics like mean, standard deviation, trigonometric function, hyperbolic function and exponential function.</p><p><em>The dataset is imbalanced, we have to deal it first, We will use over sampling/under sampling.</em></p><p><strong>7. 1 Sampling Technique</strong></p><p><strong>Over Sampling</strong></p><p>Over sampling means either we can add new Synthetic data based on similar attributes and characteristics or create duplicate data of minority class to increase number of samples as same as majority class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sr2v-63EiXZtaxfNpkvTHQ.png" /></figure><p><strong>Under Sampling</strong></p><p>In case of under sampling, we are resampling the majority class to remove the data from majority to decrease number of sample as same as minority. The main disadvantage is that , let’s assume we have 990 positive class and 10 negative class. After applying under sampling technique, we will get 10 sample for positive class. That’s means we are loosing the much information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ab59UJfSALVYisUo2Y8GMA.png" /></figure><p>Based on conclusion, we will go for only over sampling. <strong>SMOTE(Synthetic Minority Oversampling Technique),</strong>(https://www.analyticsvidhya.com/blog/2020/10/overcoming-classimbalance-using-smote-techniques/)</p><p>Code Snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjvUVoMFNdxJntd_aFI-2A.png" /></figure><p>Here, We have dropped the dependent variable — id and target on bases of from train dataset and id from test dataset. Apply the <strong>SMOTE()</strong> technique for the purpose of over sampling.</p><p><strong>7. 2 Feature Scaling</strong></p><p>We have to bring all data within bound range which is known as feature scaling. There are two ways to do that :<strong> Normalization</strong> and <strong>Standardization</strong>.</p><p><strong>Normalization:</strong></p><p>Normalization is scaling technique in which values are shifted and rescaled so that they can end up ranging between 0 and 1. It is also known as <strong>Min-Max scaling.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pZsxyHEMZU8KHS60A18NA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*I-1IbqfaHHS_q2zOrLHt6g.png" /></figure><p><strong>Standardization </strong>:</p><p>Standardization is scaling technique where values are centered around the mean with a unit standard deviation. That means , the mean of attributes became Zero and standard deviation became 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*Jk1gzcVEajGyvBRECV8cCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UtnHyGbMXymZE78ke5kUjQ.png" /></figure><p>There is no rule of thumb, that which works better, We will try both of them.</p><blockquote><strong>8.Modelling</strong></blockquote><p>We used 7 Model using hyper-parameters.</p><p>1.KNN(k-nearest neighbors)</p><p>2. Logistic Regression (Linear)</p><p>3. Support Vector Classifier(Non-Linear)</p><p>4. Random Forest (Non-Linear)</p><p>5. XGBoost (Non-Linear)</p><p>6. Decision Tree (Non — Linear)</p><p>7. Stacking Classifier</p><p><strong>For feature selection, we have four types</strong></p><ol><li>Filter Methods</li></ol><p>2. Wrapper Methods</p><p>3. Embedded Methods</p><p>4. Hybrid Methods</p><p>The Wrapper methods usually result in better predictive accuracy than filter method.</p><p>We used forward feature selection in this problem</p><p><strong>Forward Feature Selection</strong></p><p>To find top ’n’ importance features, First we need to train the model. At the same model, we used to find best features that can give more importance to that model. We used <strong>forward feature selection.</strong></p><p>The idea is simple:</p><ol><li>We need to initialize the number of top importance features of your desire.</li></ol><p>2. Iterate over all the features in train data.</p><p>3. Stop when condition of your desire is fulfilled or cross-validation score stopped improving after adding new features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*BcHuop_szxzakliUNL2Nkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*aLu4ZdXEzuQ-EeXgTeN_lQ.png" /></figure><ul><li>* Code Snippet of feature Engineering**</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6a7I60PogQOUgyEu3eVIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcTWhGFqsrF5DbPsxUwliA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*CiwfYuO4ctnNyf52RpHisw.png" /></figure><p>Here, we have performed forward feature selection on top of logistic model(log_model) to get top 50 feature on basis of performance.</p><p><strong>Pseudo — Labelling:</strong></p><p>Pseudo labelling is the process of using labelled data model to predict label for unlabeled data set. Here, at first, we have trained the model using labeled data and that model is used to generate pseudo labels for unlabeled dataset. Finally, both the dataset and labels (original label and pseudo labeled) are combined for a final model. This is called as Pseudo labelling.(<a href="https://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/">https://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*t7R4k4JNsiS0MUhpEx9QCQ.jpeg" /></figure><p>Code Snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svErGw1CZGUS8N94rQFfmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnMk4e1VeoOadyHZ1BfoLA.png" /></figure><blockquote><strong>9.Experiments and Results:</strong></blockquote><p>1 .<em> Class Weight + Feature Engineering+ Standardization + ML Classification Model</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YbxRYIyqeOf8zshuSkAIvA.png" /></figure><p>2. Over Sampling<em>+ Feature Engineering+ Standardization + ML Classification Model</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*xk9WYUiyV_sWdzvVBEDJPg.png" /></figure><p>3. Over Sampling<em>+ Feature Engineering+ Forward Feature Selection + Standardization + ML Classification Model</em></p><p>Models Using Top 50 Features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*LCe_LQe5pX4hEimCCQoXkg.png" /></figure><p>Model Using Top 100 Features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*x-1Swjl-w5jlbNlPK4Ybhw.png" /></figure><p>4. <em>Pseudo Technique +Nearest Neighbors +Standardization +ML Classification Model</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*OK5xyE3pjwDpRKWh5NgQCg.png" /></figure><p>5. <em>Class Weight + Feature Engineering+ Normalization + ML Classification Model</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*8fKE1BAVdieTzkM2ZCVrSg.png" /></figure><p>6. Class Weight + ML Classification Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*Q3_FIT5MM1rq4KdByHADRQ.png" /></figure><p>7. Pseudo Technique +ML Classification Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*6xTys2QpGMIFmpZedCCXVQ.png" /></figure><blockquote>My Best Kaggle Score Yet!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqYYL9jlNMmQH-QB6V4SqA.png" /></figure><p>The Left side is showing private score(0.834) and the right side is showing public score(0.844) on the leaderboard.</p><blockquote><strong>10 Conclusion</strong></blockquote><ol><li>We have performed the EDA on all 300 features and found most of features on the basis of target 0 and 1 were overlapped, that’s means it is harder to predict for any machine learning model</li><li>We have performed the correlation and found there is no highly correlated features. So we have not removed any features</li><li>We have performed feature engineering using basic statistics like mean, standard — deviation etc, trigonometric function, hyperbolic function and exponents function and polynomial operations and shown the plot between actual vs applied feature engineering .</li><li>If we observe experiment 1 and 2, by applying class weight with feature engineering, model works better than applying oversampling with feature engineering</li><li>We apply forward feature selection to those features which give higher AUROC score in experiment 3, we get high AUROC using top 100 features than considering all features</li><li>As per experiment 6, we have performed class weight with machine learning model and get AUROC — 0.844, but decision tree is not working as expected.</li><li>As per experiment 7, We have only performed pseudo technique with machine learning model and get good score.</li></ol><blockquote><strong>11.Future Work</strong></blockquote><ol><li>Try to perform using Lasso Regularization , chi-square to get important Features</li><li>Try to combine all important features which we get from Forward Feature Selection + Lasso Regularization + Chi-square and perform modelling on top of that</li></ol><blockquote><strong>12.References:</strong></blockquote><ol><li>For Feature Selection — (<a href="https://www.analyticsvidhya.com/blog/2020/10/feature-selection-techniques-in-machine-learning/">Feature Selection Techniques in Machine Learning (analyticsvidhya.com)</a></li><li>The problem of overfitting and how to resolve it (<a href="https://medium.com/fintechexplained/the-problem-of-overfitting-and-how-to-resolve-it-1eb9456b1dfd">The Problem Of Overfitting And How To Resolve It | by Farhad Malik | FinTechExplained | Medium</a>)</li><li>Don’t Overfit! || — How to avoid Overfitting in your Machine Learning and Deep Learning(<a href="https://towardsdatascience.com/dont-overfit-ii-how-to-avoid-overfitting-in-your-machine-learning-and-deep-learning-models-2ff903f4b36a">Don’t Overfit! II — How to avoid Overfitting in your Machine Learning and Deep Learning Models | by Md. Mubasir | Towards Data Science</a>)</li><li><a href="https://medium.com/analytics-vidhya/post-pruning-and-pre-pruning-in-decision-tree-561f3df73e65">Post-Pruning and Pre-Pruning in Decision Tree | by akhil anand | Analytics Vidhya | Medium</a></li><li>Most Voted Kaggle -<a href="https://www.kaggle.com/artgor/how-to-not-overfit">https://www.kaggle.com/artgor/how-to-not-overfit</a></li><li>To Deal with imbalanced data — <a href="https://www.kaggle.com/rafjaa/dealing-with-very-small-datasets">https://www.kaggle.com/rafjaa/dealing-with-very-small-datasets</a></li><li>For Pseudo Technique — (<a href="https://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/">https://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/</a>)</li><li>AppliedAICourse : <a href="http://www.appliedaicourse.com/">www.appliedaicourse.com</a></li></ol><p><strong>Thank you for reading the blog. Please find my </strong><a href="https://www.linkedin.com/in/anjali-sharma-98b85411a/"><strong>LinkedIn </strong></a><strong>Profile and </strong><a href="https://github.com/anjaleana/Don-t-Overfit-Case-Study-kaggle-competition-"><strong>Github Code</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88647c9c2bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>