<?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 Ayush Rathi on Medium]]></title>
        <description><![CDATA[Stories by Ayush Rathi on Medium]]></description>
        <link>https://medium.com/@aimlwork27?source=rss-7e0c1c5d9cd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X58COf4QMIQhcbLv</url>
            <title>Stories by Ayush Rathi on Medium</title>
            <link>https://medium.com/@aimlwork27?source=rss-7e0c1c5d9cd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:04:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aimlwork27/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[Unlocking Document Insights with a Multi-PDF Chatbot: A Gen-AI Journey]]></title>
            <link>https://medium.com/@aimlwork27/unlocking-document-insights-with-a-multi-pdf-chatbot-a-gen-ai-journey-af72f6825dba?source=rss-7e0c1c5d9cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/af72f6825dba</guid>
            <dc:creator><![CDATA[Ayush Rathi]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 19:29:24 GMT</pubDate>
            <atom:updated>2025-04-18T19:29:24.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnP-4-SqB8NNFXvHjpdcHQ.png" /></figure><h3>1. Introduction</h3><p>In today’s information-driven world, extracting insights from lengthy PDF documents — be it academic papers, technical manuals, or business reports — can feel like searching for a needle in a haystack. Researchers, students, and professionals often spend hours skimming through dense texts to find answers. Enter the <strong>Multi-PDF Chatbot</strong>, a generative AI-powered solution designed to transform PDFs into interactive knowledge bases. By uploading a PDF and asking questions in natural language, users can receive precise, context-aware answers in seconds.</p><blockquote>This blog explores the creation of the Multi-PDF Chatbot, a capstone project developed during the <a href="https://www.kaggle.com/learn-guide/5-day-genai"><strong>5-Day Intensive Gen-AI Course</strong></a> offered by Google on Kaggle. We’ll dive into the technologies behind it, break down the code, and discuss why generative AI is revolutionizing knowledge extraction. Let’s embark on this journey to make document analysis intuitive and impactful!</blockquote><h3>2. Technologies Used (Prerequisites)</h3><p>The Multi-PDF Chatbot leverages a powerful stack of tools and libraries to deliver a seamless experience. Here’s what powers the project:</p><ul><li><strong>Python</strong>: The core programming language for building the chatbot.</li><li><strong>PyPDF2</strong>: Extracts text from PDF files.</li><li><strong>LangChain</strong>: Provides a framework for Retrieval Augmented Generation (RAG) and question-answering chains.</li><li><strong>LangChain-Google-GenAI</strong>: Integrates Google’s Gemini models for embeddings and chat capabilities.</li><li><strong>FAISS</strong>: A library for efficient vector search and storage of text embeddings.</li><li><strong>Google Gemini API</strong>: Powers text embeddings (embedding-001) and conversational AI (gemini-1.5-pro).</li><li><strong>IPython Widgets</strong>: Enables interactive question-answering in Jupyter notebooks.</li><li><strong>Kaggle Secrets</strong>: Securely manages the Google API key.</li><li><strong>Dependencies</strong>: numpy, pandas, python-dotenv, google-generativeai.</li></ul><h3>3. Let’s Dive into the Code</h3><p>The Multi-PDF Chatbot follows a streamlined process: extract text from PDFs, chunk it, convert it into embeddings, store them in a vector database, and answer user queries using RAG.</p><h3>3.1. Install Dependencies</h3><p>The first step is to install the required libraries to handle PDF processing, embeddings, vector search, and conversational AI.</p><pre>!pip install PyPDF2 langchain langchain-community langchain-google-genai faiss-cpu python-dotenv google-generativeai</pre><p>This command installs all necessary packages, ensuring the environment is ready for the chatbot.</p><h3>3.2. Import Libraries</h3><p>We import the core libraries to handle PDF extraction, text splitting, embeddings, vector storage, and question-answering.</p><pre>import os<br>from PyPDF2 import PdfReader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI<br>from langchain_community.vectorstores import FAISS<br>from langchain.chains.question_answering import load_qa_chain<br>from langchain.prompts import PromptTemplate<br>import google.generativeai as genai<br>from IPython.display import display<br>import ipywidgets as widgets</pre><p>Each library serves a specific purpose, from PyPDF2 for PDF reading to FAISS for vector storage.</p><h3>3.3. Load API Key</h3><p>The Google API key is securely loaded from Kaggle Secrets and configured for the Gemini API.</p><pre>from kaggle_secrets import UserSecretsClient<br>user_secrets = UserSecretsClient()<br>try:<br>    google_api_key = user_secrets.get_secret(&quot;GOOGLE_API_KEY&quot;)<br>except Exception as e:<br>    raise ValueError(&quot;Failed to load GOOGLE_API_KEY from Kaggle secrets.&quot;)<br>genai.configure(api_key=google_api_key)<br>os.environ[&quot;GOOGLE_API_KEY&quot;] = google_api_key</pre><p>This ensures secure access to Gemini’s embedding and chat models.</p><p>If you aren’t using Kaggle, then create an .env file and save your API key. Then use the following code.</p><pre>from dotenv import load_dotenv<br><br>load_dotenv()<br># os.getenv(&quot;GOOGLE_API_KEY&quot;)<br>genai.configure(api_key=os.getenv(&quot;GOOGLE_API_KEY&quot;))</pre><h3>3.4. Extract Text from PDF</h3><p>The get_pdf_text function reads a PDF file and extracts text from all its pages.</p><pre>def get_pdf_text(pdf_path):<br>    text = &quot;&quot;<br>    pdf_reader = PdfReader(pdf_path)<br>    for page in pdf_reader.pages:<br>        text += page.extract_text() or &quot;&quot;<br>    return text</pre><p><strong>Explanation</strong>: Using PyPDF2, the function iterates through each page, extracts text, and concatenates it into a single string. The or &quot;&quot; handles cases where text extraction fails for a page.</p><h3>3.5. Split Text into Chunks</h3><p>To process large texts efficiently, the get_text_chunks function splits the extracted text into smaller chunks.</p><pre>def get_text_chunks(text):<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=50000, chunk_overlap=1000)<br>    chunks = text_splitter.split_text(text)<br>    return chunks</pre><p><strong>Explanation</strong>: The RecursiveCharacterTextSplitter divides the text into chunks of up to 50,000 characters with a 1,000-character overlap to preserve context. This ensures manageable pieces for embedding and retrieval.</p><h3>3.6. Create Vector Store</h3><p>The get_vector_store function converts text chunks into embeddings and stores them in a FAISS vector database.</p><pre>def get_vector_store(text_chunks):<br>    embeddings = GoogleGenerativeAIEmbeddings(model=&quot;models/embedding-001&quot;)<br>    vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)<br>    vector_store.save_local(&quot;faiss_index&quot;)<br>    return vector_store</pre><p><strong>Explanation</strong>: Gemini’s embedding-001 model generates semantic vectors for each chunk. FAISS stores these embeddings for fast similarity search and saves the index locally for reuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wicmzZsFqLcv21c9R5IfIA.jpeg" /></figure><h3>3.7. Set Up Conversational Chain</h3><p>The get_conversational_chain function configures a question-answering chain with a custom prompt and the Gemini model.</p><pre>def get_conversational_chain():<br>    prompt_template = &quot;&quot;&quot;<br>    Answer the question as detailed as possible from the provided context. If the answer is not in<br>    the provided context, say, &quot;answer is not available in the context&quot;. Don&#39;t provide incorrect information.<br>    Context:<br>    {context}<br>    Question:<br>    {question}<br>    Answer:<br>    &quot;&quot;&quot;<br>    try:<br>        model = ChatGoogleGenerativeAI(model=&quot;gemini-1.5-pro&quot;, temperature=0.3)<br>        prompt = PromptTemplate(template=prompt_template, input_variables=[&quot;context&quot;, &quot;question&quot;])<br>        chain = load_qa_chain(model, chain_type=&quot;stuff&quot;, prompt=prompt)<br>        return chain<br>    except Exception as e:<br>        print(f&quot;[Error] Failed to create QA chain: {e}&quot;)<br>        return None</pre><p><strong>Explanation</strong>: The custom prompt ensures accurate, context-grounded answers. The gemini-1.5-pro model, with a low temperature (0.3) for focused responses, powers the RAG chain. The stuff chain type processes all retrieved documents at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYQLOyS_tGkhN4tkigJvNw.jpeg" /><figcaption>Flowchart of how code is functioning and answers are streamed.</figcaption></figure><h3>s3.8. Answer Questions</h3><p>The answer_question function retrieves relevant chunks from the vector store and generates answers using the RAG chain.</p><pre>def answer_question(user_question, vector_store):<br>    embeddings = GoogleGenerativeAIEmbeddings(model=&quot;models/embedding-001&quot;)<br>    new_db = FAISS.load_local(&quot;faiss_index&quot;, embeddings, allow_dangerous_deserialization=True)<br>    docs = new_db.similarity_search(user_question)<br>    chain = get_conversational_chain()<br>    response = chain({&quot;input_documents&quot;: docs, &quot;question&quot;: user_question}, return_only_outputs=True)<br>    return response[&quot;output_text&quot;]</pre><p><strong>Explanation</strong>: The function loads the FAISS index, performs a similarity search to find relevant chunks, and passes them to the RAG chain with the user’s question. The chain generates a precise answer based on the context.</p><h3>3.9. Process the PDF</h3><p>This segment ties everything together by processing a sample PDF and building the vector store.</p><pre># Change the pdf_path according to your path of the pdf file<br>pdf_path = &quot;/kaggle/input/testing-pdfs/Augmented LLMs.pdf&quot;<br>if os.path.exists(pdf_path):<br>    print(&quot;Processing PDF...&quot;)<br>    raw_text = get_pdf_text(pdf_path)<br>    text_chunks = get_text_chunks(raw_text)<br>    vector_store = get_vector_store(text_chunks)<br>    print(&quot;PDF processed successfully!&quot;)<br>else:<br>    print(&quot;PDF file not found.&quot;)</pre><p><strong>Explanation</strong>: The code checks for the PDF, extracts text, creates chunks, and builds the FAISS vector store, preparing the chatbot for queries.</p><h3>3.10. Query the Chatbot</h3><p>Finally, the chatbot answers a sample question to demonstrate its capabilities.</p><pre>question = &quot;What is the main topic discussed in the PDF?&quot;<br>if &#39;vector_store&#39; in locals() and vector_store:<br>    print(f&quot;\nQuestion: {question}&quot;)<br>    try:<br>        answer = answer_question(question, vector_store)<br>        print(f&quot;Answer: {answer}\n&quot;)<br>    except Exception as e:<br>        print(f&quot;Error answering question: {e}\n&quot;)<br>else:<br>    print(&quot;Cannot answer question: Vector store not created.&quot;)</pre><p><strong>Explanation</strong>: The code checks if the vector store exists, then uses the answer_question function to retrieve and display the answer. Error handling ensures robustness. You can also create a list of questions.</p><h3>4. Conclusion</h3><p>The Multi-PDF Chatbot is a testament to the power of generative AI in transforming how we interact with documents. By combining <strong>Document Understanding</strong>, <strong>Embeddings</strong>, <strong>Retrieval Augmented Generation</strong>, and <strong>Vector Search</strong>, it turns passive reading into active reasoning. Whether summarizing a 50-page research paper or pinpointing specific data in a technical manual, this tool saves time and boosts productivity.</p><p>To enhance this project more, you can also create a interface or a streamlit app, where you can comfortably use the application.</p><h3>5. Future Improvements</h3><p>To enhance the Multi-PDF Chatbot and make it even more robust, scalable, and user-friendly, several improvements can be implemented:</p><ul><li><strong>Multimodal Support</strong>: Extend the chatbot to process images, tables, and charts within PDFs using advanced OCR (e.g., Tesseract) or multimodal AI models like Gemini’s vision capabilities. This would enable extraction of non-textual data, such as diagrams or infographics.</li><li><strong>Multi-PDF Processing</strong>: Allow simultaneous processing of multiple PDFs, creating a unified vector store for cross-document queries. This would be ideal for comparing insights across related documents, such as a series of research papers.</li><li><strong>Improved Chunking Strategies</strong>: Experiment with dynamic chunk sizes or semantic-based splitting (e.g., using sentence transformers) to improve context preservation and retrieval accuracy, especially for complex documents.</li><li><strong>User Interface</strong>: Develop a web-based or desktop GUI using frameworks like Streamlit or Gradio, making the chatbot accessible to non-technical users without requiring a Jupyter environment.</li><li><strong>Memory and Contextual Awareness</strong>: Integrate LangChain’s memory features to maintain conversation history, enabling follow-up questions and more natural interactions (e.g., “Can you elaborate on that?”).</li><li><strong>Performance Optimization</strong>: Implement batch processing for embeddings and caching mechanisms to reduce API calls and improve response times, addressing potential quota limitations.</li><li><strong>Support for Other Formats</strong>: Expand compatibility to include other document types like Word, HTML, or scanned PDFs, broadening the tool’s applicability.</li><li><strong>Advanced Query Handling</strong>: Incorporate natural language understanding (NLU) to handle ambiguous or multi-part questions, and add summarization or keyword extraction features for quick insights.</li><li><strong>Cloud Deployment</strong>: Deploy the chatbot on a cloud platform (e.g., Google Cloud, AWS) with an API endpoint, enabling integration into enterprise workflows or mobile apps.</li><li><strong>Evaluation Metrics</strong>: Introduce metrics to evaluate answer accuracy and relevance, such as BLEU scores or human-in-the-loop feedback, to iteratively improve the model’s performance.</li></ul><h3>6. Thanking the 5-Day Gen-AI Course</h3><p>I am deeply grateful to the <strong>5-Day Intensive Gen-AI Course</strong> offered by Google on Kaggle for providing the opportunity to learn and apply cutting-edge generative AI technologies. This course not only introduced me to powerful tools like LangChain, FAISS, and Google Gemini but also inspired me to build practical solutions like the Multi-PDF Chatbot. The hands-on approach, combined with expert guidance, empowered me to transform ideas into reality. Thank you for igniting my passion for Gen-AI and equipping me with the skills to shape the future of knowledge extraction!</p><p>Actual Notebook Link:</p><p><a href="https://www.kaggle.com/code/ayushdrathi/capstone-pdf-agent">Capstone PDF Agent</a></p><p>Video Explanation:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DouObOeIkd6w&amp;type=text%2Fhtml&amp;schema=google&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FouObOeIkd6w" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ae43889d3fff5d0d441ef46a42c27f7/href">https://medium.com/media/0ae43889d3fff5d0d441ef46a42c27f7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af72f6825dba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DECODING ROC-AUC CURVE]]></title>
            <link>https://medium.com/@aimlwork27/decoding-roc-auc-curve-aed50765d0c3?source=rss-7e0c1c5d9cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed50765d0c3</guid>
            <dc:creator><![CDATA[Ayush Rathi]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 13:27:51 GMT</pubDate>
            <atom:updated>2024-07-21T13:27:51.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kONyQf4_K7juCBjD2l0XQA.png" /></figure><h3><strong>Introduction:</strong></h3><p>In recent years, Machine learning has taken the world to another level of easiness, it has never seen before, and still, it’s only the start. It has been a prominent subject of study for the scientists and Engineers. Learning concepts and algorithms is essential in Machine Learning and in this blog, we will be covering an important one of it.</p><p>So, in the domain of machine learning and predictive modelling, the Receiver Operating Characteristic (ROC) curve and the Area Under the Curve (AUC) are pivotal tools for evaluating the performance of classification models. This blog aims to provide a deep understanding of the ROC-AUC curve, its significance, interpretation, and practical applications through various real-life examples.</p><h3><strong>Basics:</strong></h3><p>Before digging deep into the topic of ROC-AUC curve, let’s just revise with some concepts which are essential for ROC-AUC Curve. But still I suggest you to go through the concept of confusion matrix and all the classification metrics deeply before reading this blog.</p><p>1. <strong>Confusion Matrix:</strong> A <a href="https://www.analyticsvidhya.com/blog/2020/04/confusion-matrix-machine-learning/"><strong>Confusion matrix</strong></a> is an <strong><em>N x N matrix</em></strong> used for evaluating the <strong>performance of a classification model</strong>, where <strong>N</strong> is the number of <strong><em>target classes</em></strong>.</p><p>This is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*vcf_g3R0BQB4GUXZYwu97Q.png" /><figcaption>General Confusion Matrix</figcaption></figure><p>2. <strong>Specificity (True Negative Rate):</strong> Proportion of actual negatives correctly identified by the model.</p><p>Specificity = Correctly identified negatives / Total actual negatives</p><p>= TN / (TN + FP)</p><p><strong>False Positive Rate</strong> = 1 — Specificity = FP / (TN + FP)</p><p>3. <strong>Sensitivity (True Positive Rate):</strong> Proportion of actual positives correctly identified by the model.</p><p>Sensitivity = Correctly identified positives / Total actual positives</p><p>= TP / (TP + FN)</p><h3><strong>Understanding ROC and AUC:</strong></h3><p>The ROC Curve evaluates the performance of a classification model at different thresholds. It plots the True Positive Rate I.e. Sensitivity (on y-axis) against the False Positive Rate i.e. 1 — Specificity (on x-axis). While AUC or Area Under the Curve is the area under the ROC Curve, indicates a model’s overall performance. Higher AUC values signify better performance.</p><p><strong>Interpreting the ROC Curve:</strong></p><p>The ROC curve is a valuable diagnostic tool, enabling practitioners to assess a model’s trade-off between sensitivity and specificity across various threshold values. A perfect model would have an ROC curve that reaches the top-left corner, representing a TPR of 1 and an FPR of 0. Conversely, a purely random classifier’s ROC curve would be a diagonal line from the bottom-left to the top-right. Deviations from this diagonal line indicate a model’s discriminatory power.</p><p>The best option of (FPR, TPR) will lead to the best value of threshold. Now, this ‘best option’ changes with change in problem or model. If the model needs more accuracy and less false rate (like in health-related data), then we will choose the one with high TPR and less FPR. And so, on depending on the cases you develop your model, you choose your best option.</p><p><strong>How ROC Work?</strong></p><p>Let’s see the step-by-step process of how the ROC Curve is formed.</p><p>1. ROC Curve has X-axis as False Positive Rate (1 — Specificity) and y-axis as True Positive Rate (Sensitivity).</p><p>2. For different values of threshold varying between 0 and 1, the model predicts the target value (y_pred).</p><p>3. Then as the model predicts the target value, and as we already have the actual target value (y_test), we use these two parameters and form a confusion matrix.</p><p>4. From the confusion matrix, we get FPR and TPR from the formulas discussed above.</p><p>And then plot (FPR, TPR) as (x, y) on the curve.</p><p>5. This is done for different threshold values and with each we get (FPR, TPR), which indeed is a point on the ROC Curve.</p><p><strong>Significance of AUC:</strong></p><p>The AUC serves as a pivotal metric for comparing different models and assessing their overall performance. It provides a single-value summary of a model’s discriminative power, independent of the specific threshold chosen. Models with higher AUC values are generally considered more effective at distinguishing between classes, making the AUC an indispensable measure when comparing and selecting classification models.</p><p>The Area Under the Curve (AUC) quantifies the overall performance of a classification model. It measures the entire two-dimensional area underneath the ROC curve from (0,0) to (1,1).</p><p><strong>Interpretation of AUC Values (0 to 1)</strong></p><p>AUC values range from 0 to 1:</p><ul><li><strong>0.5</strong>: No discrimination (random guessing).</li><li><strong>0.7–0.8</strong>: Acceptable performance.</li><li><strong>0.8–0.9</strong>: Excellent performance.</li><li><strong>Above 0.9</strong>: Outstanding performance.</li></ul><p><strong>Significance of the Diagonal Line</strong></p><p>The diagonal line on the ROC curve represents the chance level:</p><ul><li><strong>Above the Line</strong>: The model performs better than random guessing.</li><li><strong>Below the Line</strong>: The model is worse than random guessing and some adjustments are needed to make it better.</li></ul><p><strong>Let’s Understand it with the Curve</strong>:</p><p>The higher the AUC, the better the model’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*qxtoIYg-V8EU9T3DnHyZGg.png" /></figure><p>In this case, it is equal to 1 i.e. maximum value of AUC, which means that the model can correctly distinguish between the positive class and negative class. We can say this is the perfect model because both the Sensitivity and Specificity would be the highest at TPR = 1 and FPR = 0, and we have a threshold value for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*_LjSO2HUPmAuqT7ZEKbzpw.png" /></figure><p>In this case, 0.5 &lt; AUC &lt; 1 i.e. the classifier is able to distinguish between the positive and negative classes correctly but on some instant, it is getting wrong. Since, AUC value is greater than 0.5, it is clearly predicting a greater number of true positives and true negatives correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*e7OjooFjrazx-pjM3CbVRw.png" /></figure><p>Now, in this case the AUC = 0, i.e. the classifier has predicted all positives as negatives and vice-versa.</p><p><strong>Let’s Dive into the coding part now…</strong></p><ol><li>Firstly, we import the basic libraries</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*pkAx09bnWJztK_imayS7eQ.png" /></figure><pre>import numpy as np <br>import pandas as pd <br>import matplotlib.pyplot as plt <br>from sklearn.model_selection <br>import train_test_split from sklearn.datasets import make_classification</pre><p>2. Then, create a random small dataset and then split into training and testing dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*IBxAscWia44SCXU5cSOsYA.png" /></figure><pre># Create a small dataset<br>X, y = make_classification(n_samples=1000, n_classes=2, n_features=20, random_state=27)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><p>3. Now, we fit the models with their respective classifiers and predicts the value on X_test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*V5xe4U7zOV24DrUc-tyxBA.png" /></figure><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.neighbors import KNeighborsClassifier<br># Train a logistic regression model<br>model1 = LogisticRegression()<br>model2 = KNeighborsClassifier(n_neighbors=10)<br><br>model1.fit(X_train, y_train)<br>model2.fit(X_train, y_train)<br><br># Predict probabilities<br>y_pred_proba_1 = model1.predict_proba(X_test)[:, 1]<br>y_pred_proba_2 = model2.predict_proba(X_test)[:, 1]</pre><p>4. After, predicting the target values, we use the roc_curve library to fit the FPR and TPR, from the parameters y_test and y_pred_proba. The roc_curve library forms the confusion matrix for different threshold values and returns the FPR and TPR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Z6-CSyhXAMtKms6Sh_Y2sg.png" /></figure><pre>from sklearn.metrics import roc_curve, roc_auc_score<br># Calculate ROC curve<br>fpr1, tpr1, _ = roc_curve(y_test, y_pred_proba_1)<br>fpr2, tpr2, _ = roc_curve(y_test, y_pred_proba_2)<br><br># Calculate AUC<br>roc_auc_1 = roc_auc_score(y_test, y_pred_proba_1)<br>roc_auc_2 = roc_auc_score(y_test, y_pred_proba_2)<br><br># Plot ROC curve<br>plt.figure()<br>plt.plot(fpr1, tpr1, color=&#39;blue&#39;, lw=1, label=&#39;ROC curve (area = %0.2f)&#39; % roc_auc_1, linestyle=&#39;--&#39;)<br>plt.plot(fpr2, tpr2, color=&#39;green&#39;, lw=1, label=&#39;ROC curve (area = %0.2f)&#39; % roc_auc_2, linestyle=&#39;--&#39;)<br>plt.plot([0, 1], [0, 1], color=&#39;red&#39;, lw=2, linestyle=&#39;--&#39;)<br>plt.xlim([0.0, 1.0])<br>plt.ylim([0.0, 1.05])<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.title(&#39;Receiver Operating Characteristic (ROC) Curve&#39;)<br>plt.legend(loc=&quot;lower right&quot;)<br>plt.show()</pre><p>Here’s the look of the ROC Curve –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Nl2RE5NLBfRfAs_QGUzd7g.png" /></figure><p><strong>Real-World Use Cases in Various Industries:</strong></p><ul><li><strong>Healthcare and Medical Diagnostics</strong>: In medical diagnostics, ROC-AUC is crucial. For instance, a model predicting the likelihood of diabetes needs to distinguish between patients who have the disease and those who do not, making ROC-AUC vital for evaluating its effectiveness.</li><li><strong>Finance for Credit Scoring Models</strong>: Assessing the likelihood of loan defaults.</li><li><strong>Role in Marketing Analytics</strong>: Determining the effectiveness of campaigns.</li></ul><p><strong>Challenges and Limitations of ROC-AUC:</strong></p><p><strong>1.</strong> <strong>Situations Where ROC-AUC May Be Misleading</strong></p><p>In some contexts, such as highly imbalanced datasets, ROC-AUC might not tell the whole story. Other measures may also need consideration.</p><p><strong>2.</strong> <strong>Limitations Related to Imbalanced Datasets</strong></p><p>AUC can be biased toward the majority class, potentially masking poor performance on minority instances.</p><p><strong>3.</strong> <strong>Alternatives to ROC-AUC for Specific Scenarios (Like Precision-Recall Curves)</strong></p><p>Consider using additional metrics such as precision-recall curves for a more nuanced evaluation.</p><p><strong>Conclusion:</strong></p><p>As machine learning and predictive modelling continue to advance, the significance of the ROC-AUC curve endures, empowering practitioners to gauge the effectiveness of classification models and drive impactful decision-making across an array of domains.</p><p>With a solid understanding of the ROC-AUC curve, you can effectively evaluate model performance across various fields. Continual learning and application of these methods are essential for making informed decisions that can lead to better outcomes in real-world scenarios.</p><h3>Summer of Machine Learning (SoM)</h3><p>The Summer of Machine Learning (SoM) is an exciting initiative under the BSoC open-source project. Designed to introduce enthusiasts to the dynamic fields of AI and ML, SoM offers a comprehensive 6-week course covering essential topics like Python, machine learning algorithms, model tuning, and neural networks. <a href="https://github.com/bsoc-bitbyte/Summer_of_ML">Participants get hands-on experience through projects and collaborative learning, making it a perfect opportunity for anyone looking to dive into the world of data science and machine learning</a>.</p><p><strong>FREQUENTLY ASKED QUESTIONS (FAQs)</strong></p><p><strong>What does a higher AUC value indicate?</strong></p><p>A higher AUC value indicates better model performance in distinguishing between positive and negative classes.</p><p><strong>Can the ROC curve be used for multi-class classification?</strong></p><p>Yes, ROC curves can be adapted for multi-class scenarios using one-vs-all or one-vs-one approaches.</p><p><strong>Why is AUC not the only metric to consider in model evaluation?</strong></p><p>AUC provides a good overview, but metrics like precision and recall may give deeper insights, especially in imbalanced classes.</p><p><strong>How do I interpret a ROC curve that crosses the diagonal line?</strong></p><p>A curve that crosses the diagonal suggests a model that may not perform much better than random guessing; further tuning may be needed.</p><p><strong>What are typical pitfalls when interpreting ROC curves?</strong></p><p>Common pitfalls include misunderstanding data leakage, not considering the impact of class imbalance, and failing to use cross-validation for robust analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed50765d0c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>