<?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 Sri on Medium]]></title>
        <description><![CDATA[Stories by Sri on Medium]]></description>
        <link>https://medium.com/@msvs.akhilsharma?source=rss-47537d3e4f66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sri on Medium</title>
            <link>https://medium.com/@msvs.akhilsharma?source=rss-47537d3e4f66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:04:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msvs.akhilsharma/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[The Driver, the CEO, and the AI: A David vs. Goliath Story in the Back of an Uber]]></title>
            <link>https://medium.com/@msvs.akhilsharma/the-driver-the-ceo-and-the-ai-a-david-vs-goliath-story-in-the-back-of-an-uber-a2a104a5e72f?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a104a5e72f</guid>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[gen-ai-revolution]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[amc]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 04:29:39 GMT</pubDate>
            <atom:updated>2025-12-08T04:29:39.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HrN1wIJIOPKu-zZk" /></figure><p>On an ordinary Wednesday afternoon, heading to DFW airport, I didn’t expect to walk into the middle of a legal war.</p><p>My Uber arrived, and the first thing I noticed wasn’t the car, but the cargo. Stacks of boxes filled with paper lined the seats. The driver, a soft-spoken man, was mid-sentence — not with a passenger, but with ChatGPT. He was using the AI to rewrite complex legal motions, his voice steady as he navigated the dense terminology of the American court system.</p><p>He asked if the noise disturbed me. I told him no. I was curious.</p><p>As it turns out, I was sitting in the car with <strong>Nelson Willis</strong>, the man currently taking on <strong>Adam Aron, the CEO of AMC Entertainment</strong>, in the Fifth Circuit Court of Appeals.</p><h3>When the “Common Man” Finds a Digital Sword</h3><p>For the last two years, I’ve been an AMC Stubs A-Lister. I know the cinemas, and like many, I’ve followed the volatility of the AMC stock. But hearing the story from the driver’s seat was different. Willis explained his battle: a fight over shareholder rights, stock splits, and what he alleges were predatory marketing tactics that left retail investors holding the bag.</p><p>What struck me wasn’t just the complexity of the case (<em>Willis v. Aron</em>), but the sheer imbalance of power. On one side, you have a CEO who can afford the most prestigious law firms in the world. On the other hand, you have a man driving an Uber, supported only by a few friends and a phone.</p><p>In any other decade, this fight would have ended before it began. The “Goliaths” of the world usually win by simply exhausting the “Davids” — drowning them in legal fees and paperwork they can’t afford to draft.</p><p><strong>But then came AI.</strong></p><h3>AI as the Great Equalizer</h3><p>We usually hear about the negatives of AI: deepfakes, job loss, and misinformation. But in that Uber, I saw the positive side that rarely makes the news.</p><p>Willis was using ChatGPT to bridge the “justice gap.” It helped him:</p><ul><li><strong>Understand complex procedures:</strong> Translating “legalese” into plain English so he could respond to motions.</li><li><strong>Draft documentation:</strong> Helping a <em>pro se</em> (self-represented) litigant file clear, structured arguments that the court would actually read.</li><li><strong>Organize evidence:</strong> Turning a “stack of boxes” into a coherent narrative for his appeal.</li></ul><h3>The Human Behind the Docket</h3><p>The court documents for <em>Willis v. Aron</em> describe a man “expressing frustration” via emails from a hospital bed. It reads like a sterile legal summary. But sitting in that car, I saw a man who felt silenced and was using every tool at his disposal to be heard.</p><p>He didn’t want to be in court; he felt forced into it after a defamation case was threatened against him. He felt he was being made an “example” of. In response, he decided to become an example of something else: <strong>persistence.</strong></p><h3>Why This Matters</h3><p>As AI continues to evolve, we focus on whether it can write poems or generate art. We should be focusing on whether it can democratize justice.</p><p>Seeing Nelson Willis work on his case while navigating Dallas traffic made me realize that AI isn’t just a toy for tech enthusiasts. For the common man, it is a shield. It gives the underfunded and the solo litigants a way to stand in the same room as the giants.</p><p>Whether he wins or loses his appeal, the fact that he is still standing, still filing, and still fighting is a testament to human willpower — amplified by the digital age.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a104a5e72f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Smarter AI to Chat With My Documents: A Deep Dive into RAG]]></title>
            <link>https://medium.com/@msvs.akhilsharma/i-built-a-smarter-ai-to-chat-with-my-documents-a-deep-dive-into-rag-0d6191992811?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d6191992811</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 05:56:50 GMT</pubDate>
            <atom:updated>2025-12-05T05:56:50.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XYKAAFsof7HShxZJ" /></figure><p><strong>How Retrieval-Augmented Generation (RAG) grounds Large Language Models in reality, and the engineering journey behind building a custom document Q&amp;A app.</strong></p><p>Large Language Models (LLMs) like GPT and Llama are incredible. They can write poetry, debug software, and explain complex physics. But they have a critical weakness: they act like a genius who has been locked in a room without internet access for two years. They operate from a fixed “memory” of the data they were trained on.</p><p>This means they cannot access information published yesterday, they know nothing about your private documents, and — worst of all — when they don’t know the answer, they sometimes just make things up. In the AI world, we call this <strong>hallucination</strong>.</p><p>But what if we could give that genius an open textbook during an exam? What if, before answering a question, the AI could look up the relevant facts from a specific, trusted source that you provide?</p><p>That is the core idea behind <strong>Retrieval-Augmented Generation (RAG)</strong>. It is a technique that combines the reasoning power of an AI with the factual accuracy of a dedicated library. Instead of just “remembering,” the AI “reads” relevant information first and then formulates an answer.</p><p>In this article, I’ll walk you through a project I built: a full-stack web application that lets users upload their own PDFs and ask questions about them. I will strip away the complex code to explain the theory, the architecture, and the engineering hurdles I had to overcome to make it work.</p><h3>The Concept: How RAG Works (In Plain English)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsDqWcdFD1tdr3pF3p51ww.png" /></figure><p>To understand how my application works, imagine a very efficient librarian. When you ask a question, the librarian doesn’t just guess. They run to the specific shelf, pull the exact page relevant to your query, and read it to you.</p><p>The application I built follows a similar logical pipeline:</p><ol><li><strong>Ingestion (Reading):</strong> The user uploads a PDF. The system reads the raw text.</li><li><strong>Chunking (Organizing):</strong> You can’t feed a 100-page book to an AI all at once; it’s too much information. So, the system breaks the text down into smaller, bite-sized pieces called “chunks.”</li><li><strong>Embedding (Translating):</strong> Computers don’t understand words; they understand numbers. The system converts every chunk of text into a long list of numbers (a vector) that represents the <em>meaning</em> of that text.</li><li><strong>Indexing (Filing):</strong> These number lists are stored in a specialized database designed for fast lookup.</li><li><strong>Retrieval &amp; Generation (The Answer):</strong> When you ask a question, the system searches the database for the chunks that are mathematically closest to your question. It sends those specific chunks to the AI and says, <em>“Using only these notes, answer the user’s question.”</em></li></ol><h3>The Technical Implementation</h3><p>While the concept is simple, the engineering is nuanced. My goal was to create a robust, interactive application, not just a script. Here is the tech stack I chose and why:</p><ul><li><strong>The Brain (LLM):</strong> I used <strong>Phi-3 Mini</strong> (via Ollama). I chose this purely for efficiency. It is a “small language model” that can run locally on a laptop without needing expensive cloud GPUs, yet it is surprisingly capable of reasoning.</li><li><strong>The Backend:</strong> I built the API using <strong>Flask</strong>. It handles the heavy lifting of processing files and managing the data flow.</li><li><strong>The Frontend:</strong> I used <strong>Streamlit</strong>. It allowed me to build a clean, user-friendly interface very quickly so I could focus on the logic rather than CSS.</li><li><strong>The Database:</strong> I used <strong>FAISS (Facebook AI Similarity Search)</strong>. This is a vector database that runs locally. It is incredibly fast at comparing the “numerical meaning” of user questions against the stored document chunks.</li></ul><h3>Key Engineering Decisions &amp; Verification</h3><p>Building this wasn’t just about connecting APIs; it required verifying that the results were accurate and the system was stable. Here is how I approached the engineering process.</p><h3>1. Smart vs. Simple Chunking</h3><p>The Theory: How you cut up a document matters. If you simply cut a document every 500 words, you might slice a sentence in half, or separate a question from its answer. This confuses the AI.</p><p>My Approach: I implemented “Semantic Chunking.” Instead of cutting by character count, the system analyzes the text to find natural breaks in conversation or topics. It tries to keep related ideas together.</p><p>Verification: To verify this, I manually inspected the “chunks” generated by the system. I compared the semantic chunks against standard fixed-size chunks. The semantic version consistently kept paragraphs intact, resulting in better context for the AI.</p><h3>2. The Math of Meaning (Embeddings)</h3><p>The Theory: I used an open-source model from Hugging Face to turn text into numbers. This model places similar concepts close together in mathematical space. For example, “King” and “Queen” would be mathematically closer than “King” and “Banana.”</p><p>Verification: To ensure the retrieval was working, I didn’t just look at the text answer. I programmed the backend to return a “Relevance Score” (a mathematical distance score).</p><ul><li>A lower score meant the retrieved text was very close to the question.</li><li>A high score meant the system was guessing.</li><li>By exposing this score in the logs, I could quantitatively measure if the database was finding the right information.</li></ul><h3>3. Controlling the AI (Prompt Engineering)</h3><p>The Theory: Even with the right data, an AI might ignore it and use its own training data.</p><p>My Approach: I had to be strict. I designed a “System Prompt” that acts as a set of rules for the AI. It explicitly commands: “You are a subject matter expert. Answer ONLY using the context below. If the answer is not present, say ‘I don’t know’.”</p><p>Verification: I tested this by asking questions about topics that were not in the uploaded PDF. Early versions of the app would try to hallucinate an answer. After refining the prompt, the AI correctly responded, “I don’t know from the provided document,” proving that the grounding was successful.</p><h3>Challenges and Resolutions</h3><p>No project goes perfectly according to plan. Here are the specific issues I faced and how I resolved them.</p><h3>Challenge 1: The Fragility of Semantic Chunking</h3><p>The Issue: While Semantic Chunking is smarter, it is also more computationally heavy and prone to crashing on poorly formatted PDFs (like scanned receipts or complex layouts). During testing, the application would occasionally crash completely when uploading specific files.</p><p>The Resolution: I implemented a Fallback Mechanism (defensive programming). I wrapped the complex chunking logic in a “try-except” block.</p><ul><li><em>Plan A:</em> Try the smart, semantic chunking.</li><li>Plan B: If that fails or errors out, automatically switch to a simpler “Token Splitter” that cuts text by character count.</li><li>This ensured the application never crashed, regardless of the file quality. It prioritized stability over perfection.</li></ul><h3>Challenge 2: Context Window Limits</h3><p>The Issue: LLMs have a limit on how much text they can read at once. Initially, I tried to feed too many retrieved chunks to the AI, which caused errors because the prompt became too long.</p><p>The Resolution: I limited the retrieval to the top 3 most relevant chunks. This struck the right balance: it provided enough information to answer the question without overflowing the model’s memory capacity.</p><h3>Conclusion</h3><p>This project was an exercise in turning theoretical AI concepts into a working utility. By combining a vector database with a local LLM, I was able to create a system that doesn’t just “guess” but actually “studies” your data before answering.</p><p>It demonstrated that the key to good AI isn’t just a bigger model — it’s better data pipeline engineering. By focusing on how we ingest, chunk, and retrieve data, we can build AI tools that are trustworthy, private, and grounded in reality.</p><p>The era of personalized, fact-grounded AI is here, and you can build it right on your laptop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d6191992811" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hot Dog or Not: Building a CNN from Scratch with NumPy ]]></title>
            <link>https://medium.com/@msvs.akhilsharma/hot-dog-or-not-building-a-cnn-from-scratch-with-numpy-ed46e2d2d554?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed46e2d2d554</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 17:26:54 GMT</pubDate>
            <atom:updated>2025-08-29T17:28:03.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*FaADp6D686OwNPrdx6yjOQ.png" /></figure><p>Ever wondered what goes on <em>under the hood</em> of those magical deep learning frameworks? We’ve all been there, effortlessly typing model.fit() and watching the accuracy climb, feeling like a wizard. But what if we peeled back the layers and built a core component of modern computer vision—a Convolutional Neural Network (CNN)—from the ground up, using just <strong>NumPy</strong>?</p><p>That’s exactly what we’re going to do today! Our mission: to classify images as either “hot dog” or “not hot dog.” A classic, fun challenge that perfectly illustrates the power of CNNs.</p><h3>Why Go “From Scratch” When PyTorch and TensorFlow Exist?</h3><p>It’s a fair question! Tools like PyTorch and TensorFlow are incredibly powerful, optimized, and come with a plethora of pre-built functionalities. For most production-level tasks, they are undoubtedly the way to go.</p><p>However, building a CNN from scratch offers unparalleled benefits:</p><ol><li><strong>Deep Understanding:</strong> You’ll grasp the intricate dance between forward and backward passes, the role of each layer, and how gradients flow. It’s like learning to build an engine instead of just driving a car.</li><li><strong>Debugging Prowess:</strong> When you hit a wall in a complex PyTorch model, having this foundational knowledge will make debugging much easier. You’ll intuitively know where to look.</li><li><strong>Appreciation:</strong> You’ll gain a profound appreciation for the engineering marvels that are modern deep learning libraries!</li><li><strong>Customization:</strong> For highly specialized research or novel architectures, knowing how to implement layers manually can be invaluable.</li></ol><p>So, buckle up! We’re about to embark on a journey that will demystify CNNs.</p><h3>The Blueprint: Our CNN Architecture</h3><p>Our “TinyCNN” will be a simple, yet effective, architecture:</p><p>Conv2D -&gt; ReLU -&gt; MaxPool2x2 -&gt; Conv2D -&gt; ReLU -&gt; MaxPool2x2 -&gt; Flatten -&gt; Linear -&gt; Sigmoid</p><p>This structure is a miniature version of many successful CNNs.</p><h3>Step 1: Data Preparation — Getting Our Hot Dogs in a Row</h3><p>Before we can train our CNN, we need data! For our “hot dog or not” task, you’d typically have two folders: hotdog/ and not_hotdog/, each filled with images.</p><h3>Loading Images</h3><p>First, we need a way to load these images, resize them to a consistent size, and convert them into a NumPy array.</p><p>Python</p><pre>import os<br>import cv2<br>import numpy as np</pre><pre>def load_images(base_path, img_size=(64, 64)):<br>    images = []<br>    labels = []<br>    <br>    # Load &#39;hotdog&#39; images (label 1)<br>    for img_name in os.listdir(os.path.join(base_path, &#39;hotdog&#39;)):<br>        img_path = os.path.join(base_path, &#39;hotdog&#39;, img_name)<br>        img = cv2.imread(img_path)<br>        if img is not None:<br>            img = cv2.resize(img, img_size)<br>            images.append(img)<br>            labels.append(1) # Hot dog<br>            <br>    # Load &#39;not_hotdog&#39; images (label 0)<br>    for img_name in os.listdir(os.path.join(base_path, &#39;not_hotdog&#39;)):<br>        img_path = os.path.join(base_path, &#39;not_hotdog&#39;, img_name)<br>        img = cv2.imread(img_path)<br>        if img is not None:<br>            img = cv2.resize(img, img_size)<br>            images.append(img)<br>            labels.append(0) # Not hot dog<br>            <br>    return np.array(images), np.array(labels)</pre><p>Common Pitfall: Empty Dataset!</p><p>Oh, the horror of X_train being empty! This usually happens if base_path is incorrect, or your hotdog and not_hotdog subfolders are misspelled or empty. Always double-check your file paths! A quick print(len(images)) after loading can save you hours.</p><h3>Preprocessing: Making Data CNN-Friendly</h3><p>Our images are currently in (Height, Width, Channels) format (HWC), with pixel values from 0-255. CNNs prefer (Channels, Height, Width) (CHW) and normalized pixel values (0-1).</p><p>Python</p><pre>def preprocess_images(images):<br>    # Normalize pixel values to 0-1<br>    images = images.astype(np.float32) / 255.0<br>    # Change to NCHW format (Num_Images, Channels, Height, Width)<br>    images = np.transpose(images, (0, 3, 1, 2))<br>    return images</pre><p>Here, np.transpose is our best friend for reshaping. (0, 3, 1, 2) means: keep the number of images (0th dim) as is, move channels (3rd dim) to the 1st position, and height/width (1st and 2nd dims) to the 2nd and 3rd positions respectively.</p><h3>Step 2: Building Blocks — Our Custom Layers</h3><p>Now for the fun part: implementing the core layers of our CNN! Each layer will have a forward method (for predictions) and a backward method (for gradient calculation).</p><h3>2.1 Convolutional Layer (Conv2D)</h3><p>This is the heart of a CNN. It applies filters (kernels) to the input to detect features like edges, textures, etc.</p><p>Python</p><pre>class Conv2D:<br>    def __init__(self, in_channels, out_channels, kernel_size, learning_rate):<br>        self.out_channels = out_channels<br>        self.kernel_size = kernel_size<br>        # Initialize weights (filters) and biases<br>        self.weights = np.random.randn(out_channels, in_channels, kernel_size, kernel_size) * 0.01<br>        self.biases = np.zeros(out_channels)<br>        self.learning_rate = learning_rate<br>        <br>    def forward(self, input_data):<br>        self.input_data = input_data # Store for backward pass<br>        num_images, in_channels, in_height, in_width = input_data.shape<br>        <br>        # Calculate output dimensions<br>        out_height = in_height - self.kernel_size + 1<br>        out_width = in_width - self.kernel_size + 1<br>        <br>        output = np.zeros((num_images, self.out_channels, out_height, out_width))<br>        <br>        # Perform convolution<br>        for i in range(num_images):<br>            for c_out in range(self.out_channels):<br>                for h in range(out_height):<br>                    for w in range(out_width):<br>                        # Extract the receptive field (slice of input)<br>                        receptive_field = input_data[i, :, h:h+self.kernel_size, w:w+self.kernel_size]<br>                        # Element-wise multiplication and sum<br>                        output[i, c_out, h, w] = np.sum(receptive_field * self.weights[c_out]) + self.biases[c_out]<br>        return output<br>    def backward(self, d_output):<br>        # Initialize gradients<br>        d_weights = np.zeros_like(self.weights)<br>        d_biases = np.zeros_like(self.biases)<br>        d_input = np.zeros_like(self.input_data)<br>        num_images, in_channels, in_height, in_width = self.input_data.shape<br>        _, out_channels, out_height, out_width = d_output.shape<br>        for i in range(num_images):<br>            for c_out in range(out_channels):<br>                for h in range(out_height):<br>                    for w in range(out_width):<br>                        # Gradients for weights and biases<br>                        receptive_field = self.input_data[i, :, h:h+self.kernel_size, w:w+self.kernel_size]<br>                        d_weights[c_out] += receptive_field * d_output[i, c_out, h, w]<br>                        d_biases[c_out] += d_output[i, c_out, h, w]<br>                        # Gradients for input data<br>                        d_input[i, :, h:h+self.kernel_size, w:w+self.kernel_size] += self.weights[c_out] * d_output[i, c_out, h, w]<br>        # Update weights and biases<br>        self.weights -= self.learning_rate * d_weights<br>        self.biases -= self.learning_rate * d_biases<br>            <br>        return d_input</pre><p>Tensor Shape Mismatches</p><p>This is where 90% of your initial debugging efforts will go. When slicing receptive_field or performing element-wise operations, ensure the shapes align. A common mistake is (in_channels, kernel_size, kernel_size) not matching (in_channels, kernel_size, kernel_size) for receptive_field and self.weights[c_out]. Print shapes often! print(receptive_field.shape, self.weights[c_out].shape) can be your best friend.</p><h3>2.2 ReLU Activation</h3><p>The Rectified Linear Unit (ReLU) introduces non-linearity, allowing the network to learn more complex patterns. It’s simple: max(0, x).</p><p>Python</p><pre>class ReLU:<br>    def forward(self, input_data):<br>        self.input_data = input_data # Store for backward pass<br>        return np.maximum(0, input_data)<br>    def backward(self, d_output):<br>        # Gradient is 1 for positive inputs, 0 otherwise<br>        return d_output * (self.input_data &gt; 0)</pre><h3>2.3 Max Pooling Layer (MaxPool2x2)</h3><p>Max pooling downsamples the input, reducing dimensionality and making the network more robust to small shifts in features.</p><p>Python</p><pre>class MaxPool2x2:<br>    def forward(self, input_data):<br>        self.input_data = input_data<br>        num_images, channels, in_height, in_width = input_data.shape<br>        <br>        out_height = in_height // 2<br>        out_width = in_width // 2<br>        <br>        output = np.zeros((num_images, channels, out_height, out_width))<br>        <br>        for i in range(num_images):<br>            for c in range(channels):<br>                for h in range(out_height):<br>                    for w in range(out_width):<br>                        # Extract 2x2 window<br>                        window = input_data[i, c, h*2:(h+1)*2, w*2:(w+1)*2]<br>                        output[i, c, h, w] = np.max(window)<br>        return output<br>    def backward(self, d_output):<br>        d_input = np.zeros_like(self.input_data)<br>        num_images, channels, in_height, in_width = self.input_data.shape<br>        _, _, out_height, out_width = d_output.shape<br>        for i in range(num_images):<br>            for c in range(channels):<br>                for h in range(out_height):<br>                    for w in range(out_width):<br>                        window = self.input_data[i, c, h*2:(h+1)*2, w*2:(w+1)*2]<br>                        # Find where the max value was<br>                        mask = (window == np.max(window))<br>                        # Distribute gradient only to the max position<br>                        d_input[i, c, h*2:(h+1)*2, w*2:(w+1)*2] += mask * d_output[i, c, h, w]<br>        return d_input</pre><h3>2.4 Flatten Layer</h3><p>After convolutional and pooling layers, we need to “flatten” the 3D feature maps into a 1D vector so it can be fed into a fully connected (linear) layer.</p><p>Python</p><pre>class Flatten:<br>    def forward(self, input_data):<br>        self.input_shape = input_data.shape # Store original shape for backward<br>        num_images = input_data.shape[0]<br>        # Reshape to (num_images, -1) where -1 automatically calculates the dimension<br>        return input_data.reshape(num_images, -1)<br>    def backward(self, d_output):<br>        # Reshape back to the original input shape<br>        return d_output.reshape(self.input_shape)</pre><p><strong>Missing </strong><strong>flat_size?</strong> This error often pops up if you try to define the size of your linear layer before knowing the output size of your last pooling layer. The Flatten layer handles this dynamically.</p><h3>2.5 Linear (Fully Connected) Layer</h3><p>This is your standard neural network layer, performing a weighted sum of inputs and adding a bias.</p><p>Python</p><pre>class Linear:<br>    def __init__(self, input_size, output_size, learning_rate):<br>        self.weights = np.random.randn(input_size, output_size) * 0.01<br>        self.biases = np.zeros(output_size)<br>        self.learning_rate = learning_rate<br>    def forward(self, input_data):<br>        self.input_data = input_data<br>        return np.dot(input_data, self.weights) + self.biases<br>    def backward(self, d_output):<br>        # Gradients for weights, biases, and input<br>        d_weights = np.dot(self.input_data.T, d_output)<br>        d_biases = np.sum(d_output, axis=0)<br>        d_input = np.dot(d_output, self.weights.T)<br>        # Update weights and biases<br>        self.weights -= self.learning_rate * d_weights<br>        self.biases -= self.learning_rate * d_biases<br>        <br>        return d_input</pre><h3>2.6 Sigmoid Activation</h3><p>For binary classification, the sigmoid function squashes the output of our final linear layer into a probability between 0 and 1.</p><p>Python</p><pre>class Sigmoid:<br>    def forward(self, input_data):<br>        self.output = 1 / (1 + np.exp(-input_data))<br>        return self.output<br>    def backward(self, d_output):<br>        # Sigmoid derivative: s * (1 - s)<br>        return d_output * (self.output * (1 - self.output))</pre><p><strong>Missing </strong><strong>sigmoid attribute?</strong> Check your class definition and make sure self.output is correctly stored in the forward pass for use in the backward pass.</p><h3>Step 3: Orchestrating the Network — The TinyCNN Class</h3><p>Now we assemble our layers into a complete CNN!</p><p>Python</p><pre>class TinyCNN:<br>    def __init__(self, learning_rate=0.01):<br>        self.learning_rate = learning_rate<br>        self.layers = [<br>            Conv2D(3, 8, 3, learning_rate),  # 3 input channels (RGB), 8 output filters, 3x3 kernel<br>            ReLU(),<br>            MaxPool2x2(),<br>            Conv2D(8, 16, 3, learning_rate), # 8 input channels, 16 output filters, 3x3 kernel<br>            ReLU(),<br>            MaxPool2x2(),<br>            Flatten(),<br>            Linear(16 * 14 * 14, 1, learning_rate), # Depends on image size and pooling! (16*14*14 for 64x64 img)<br>            Sigmoid()<br>        ]<br>    def forward(self, X):<br>        for layer in self.layers:<br>            X = layer.forward(X)<br>        return X<br>    def backward(self, d_output):<br>        for layer in reversed(self.layers): # Backpropagate in reverse order<br>            d_output = layer.backward(d_output)<br>        return d_output</pre><p><strong>The </strong><strong>Linear Layer&#39;s </strong><strong>input_size</strong> is crucial here. If your initial image size is 64x64:</p><ul><li>After first MaxPool2x2: (64/2) = 32x32</li><li>After second MaxPool2x2: (32/2) = 16x16</li><li>With 16 output channels from the last Conv2D: 16 * 16 * 16 = 4096. <em>Wait, my code snippet says </em><em>16 * 14 * 14!</em> This highlights a common issue: the exact dimensions depend on padding and kernel sizes. My example implicitly assumes a specific output size after the convolutions. <strong>Always calculate the exact output size after each layer carefully!</strong></li><li>For Conv2D(in_channels, out_channels, kernel_size) with no padding, output dimension is input_dim - kernel_size + 1.</li><li>For MaxPool2x2, it’s input_dim / 2.</li><li>A (64,64) image with two Conv2D(kernel_size=3) layers (no padding) and two MaxPool2x2 layers would lead to:</li><li>Conv1: 64 - 3 + 1 = 62x62</li><li>MaxPool1: 62 / 2 = 31x31</li><li>Conv2: 31 - 3 + 1 = 29x29</li><li>MaxPool2: 29 / 2 = 14x14 (integer division)</li><li>So, 16 * 14 * 14 is correct for a 64x64 image with these parameters!</li></ul><h3>Step 4: Training Time — The Learning Begins!</h3><p>Now that our network is built, we need to train it. This involves feeding it data, calculating loss, and updating weights.</p><p>Python</p><pre>def binary_cross_entropy_loss(y_true, y_pred):<br>    # Clip predictions to avoid log(0)<br>    y_pred = np.clip(y_pred, 1e-12, 1 - 1e-12)<br>    return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))<br>def binary_cross_entropy_loss_prime(y_true, y_pred):<br>    # Derivative of BCE loss<br>    y_pred = np.clip(y_pred, 1e-12, 1 - 1e-12)<br>    return ((1 - y_true) / (1 - y_pred) - y_true / y_pred) / len(y_true)<br>def train(model, X_train, y_train, epochs, batch_size):<br>    num_samples = X_train.shape[0]<br>    <br>    for epoch in range(epochs):<br>        # Shuffle data for each epoch<br>        permutation = np.random.permutation(num_samples)<br>        X_shuffled = X_train[permutation]<br>        y_shuffled = y_train[permutation]<br>        <br>        for i in range(0, num_samples, batch_size):<br>            X_batch = X_shuffled[i:i+batch_size]<br>            y_batch = y_shuffled[i:i+batch_size]<br>            <br>            # Forward pass<br>            predictions = model.forward(X_batch)<br>            <br>            # Calculate loss<br>            loss = binary_cross_entropy_loss(y_batch, predictions)<br>            <br>            # Backward pass (calculate gradients and update weights)<br>            d_loss = binary_cross_entropy_loss_prime(y_batch, predictions)<br>            model.backward(d_loss)<br>            <br>        print(f&quot;Epoch {epoch+1}/{epochs}, Loss: {loss:.4f}&quot;)</pre><p>Proper Use of Learning Rate During Backprop:</p><p>Notice how the learning rate is used directly in each layer’s backward method to update weights. If your loss is exploding or not decreasing, a learning rate that’s too high or too low is often the culprit. Experiment with values like 0.01, 0.001, or even 0.0001. It’s a hyperparameter, and finding the sweet spot is key!</p><h3>Step 5: Evaluation — How Did Our Hot Dog Detector Do?</h3><p>After training, we need to evaluate our model’s performance on unseen data.</p><p>Python</p><pre>def evaluate(model, X_test, y_test):<br>    predictions = model.forward(X_test)<br>    # Convert probabilities to binary predictions (0 or 1)<br>    binary_predictions = (predictions &gt; 0.5).astype(int)<br>    <br>    accuracy = np.mean(binary_predictions.flatten() == y_test.flatten())<br>    <br>    # Confusion Matrix<br>    tp = np.sum((binary_predictions.flatten() == 1) &amp; (y_test.flatten() == 1))<br>    tn = np.sum((binary_predictions.flatten() == 0) &amp; (y_test.flatten() == 0))<br>    fp = np.sum((binary_predictions.flatten() == 1) &amp; (y_test.flatten() == 0))<br>    fn = np.sum((binary_predictions.flatten() == 0) &amp; (y_test.flatten() == 1))<br>    <br>    print(f&quot;\nAccuracy: {accuracy:.4f}&quot;)<br>    print(&quot;Confusion Matrix:&quot;)<br>    print(f&quot;TP: {tp}, TN: {tn}, FP: {fp}, FN: {fn}&quot;)<br>    # <br>    return accuracy, (tp, tn, fp, fn)</pre><h3><strong>OUTPUT:</strong></h3><pre>Starting training...<br>Epoch 01 | loss=0.7682 | train_acc=0.512 | val_acc=0.502 | 218.5s<br>Epoch 02 | loss=0.6997 | train_acc=0.524 | val_acc=0.525 | 217.3s<br>Epoch 03 | loss=0.6862 | train_acc=0.542 | val_acc=0.502 | 218.1s<br>Epoch 04 | loss=0.6807 | train_acc=0.547 | val_acc=0.562 | 219.0s<br>Epoch 05 | loss=0.6827 | train_acc=0.567 | val_acc=0.555 | 220.1s<br><br>Final evaluation on held-out test set:<br>Test Accuracy: 0.581<br>Confusion Matrix [tn fp; fn tp] -&gt; [[289 150]; [179 167]]</pre><h3>Training Log Analysis</h3><p>The training log shows the model’s performance at the end of each epoch. An epoch is one full pass through the entire training dataset.</p><ul><li><strong>Epoch 01 | loss=0.7682 | train_acc=0.512 | val_acc=0.502 | 218.5s:</strong></li><li><strong>loss=0.7682</strong>: This is the average Binary Cross-Entropy (BCE) loss on the training data for this epoch. A higher loss means the model&#39;s predictions are less confident or further from the true labels. This starting value is quite high, as expected for an untrained model.</li><li><strong>train_acc=0.512</strong>: The training accuracy is 51.2%. This means the model correctly classified about half of the images it saw during this epoch&#39;s training. This is only slightly better than random guessing (which would be 50% for a binary task).</li><li><strong>val_acc=0.502</strong>: The validation accuracy is 50.2%. The validation set is a small, separate portion of the data the model <em>doesn&#39;t</em> train on. It gives us a sneak peek into how well the model generalizes to new data. At this stage, the training and validation accuracy are very similar, which is normal for the first epoch.</li><li><strong>218.5s</strong>: The time it took to complete this epoch.</li><li><strong>Progression over Epochs:</strong></li><li>From Epoch 1 to 5, we see the loss consistently <strong>decreasing</strong> (0.7682 -&gt; 0.6827). This is a great sign! It means our model is successfully learning and adjusting its weights to make better predictions.</li><li>The <strong>training accuracy (</strong><strong>train_acc)</strong> is steadily <strong>increasing</strong> (0.512 -&gt; 0.567). The model is getting better at classifying the data it has seen before.</li><li>The <strong>validation accuracy (</strong><strong>val_acc)</strong> is also showing a general <strong>increase</strong> (0.502 -&gt; 0.555), although it fluctuates. This increase is the most important metric because it tells us the model is actually learning to <strong>generalize</strong> and not just memorize the training data.</li></ul><h3>Final Evaluation and Confusion Matrix</h3><p>The final evaluation is the most important step. We use a completely separate <strong>test set</strong> that the model has never seen before to get an unbiased measure of its performance.</p><ul><li><strong>Test Accuracy: 0.581</strong>: The model correctly classified 58.1% of the images in the test set. While not perfect, it’s a significant improvement over random guessing and a good result for a simple, from-scratch CNN. It shows the learning process was successful.</li><li><strong>Confusion Matrix [tn fp; fn tp] -&gt; [[289 150]; [179 167]]</strong>:</li><li>A confusion matrix is a table used to describe the performance of a classification model. The format [[tn fp]; [fn tp]] stands for:</li><li><strong>tn</strong> (True Negatives): The number of &quot;not hot dog&quot; images that the model correctly predicted as &quot;not hot dog&quot;. In our case, 289.</li><li><strong>fp</strong> (False Positives): The number of &quot;not hot dog&quot; images that the model <strong>incorrectly</strong> predicted as &quot;hot dog&quot;. We have 150 of these. This is also known as a <strong>Type I error</strong>.</li><li><strong>fn</strong> (False Negatives): The number of &quot;hot dog&quot; images that the model <strong>incorrectly</strong> predicted as &quot;not hot dog&quot;. We have 179 of these. This is also known as a <strong>Type II error</strong>.</li><li><strong>tp</strong> (True Positives): The number of &quot;hot dog&quot; images that the model correctly predicted as &quot;hot dog&quot;. We have 167 of these.</li></ul><p><strong>Interpretation:</strong></p><ul><li>The model is better at identifying <strong>true negatives</strong> (289 correct predictions for “not hot dog”) than <strong>true positives</strong> (167 correct predictions for “hot dog”).</li><li>It makes a significant number of mistakes: 150 times it thought something was a hot dog when it wasn’t, and 179 times it thought something wasn’t a hot dog when it was.</li><li>The total number of images in the test set is the sum of all four numbers: 289 + 150 + 179 + 167 = 785.</li><li>The test accuracy of 58.1% can be verified from the matrix: (True Positives + True Negatives) / Total = (167 + 289) / 785 = 456 / 785 ≈ 0.581.</li></ul><p>The confusion matrix provides a much richer view of performance than accuracy alone, revealing the specific types of errors the model tends to make.</p><h3>Final Thoughts: The Journey from NumPy to a Hot Dog Detector</h3><p>And there you have it! A fully functional (if a little wobbly) CNN, built one NumPy array at a time. This project isn’t about outperforming the state-of-the-art; it’s about the profound learning that happens when you’re forced to confront the mechanics of deep learning head-on.</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Debugging is a feature, not a bug:</strong> Tensor shape mismatches are inevitable. Learning to print shapes and trace the flow of data is the most valuable skill you’ll acquire.</li><li><strong>The Power of Backpropagation:</strong> Seeing how the backward pass updates parameters in a chain is a true &quot;Aha!&quot; moment. It&#39;s the engine of all deep learning.</li><li><strong>Appreciation for Frameworks:</strong> The next time you use PyTorch or TensorFlow, you’ll have a newfound respect for the engineers who built these robust, efficient, and user-friendly tools.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed46e2d2d554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Web Scraping: A Practical Guide with Selenium (with an example)]]></title>
            <link>https://medium.com/@msvs.akhilsharma/mastering-web-scraping-a-practical-guide-with-selenium-with-an-example-5ca5665e70c1?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ca5665e70c1</guid>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[web-scraping-tools]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 20:24:34 GMT</pubDate>
            <atom:updated>2024-01-08T10:09:21.926Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Selenium</strong> is a powerful tool primarily used for automated testing of web applications. However, it can also be used for <strong>web scraping</strong>, though it may not be the most efficient choice for this purpose. Selenium is commonly employed in conjunction with other libraries like <strong>BeautifulSoup</strong> or <strong>Scrapy</strong> for more effective scraping.</p><p><a href="https://www.selenium.dev/">Selenium</a></p><h4>Picking the Right Tool: Selenuim vs <strong>BeautifulSoup/Scrapy</strong></h4><p>1. Handling Dynamic Content:<br><strong>Selenium</strong>: Ideal for websites with dynamic content or heavy use of JavaScript. It can interact with pages like a real user, executing JavaScript and handling dynamic updates.<br><strong> BeautifulSoup/Scrapy</strong>: Suited for static HTML content, struggling with JavaScript-heavy sites that dynamically load data.</p><p>2. Interaction Complexity:<br><strong>Selenium</strong>: Preferred for complex tasks like clicking buttons, filling forms, or navigating multiple pages due to its ability to simulate user interactions.<br><strong>BeautifulSoup/Scrapy</strong>: Better for straightforward scraping where minimal interaction with the webpage is needed.</p><p>3. Robustness against Anti-Scraping Measures:<br><strong>Selenium</strong>: Less likely to be affected by anti-scraping measures since it closely mimics user behavior.<br><strong>BeautifulSoup/Scrapy</strong>: Websites may detect and block automated scraping more easily as they don’t execute JavaScript, appearing more like automated bots.</p><p>In short, it’s better to choose Selenium to BeautifulSoup or Scrapy for <strong>dynamic content</strong> and <strong>complex interactions</strong>.</p><h3>Key Functions you can perform with Selenium for web scraping</h3><p>1. <strong>Navigation</strong>:<br>get(URL) — Open a specified URL in the browser.<br>back() — Go back to the previous page.<br>forward() — Move forward to the next page.<br>refresh() — Refresh the current page.</p><p>2. <strong>Element Location</strong>:<br>find_element(by=XYZ, value=ABC) — Locate the first HTML element on the page based on the given criteria (by ID, class name, XPath, etc.).<br>find_elements(by=XYZ, value=ABC) — Locate all HTML elements on the page based on the given criteria.</p><p>3. <strong>Interactions</strong>:<br>click() — Click on a web element.<br>send_keys() — Type text into an input field.<br>clear() — Clear the text from an input field.<br>submit() — Submit a form.</p><p>4. <strong>Waiting</strong>:<br>implicitly_wait(time) — Set a maximum time to wait for the browser to load before throwing an exception.<br>WebDriverWait(driver, timeout).until() — Explicitly wait for a certain condition to be met before proceeding.</p><p>5. <strong>Browser Control</strong>:<br>maximize_window() — Maximize the browser window.<br>minimize_window() — Minimize the browser window.<br>close() — Close the current window.<br>quit() — Quit the entire browser.</p><p>6. <strong>Switching Between Windows and Frames</strong>:<br>switch_to.window(window_name) — Switch to a different browser window.<br>switch_to.frame(frame_reference) — Switch to a different frame on the page.</p><p>7. <strong>Capturing Screenshots</strong>:<br>save_screenshot(filename) — Capture a screenshot of the current page and save it to a file.</p><p>The above functions enable you to automate interactions with web pages, manipulate data, and navigate through websites, making Selenium a helpful tool for your daily web scraping tasks.</p><h3>Example: Web Scraping IMDb: Behind the Scenes of Automated Review Collection and Organization</h3><p>For this section, I’m extracting movie reviews specifically from movies that have sparked controversy and are believed to have experienced review bombing. The selected films include The Little Mermaid, Peter Pan &amp; Wendy, Star Wars: The Last Jedi, and Captain Marvel.</p><ol><li><strong>Installation</strong>:</li></ol><p>Firstly, you need to install the Selenium library and Chromium driver using a package manager like pip. The Chromium driver is necessary for Selenium to interact with the Chromium browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_auZcDpONNGQbzMOqjL-Q.png" /></figure><p><strong>2. Set IMDb URLs and Movie Titles:</strong></p><p>As we aim to extract particular movie reviews, we need to identify and list the movies for which we intend to scrape reviews. In this context, we are providing the URLs of these movies in the form of a tuple.</p><p>Then, it sets up a virtual browser in the background, so you won’t see it working on your screen.</p><p><strong>3. Initialize WebDriver:</strong></p><p>Start a Chrome WebDriver with the specified options.</p><p>“<strong>driver = webdriver.Chrome(“/usr/bin/chromedriver”, options=options)</strong>”</p><ul><li>Role: Initializes a Chrome WebDriver, specifying the location of the ChromeDriver executable and additional options.</li><li>Functionality: Launches a virtual Chrome browser controlled by Selenium.</li></ul><p><strong>4. Initialize Empty Lists:</strong></p><p>Here, we’re initializing empty lists to serve as containers for the scraped data. These lists will later be used to organize the collected information, which will be transformed into a DataFrame and ultimately saved as a CSV file.</p><p><strong>5. Loop Through IMDb URLs:</strong></p><p>1. For every IMDb URL and corresponding movie title in the `movie_info` list.<br>2. Open the IMDb webpage associated with the given URL.<br>3. Repeatedly try to click a “Load More” button to unveil additional reviews, with a maximum of 5000 attempts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujLmtwxJ_6BklJLM6kNLTg.png" /></figure><p><strong>driver.get(movie_url)</strong></p><ul><li>Role: Navigates the WebDriver to the specified URL (IMDb movie page).</li><li>Functionality: Opens the IMDb webpage for each movie in the list.</li></ul><p><strong>6. Locate Review Blocks:</strong></p><p>Using a CSS selector, find the HTML elements representing individual review blocks on the webpage.</p><p><strong>reviews = driver.find_elements(By.CSS_SELECTOR, ‘.lister-item-content’)</strong></p><ul><li>Role: Locates and clicks on the “Load More” button on the IMDb page.</li><li>Functionality: Initiates the action of loading additional reviews by simulating a button click.</li></ul><p><strong>7. Extract Review Details:</strong></p><ul><li>For each review block, extract details such as title, content, rating, date, and username.</li><li>Append the extracted information to their respective lists.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVldpVQ4B9cFiJd0x1vm7Q.png" /></figure><p><strong>8. Create DataFrame:</strong></p><p>Create a dictionary using the collected information. Use the Pandas library to create a DataFrame from the dictionary.</p><p><strong>9. Export to CSV:</strong></p><p>Let&#39;s save this table of information into a CSV file, which is a simple file that can be opened in Excel or any spreadsheet program. So, when the script finishes, you have a file named ‘movie_reviews.csv’ with all the movie reviews neatly organized.</p><p><strong>10. Close WebDriver:</strong></p><p>Finally, quit the Chrome WebDriver, closing the browser.</p><p><strong>driver.quit()</strong></p><h3>Limitations of Selenium for Web Scraping</h3><ol><li>Resource Intensive: Selenium, particularly when used with a real browser, can be resource-intensive. Running multiple instances simultaneously or scraping large-scale data may demand significant computational resources.</li><li>Speed: Selenium can be slower compared to other scraping tools like BeautifulSoup or Scrapy. The process of automating a complete browser, including rendering and processing JavaScript, contributes to its relatively slower speed.</li><li>No Built-in Parsing: While Selenium can locate and interact with elements on a page, it lacks built-in HTML parsing capabilities. For parsing, additional libraries like BeautifulSoup are often used in conjunction with Selenium.</li></ol><h3>conclusion</h3><p>In conclusion, mastering web scraping with Selenium involves leveraging its capabilities for automating browser interactions, <strong>though it may not be the most efficient choice for scraping tasks alone</strong>.</p><p><strong>Combining Selenium with libraries like BeautifulSoup or Scrapy</strong> proves effective, with Selenium excelling in handling dynamic content and complex user interactions.</p><p><strong>Understanding Selenium’s key functions</strong>, such as navigation, element location, and interactions, is essential.</p><p>The provided example of scraping IMDb reviews showcases Selenium’s practical application, emphasizing its role in <strong>automating complex web interactions and data extraction</strong>.</p><p>However, users should be mindful of its resource-intensive nature and potential limitations, <strong>choosing the right tool based on the specific requirements of the scraping task at hand</strong>.</p><p>Code for reference:</p><p><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Web-Scraping-Sentimental-analysis-and-Review-summerization./blob/main/Scrapping%20of%20IMDB%20Reviews%20Using%20Selenium.ipynb">Web-Scraping-Sentimental-analysis-and-Review-summerization./Scrapping of IMDB Reviews Using Selenium.ipynb at main · SriVenkataSatyaAkhilMalladi/Web-Scraping-Sentimental-analysis-and-Review-summerization.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ca5665e70c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of SHAP Analysis: A Comprehensive Guide to Feature Selection]]></title>
            <link>https://medium.com/@msvs.akhilsharma/unlocking-the-power-of-shap-analysis-a-comprehensive-guide-to-feature-selection-f05d33698f77?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05d33698f77</guid>
            <category><![CDATA[model]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[lightgbm]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 20:41:06 GMT</pubDate>
            <atom:updated>2023-10-01T20:41:06.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Feature selection is a critical step in the machine learning pipeline that involves choosing the most relevant and informative features (variables) from the dataset to build a predictive model.</p><p>It helps by selecting relevant features, reducing overfitting, and enhancing model generalization, making it a fundamental step in the model-building process.</p><p><strong>SHAP (SHapley Additive exPlanations) </strong>is a powerful tool for unveiling the influence of individual features on model predictions. <strong>It assigns a value to each feature, showing how much it contributes to the model’s output.</strong></p><p>This method has gained significant attention in the machine learning community due to its interpretability, enabling users to understand complex model behaviors and make informed decisions.</p><p>Furthermore, SHAP analysis is effective in feature selection by identifying the most impactful variables, aiding in building more efficient and transparent models. Now in this article I will try to explain how we can use SHAP in feature selection for our model.</p><p><strong>Calculation of SHAP Values: </strong>The <strong>Shapley value</strong> of a feature value tells us how much that feature contributed to the final result (like a prize or payout) when you consider all the different ways that features can come together.</p><p>It’s like figuring out how much credit each feature should get for the outcome, taking into account all the different ways they could have worked together. This helps us understand which features were more important in making the final decision or getting the final result(output).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUflZxrfdXGOaI2c8ZZR5Q.png" /></figure><p><strong>Analyzing the Worked Example: </strong>Below I will be explaining how I used SHAP for feature selection for my model. Also I will explain when and when not to use it.</p><p><a href="https://www.kaggle.com/datasets/rodolfomendes/abalone-dataset">Abalone Dataset</a></p><p>Above is the dataset we will be working on…</p><p>The dataset contains essential attributes of abalones, including their sex and physical measurements (length, diameter, height, whole weight, shucked weight, viscera weight, shell weight) which will be out input columns, along with an age proxy represented by the “Rings” column, which will be our output column.</p><p>To leverage SHAP for feature selection in this dataset, we will begin by treating all the provided input columns, representing various abalone attributes, as our potential features. These features will be preprocessed through techniques such as standardization and normalization to ensure uniform scaling.</p><p>Next, we’ll select an appropriate machine learning model and fine-tune its hyperparameters to create a robust predictive model. Once the model is established, we can conduct SHAP analysis to identify which features significantly influence the model’s predictions. Features with higher SHAP values positively affect the model’s prediction accuracy, and this analysis will help us prioritize and select the most informative features for our outcome prediction task.</p><p>In summary, the process involves data preprocessing, model selection, and SHAP analysis to pinpoint the essential features that contribute positively to the prediction of abalone age, streamlining feature selection for our model.</p><p><strong>Model Selection:</strong></p><p>In the feature selection process, several machine learning models were tested, and their performance was evaluated using two key metrics: Mean Squared Error (MSE) and R-squared (R²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpzQNxn_9c7ReA7MjGKI-Q.png" /></figure><p>Based on the above evaluation of the models we have chosen, <strong>LightGBM exhibited the best performance with the lowest Mean Squared Error (MSE) and the highest R-squared (R²) value.</strong> ( MSE represents the model’s predictive accuracy, with lower values indicating better performance. R-squared measures how well the model explains the variance in the data, with higher values indicating better explanatory power.)</p><p><strong>SHAP :</strong></p><p>First lets begin by installing the SHAP library using pip install shap and import it (import shap) into your Python environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cv_Cgs6Wc3WRqQZ6e8UFPQ.png" /></figure><p>Now lets fit our chosen LightGBM model to your dataset and create a TreeExplainer object to interpret the model by running explainer = shap.TreeExplainer(model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6d3c8cWAyzmenyuemLf8Hw.png" /></figure><p>Lets utilize SHAP’s visualization and analysis tools to gain insights into our model’s feature importances and prediction explanations, aiding in feature selection and model refinement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ln2MmwIv6FWAAOP4B-idog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTejQnXuL-DAjVTELv-iRg.png" /></figure><p><strong>SHAP Values Analysis: </strong>The SHAP value plot highlights that “Shell weight,” “Shucked weight,” “Whole weight,” “Sex,” and “Viscera weight” are the most significant features for predicting the output. These features contribute significantly to the model’s predictions compared to others.</p><p><strong>Single-Point Force Graph: </strong>When examining below single-point force graph, it becomes evident that these significant features positively contribute to predicting a specific output value. This means that an increase in these feature values generally leads to higher predicted outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJjEgU1joWVXGBR6oe_v4A.png" /></figure><p><strong>Feature Impact on Prediction: </strong>Among these influential features, “Shell weight,” “Viscera weight,” and “Shucked weight” exhibit the most substantial impact on predicting this particular value. These features play a predominant role in determining the output for this specific data point, emphasizing their importance in understanding the model’s behavior for individual predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbSTY5TpLxAEBNEUhfUgnw.png" /></figure><p><strong>Identifying Top Features:</strong> Based on the mean SHAP values in our model, “Shell weight,” “Shucked weight,” and “Whole weight” emerge as the top three most significant features. “Sex” and “Viscera weight” also exhibit notable importance.</p><p><strong>Threshold Selection: </strong>The conventional threshold for feature importance is typically set at 0.5, indicating a strong positive impact on predictions. However, in our case, applying this threshold led to the removal of 5 out of 8 features and resulted in underfitting. This can occur when you have too few features, and each of them contributes significantly to the outcome.</p><p><strong>Adjusting the Threshold: </strong>To address the underfitting issue, I decided to lower the threshold to 0.25, allowing us to retain 5 features. By doing this, we aim to strike a balance between feature selection and model complexity. The adjusted threshold may help us maintain a sufficient level of model complexity while avoiding underfitting.</p><p>After conducting <strong>SHAP analysis</strong> and adjusting the feature importance threshold, the final set of selected features for our model consists of <strong>‘Sex,’ ‘Whole weight,’ ‘Shucked weight,’ ‘Viscera weight,’ and ‘Shell weight.’</strong></p><p>These features were identified as the most influential in predicting the target variable, and their inclusion in the model aims to strike a balance between interpretability and predictive accuracy, addressing the previous issue of underfitting. This selection represents a carefully considered feature subset that optimizes the model’s performance.</p><h4><strong>Final Outcome:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXMWQGh2eXYj9ci2KnmJnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFsO8wfQrbfpsQlGzIMEwQ.png" /></figure><p>Indeed, the outcomes of fitting the model with the selected features show a relatively small but meaningful improvement. The Mean Squared Error (MSE) decreased by 0.1, and the R-squared (R²) increased by 0.01.</p><p>Although these changes may appear modest, they are noteworthy in this context because every column in the dataset was equally important, and even a slight positive change can be significant.</p><p>This highlights the potential of using the SHAP analysis method for feature selection in various problem domains. By identifying and focusing on the most influential features, it becomes possible to enhance model performance and obtain better results.</p><p>This approach can be particularly valuable when dealing with datasets where feature importance varies widely, as it allows you to pinpoint and leverage the key drivers of predictions, ultimately leading to improved model outcomes.</p><p><strong>Cons of Shap analysis for Feature Selection:</strong></p><p><strong>Computational Complexity: </strong>SHAP analysis can be computationally expensive, especially for complex models or large datasets. Calculating SHAP values for every data point and feature combination may require significant computational resources.</p><p>When attempting to apply SHAP analysis to a problem involving a larger number of columns without prior feature selection, I encountered significant computational challenges. The process took considerably more time, and in some cases, it failed due to limitations in computational power and available RAM.</p><p>This experience highlights the resource-intensive nature of SHAP analysis, particularly when dealing with complex models and high-dimensional datasets. It underscores the importance of optimizing computational resources, employing feature selection strategies, or resorting to parallel computing techniques when working with large datasets to ensure the successful execution of SHAP analysis.</p><p><strong>Model Dependency:</strong> SHAP analysis is model-agnostic in theory, but the actual implementation often depends on model-specific explanations. Some models may not have straightforward SHAP implementations, limiting its applicability.</p><p><strong>Feature Interactions:</strong> SHAP values assume feature independence, but in reality, features often interact with each other. SHAP values may not fully capture complex interactions, which can lead to misinterpretations of feature importance</p><p><strong>Threshold Selection:</strong> Determining the appropriate threshold for feature importance can be subjective and may require experimentation. Setting a threshold too high or too low can lead to suboptimal feature selection.</p><p><strong>Resource Intensive for High-Dimensional Data: </strong>In high-dimensional datasets, SHAP analysis can become impractical due to the large number of potential feature combinations.</p><p><strong>Code:</strong></p><ul><li><a href="https://www.kaggle.com/code/akhilmalladi/shap-for-feature-selection-abalone-age-pred">SHAP for feature selection(Abalone Age Pred)</a></li><li><a href="https://www.kaggle.com/code/akhilmalladi/shap-for-feature-selection-in-classification">SHAP for feature selection in Classification.</a></li></ul><p><strong>References:</strong></p><ul><li><a href="https://christophm.github.io/interpretable-ml-book/shapley.html">9.5 Shapley Values | Interpretable Machine Learning</a></li><li><a href="https://www.linkedin.com/pulse/understanding-shapley-explanatory-values-shap-evan-dunbar/">Understanding Shapley Explanatory Values (SHAP)</a></li><li><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Model-Interpretability-and-Shap-analysis-in-machine-learning">GitHub - SriVenkataSatyaAkhilMalladi/Model-Interpretability-and-Shap-analysis-in-machine-learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05d33698f77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Personalized Stock Newsletter Subscription App: Using Generative AI.]]></title>
            <link>https://medium.com/@msvs.akhilsharma/building-a-personalized-stock-newsletter-subscription-app-integrating-amazon-sns-gpt-3-5-855d0a55ee35?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/855d0a55ee35</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Sat, 27 May 2023 23:41:37 GMT</pubDate>
            <atom:updated>2023-11-06T17:04:28.334Z</atom:updated>
            <content:encoded><![CDATA[<p>This project was developed by our team for the Big Data Systems &amp; Intelligent Analytics course. Our goal was to create an interactive platform delivering personalized stock updates and insights to subscribers. In this article, I will guide you through the implementation details and steps involved.</p><p><strong>Project Overview</strong></p><p>Our stock newsletter app delivers personalized investment insights, market trends, and curated news articles to subscribers. It aims to provide comprehensive and valuable information for informed investment decisions.</p><p><strong>Technologies Involved</strong></p><p>Here are the key components of our application: Streamlit, Amazon SNS, Alpha Vantage API/ Yahoo Finance API, NewsAPI, Google Trends, GPT-3.5 API, FastAPI, Apache Airflow, Docker, and Amazon EC2</p><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rF0GW-A3kEPPhKFh" /></figure><h3><strong>Process Flow</strong></h3><p>Here the process flow starts with the user’s interaction with the system. The user interacts with the system through the Streamlit application.</p><ol><li><strong>User Interaction</strong>: The user accesses the system through the Streamlit interface, where they can input their preferences and subscribe to the stock newsletter.</li><li><strong>Recommendation/ Newsletter Generation System</strong>: After receiving user inputs, the recommendation system components come into play:</li></ol><ul><li>The “Alpha Vantage” and “NewsAPI” APIs are used to gather stock data and news articles, respectively. These APIs retrieve relevant information and pass it to the machine learning model and storage components(Amazon s3 Bucket).</li><li>The “ML Model” (or) machine learning model is responsible for generating stock recommendations. It utilizes the retrieved stock data, analyzes trends, and applies sentiment analysis on news articles to provide personalized recommendations.</li><li>The “Amazon S3” is a cloud-based storage service used to store data, including stock information and machine learning models. The model’s outputs and other relevant data are stored here for future access.</li><li>The “GPT 3.5” generates personalized recommendations and newsletter content based on the inputs from the machine learning model.</li><li>The “Amazon SNS” (or) Amazon Simple Notification Service, handles the delivery of customized newsletters to subscribers. It receives the generated recommendations from the GPT model and sends them to the subscribers.</li></ul><p>3. <strong>Dashboard</strong>: Simultaneously, when the user Logins they can access dashboard components that gather and display additional data for users.</p><ul><li>The “Google Trends” component retrieves and displays Google Trends data related to stocks, providing users with insights into popular search trends.</li><li>The “Yahoo Finance” component retrieves and displays financial data from Yahoo Finance, offering users further information on stock performance and financial metrics.</li></ul><p>4. <strong>Airflow</strong>: Apache Airflow is an open-source platform used for orchestrating and managing workflows. Airflow is responsible for coordinating the different steps and tasks involved in the stock recommendation system. It will schedule and trigger data retrieval, model training, recommendation generation, and other related processes once the User Is logged in. Airflow helps automate and streamline the workflow, ensuring that each step is executed appropriately and in the correct sequence.</p><p><strong>5. Docker</strong>: Docker is utilized within the Docker Compose cluster. Docker provides containerization technology that allows for the efficient deployment and management of applications and services. Docker is responsible for hosting and running the various components of the system, including Streamlit, the recommendation system, and the dashboard components. By utilizing Docker, the application’s dependencies and environment can be encapsulated within containers, ensuring consistent and reproducible deployments across different environments.</p><p>6. <strong>Cloud Deployment</strong>: Finally, we deployed our application to Amazon EC2 and were able to monitor it with CloudWatch.</p><p>The process flow involves the user interacting with the Streamlit application, the recommendation system generating personalized stock recommendations, and the dashboard components providing additional data and insights. The process ends with the delivery of the customized newsletter to the subscribers through the Amazon SNS service.</p><h3><strong>Functionalities</strong></h3><ol><li><strong>User Management</strong>: The first step in building the app is implementing user management functionalities. Users will be able to register and log in to access the app’s features. We will use Streamlit to create login and registration pages, where users can provide their contact information, such as email addresses.</li><li><strong>Plan Upgrades</strong>: To provide additional features, we will implement a plan upgrade functionality. Users can choose to upgrade their plan from free to premium, granting them access to more advanced functionalities(More Fast API Tokens).</li><li><strong>Stock Dashboard</strong>: The core of the application is the stock dashboard, where users can view real-time stock data presented through charts and graphs. We will utilize the Yahoo Finance API to retrieve stock prices and other relevant information. Streamlit will be used to create an interactive dashboard that displays the data in an easily understandable format.</li><li><strong>Data Processing and Analysis</strong>: To generate accurate stock recommendations, we will perform data processing and analysis. The application will include a sentiment analysis model to analyze news articles obtained from the NewsAPI. The sentiment polarity scores will be merged with the financial data retrieved from Alpha Vantage. Machine learning models will be employed to analyze the data and generate recommendations based on stock performance and news sentiment.</li><li><strong>Newsletter Generation and Delivery</strong>: Using the generated recommendations, we will create personalized newsletters for each user. The GPT API will be utilized to generate engaging content for the newsletters. To deliver the newsletters, we will integrate the Amazon Simple Notification Service (SNS). SNS will send customized newsletters to users based on their preferences and contact information.</li><li><strong>Task Scheduling and Management</strong>: To automate the data processing and recommendation generation tasks, we will employ Apache Airflow. Airflow will schedule and trigger the necessary tasks, known as Directed Acyclic Graphs (DAGs). We will create DAGs for data scraping, recommendation generation, and newsletter creation. Airflow will ensure that these tasks are executed at the desired intervals and maintain data integrity.</li><li><strong>Deployment and Execution</strong>: To run the application, we will deploy it on the cloud(Amazon EC2). Docker is used for containerization and easier deployment. We can monitor the application using CloudWatch to track logs and performance.</li></ol><h3>Streamlit UI layout</h3><ul><li>Login Functionality: Login page for returning users to enter username and password to get access to the application</li><li>Register: Register page for new users to enter their full name, email, username, password, confirm password, user type, and plans to access the application</li><li>Forgot Password: Forgot Password page for users to change their password using their username to get access</li><li>Logout: Logout users to end the session and return to the Login page</li><li>Dashboard and Recommendation: Once logged in User gets access to a customized stock Dashboard and Recommendations, Also when they press on the “Generate Custom Newsletter!” button they get delivered with a customized newsletter to their registered Email ID.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQr1jOe7NNNEgtIi42APtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Puq-zyp34mfFPBXOqVB5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrZQNb-nAU6bRS2rdtsq4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvEUL0M6OuMZFqzoKVZ94g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAvk9KAPH59N7a9NeezInQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFJh-SJDIo9DWXB7zTPwQQ.png" /></figure><h3>Fast API</h3><p>To truly ensure decoupling, API calls are made in the backend to the Streamlit app to achieve the following:</p><ul><li>Create and Get users: Users are created with their full name, username, email, password(stored as a hash), user type, and Plan</li><li>Plan: The users are offered 2 plans: Free and Premium with varying levels of API request limits.</li><li>Create and verify Login and Access Tokens</li><li>Change the user account password and update the hashed password in the database</li></ul><p>The users in the database are granted an access token for a limited time, also known as a session. This access token acts as authentication to facilitate authorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-rhRc15LS3rSrlNGOLNsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPwPvW0WSIiE4-M0MjRrPg.png" /></figure><h3>AirFlow</h3><p><strong>Scraping DAG</strong>: This DAG is responsible for scraping data from the sources and storing it in a database for further processing. The DAG includes a set of tasks that perform the following steps:</p><ul><li>Invoking the stock-data-scrape API endpoint to obtain stock parameter data and news articles.</li><li>Store the scraped data in a database.</li></ul><p><strong>Recommendations DAG</strong>: This DAG generates stock recommendations based on the scraped data, analyzing trends and patterns to provide insights to users. The DAG includes a set of tasks that perform the following steps:</p><ul><li>Retrieving the stored stock parameter data and news articles from the database.</li><li>Merging the data based on stock symbols and performing data analysis to generate stock trends for the upcoming week.</li><li>Store the recommendations in the database for later retrieval and analysis for the dashboard in the streamlit application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87x5yeDUuB7udZYxDj7LJw.png" /></figure><p><strong>Conclusion</strong></p><p>If you require additional information about the application, please refer to the provided resources. The readme file contains all the necessary information, and there is also a detailed code labs document available.</p><p><a href="https://github.com/SriVenkataSatyaAkhilMalladi/StockRecommendationSystem">GitHub - SriVenkataSatyaAkhilMalladi/StockRecommendationSystem: Damg 7245 Final project</a></p><p>Thanks for reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855d0a55ee35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis and Visualization of Unicorn Start-Ups Data Using Tableau]]></title>
            <link>https://medium.com/@msvs.akhilsharma/analysis-and-visualization-of-unicorn-start-ups-data-using-tableau-cb01e67bfd37?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb01e67bfd37</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Fri, 26 May 2023 23:46:17 GMT</pubDate>
            <atom:updated>2023-05-26T23:46:17.263Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explores a dataset that consists of information about private companies with a valuation of over $1 billion as of March 2022. The dataset discussed in the article can be accessed directly from the Maven Analytics website.</p><p>The data is organized in a single table with 1,074 records. Each record represents a unique unicorn start-up and includes the following attributes: Company Name, Valuation, Funding, Continent, Country, City, Industry, Investors, Year Founded, and Year Became Unicorn.</p><p><a href="https://www.mavenanalytics.io/data-playground?accessType=open&amp;page=2&amp;pageSize=5">Free Data Sets &amp; Dataset Samples | Maven Analytics</a></p><p>For this analysis, I will be utilizing Excel for data manipulation and Tableau for data visualization. These tools offer a powerful combination for conducting insightful analysis and creating visually appealing visualizations.</p><p>In the dataset, a total of 1,074 companies have recently gained a Billion dollar valuation deeming them to be Unicorns. Now, let’s explore the data furthermore to find, Which countries have the most unicorns? Are there any cities that appear to be industry hubs? Which unicorn companies have had the biggest return on investment?</p><h4><strong>Exploring the distribution of unicorn companies across different countries and Cities</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQXgJ6YLKTx098QCm0u3pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMCdiOA_fxPty_MhC1MvbA.png" /></figure><p>From the above Visualizations, we can suggest that the USA has the Highest number of Unicorns followed by China. Also, we can see in which countries are these unicorns present. And as for cities San Francisco has the highest number of Unicorns(ie 152) followed by Newyork. We can also see the Top 10 cities with the most Unicorns above.</p><p><strong>Valuation and Funding by Industry</strong></p><p>Let’s explore the dataset to determine which industry has secured the highest funding and valuation among unicorn start-ups, providing insights into the sectors that excel in financial growth and investor confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ll1hMbDereDBwakLR8Q1oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C35ub-QX-u3gI2jaq_igjw.png" /></figure><p>Based on the analysis, it is evident that the Fintech industry has secured the highest funding and valuation among the Unicorn start-ups. This highlights the industry’s strong financial growth and investor confidence. Conversely, the travel industry has received the least funding and has the lowest valuation, indicating its comparatively challenging position within the unicorn start-up ecosystem.</p><p><strong>Companies with the Highest Valuation and Funding</strong></p><p>Now let’s see which companies got the highest funding and which ones have the highest valuation. And is there a correlation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQfRnKCQXN--2O_vByCSQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTW2OiM8jkoH5Ih_DXS0zA.png" /></figure><p>From above we see that there are some companies that got high funding and ended up having high valuations such as Bytedance(2nd highest funding and most values), SpaceX, and JUUL Labs(1st highest funding and 9th highest valuation. But just based on these three companies we cannot suggest that there is a correlation between funding and valuation.</p><p><strong>How long does it usually take for a company to become a unicorn?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVecWjdQTP-47BObleZl8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrqVtoJn0MLwT_fVQOwelg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_KimdbDFjc6V2liMrE-nA.png" /></figure><p>Upon examination, it is evident that while some of these companies began their journey as unicorns as early as 2007, a few of them have a much longer history, with establishment dates dating back as far as 1919.</p><p>This observation highlights the diverse range of unicorn start-ups, showcasing both relatively newer players and established companies that have successfully attained unicorn status over time.</p><p>Upon closer examination, we discover that Otto Bock Healthcare holds the distinction of taking the longest time, spanning almost a century, to achieve unicorn status. Notably, Otto Bock Healthcare is the sole company in the dataset established in 1919, with no other companies between its establishment and 1994 reaching unicorn status.</p><p>This unique case underscores the significant time and perseverance required for certain companies to attain the coveted unicorn status, making Otto Bock Healthcare a remarkable example of long-term success in the unicorn start-up landscape.</p><p><strong>Are there any cities that appear to be industry hubs?</strong></p><p>Let’s now explore if there are any cities that serve as industry hubs or have the highest concentration of companies within specific industries.</p><p>By analyzing the dataset, we can identify cities that stand out as hotspots for particular industries, indicating their role as key centers of innovation and entrepreneurship.</p><p>This analysis will shed light on the geographic clustering of companies and provide insights into the cities driving growth and specialization within different sectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sj6OoakrGYf6jRAfIYXeA.png" /></figure><p>Based on the analysis, it is apparent that Beijing emerges as the industry hub for the highest number of industries, with influence spanning across five sectors.</p><p>On the other hand, San Francisco stands out with the highest number of unicorns, particularly in the Internet software services industry. Moreover, the Internet software services and Fintech sectors in San Francisco surpass all other industries in terms of the number of unicorns, demonstrating their significant presence and success in the city.</p><p><strong>Companies that gave the highest Return</strong></p><p>Finally, the aspect that generated the most excitement during the analysis was identifying the companies that delivered the highest return on investment (ROI).</p><p>For this purpose, I will be using the below calculation</p><p><strong>ROI = ((Valuation — Funding) / Funding)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rEvFTIeNiUrllcxv6dlEA.png" /></figure><p>Upon analyzing the dataset, we observe notable examples of companies that have generated significant returns on their initial funding. Zapier emerges as a standout, delivering an extraordinary return of nearly 3999 times on the original investment.</p><p>Dunamu follows but not closely, providing a remarkable return of 126 times. Additionally, other companies in the dataset exhibit comparable returns on investment.</p><p>You can find the DashBoard and Code for the above analysis in the below Github link, Thanks for Reading…</p><p><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Analysis-and-Visualization-of-Unicorn-Start-Ups-Data-Using-Tableau/tree/main">GitHub - SriVenkataSatyaAkhilMalladi/Analysis-and-Visualization-of-Unicorn-Start-Ups-Data-Using-Tableau: This project explores a dataset that consists of information about private companies with a valuation of over $1 billion as of March 2022. The dataset discussed in the article can be accessed directly from the Maven Analytics website.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb01e67bfd37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis and Visualization of Airline Flight Delays Data: Unveiling Patterns and Insights]]></title>
            <link>https://medium.com/@msvs.akhilsharma/analysis-and-visualization-of-airline-flight-delays-data-unveiling-patterns-and-insights-eab86e639905?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab86e639905</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Sat, 20 May 2023 19:38:33 GMT</pubDate>
            <atom:updated>2023-05-20T19:38:33.064Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explores a vast dataset of 5,000,000+ commercial flights in 2015, collected for the U.S. DOT Air Travel Consumer Report. Each record captures essential details like airline name, flight number, airports, flight distance, and scheduled/actual departure and arrival times.</p><p>The dataset discussed in the article can be accessed directly from the Maven Analytics website, enabling users to explore and analyze the extensive information on commercial airline flights in 2015.</p><p><a href="https://www.mavenanalytics.io/data-playground?accessType=open&amp;dataStructure=2lXwWbWANQgI727tVx3DRC&amp;page=3">Free Data Sets &amp; Dataset Samples | Maven Analytics</a></p><p>The article utilizes the dataset to uncover insights into flight delays and cancellations, highlighting their implications for airlines, passengers, and industry stakeholders. By analyzing the data, valuable information can be derived to address operational challenges, improve customer satisfaction, and inform decision-making by airlines, regulators, and airports.</p><p>I will be conducting the analysis and visualization in Google Colab, leveraging the following imports: pandas for data manipulation, sqlite3 for SQL capabilities, matplotlib.pyplot for data visualization, calendar for working with dates, and matplotlib.ticker for customizing tickers on plots. This approach allows for effective data visualization and enables data analysis using SQL and pandas functionalities.</p><p>After thoroughly examining the dataset, I have found no null values, duplicates, or other abnormalities that require resolution. The data is clean and ready for analysis, allowing us to proceed without data preprocessing.</p><p>In the dataset, a total of 5,819,079 flights were scheduled in 2015. Now, let’s explore the number of flights canceled or delayed and identify the airlines associated with them.</p><h4><strong>Number of Flights by each Airline</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*05oaAftt9dW6Sh8Oagwq9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*oUtZw9Jg-2mtc7VeZE1t4Q.png" /></figure><p>Southwest Airlines Co had the highest number of scheduled flights, while Virgin America had the lowest.</p><p><strong>How does the overall flight volume vary by month? By the day of the week? By the day of the Month?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*JBoiU4FNJU95adVJ-NfFMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*COFytX3PFnbcYtZLvmO2hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*GJnkzc37MFj-jrWYL6GbgQ.png" /></figure><p>Based on the analysis, flights are observed to be highest in July and lowest in February, aligning with the non-leap year having fewer days. Additionally, a greater number of flights were scheduled during the summer months compared to other months, indicating a seasonal trend.</p><p>The number of flights scheduled on the 31st is approximately half compared to other days, reflecting the presence of fewer months with 31 days. Additionally, there is a lower volume of flights towards the end of the month, potentially influenced by February’s shorter duration, as well as fewer flights on weekends, particularly Saturdays.</p><h3><strong>Cancellations and Reasons</strong></h3><p>Now let’s look into the number of canceled flights and their reasons. And which airline is unreliable when it comes to flight cancellations.</p><p>Number of canceled flights is <strong>89884</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*H0tU2RSV2_qHc_QR-Z-Rbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*fl88nb5DexoufBj-oi8Icw.png" /></figure><p>Upon analyzing the data, it is evident that Southwest Airlines Co. had the highest number of canceled flights (16,043), which correlates with its highest number of departures (22%). However, American Eagle Airlines Inc stands out with 15,025 flight cancellations, accounting for the highest cancellation rate of 5.1% among all airlines. But we have to understand these cancellations involve all kinds of reasons and not just Airline/Carrier Issues.</p><p>Also, we can see that weather stands to be the top reason for flight cancellations followed by Airline/Carrier issues.</p><p><strong>Flight cancellation due to Airline/Carrier Issues</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*teTn-vrN6BUfFIlbtwY_lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*mP9ct831ZGsaqV60EPPL8A.png" /></figure><p>The analysis reveals that Southwest Airlines Co. has the highest number of flights canceled due to airline issues, which aligns with its large volume of departures. Additionally, American Eagle Airlines Inc maintains the highest cancellation rate of 0.84% among all airlines, indicating a relatively higher frequency of cancellations caused by airline-related factors.</p><h3><strong>Delays and Reasons</strong></h3><p>In this session, our focus will be exclusively on departure delays rather than arrival delays, as departure delays are generally considered to have a greater impact and pose more significant challenges for airlines and passengers.</p><p><strong>What percentage of flights experienced a departure delay in 2015? Among those flights, what was the average delay time, in minutes?</strong></p><p>From our analysis, it is evident that in 2015, a total of 415,513 flights experienced departure delays. The average delay time for these flights was 9.4 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jUzQQEajREg2IwY7IPHeaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*3BSJUpWIpvpl1IxkqYJOcg.png" /></figure><p>Upon further analysis, it becomes evident that Southwest Airlines Co. had the highest number of airline delays among all airlines. Additionally, Southwest Airlines Co. ranks second in terms of the percentage of delayed flights, with 44.9% of their flights experiencing delays. United Air Lines Inc takes the lead in this aspect, with 49.7% of their flights being delayed.</p><p>Furthermore, when examining the average departure delay for flights by airline, Spirit Airlines stands out with the highest average delay time of 16 minutes, followed by United Air Lines Inc at 14.5 minutes. In contrast, Hawaiian Airlines demonstrates the lowest average departure delay of only 0.5 minutes.</p><p>Number of Diverted flights in the year 2015-<strong>15187</strong></p><p>Number of Arrival Delayed flights in the year 2015<strong>–114254</strong></p><p><strong>Reason for Delays</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hqy9o5Iy9CEeAJ8ghg0snA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*hdBk2uf3oXr6PdVXRGc0DQ.png" /></figure><p>From the analysis conducted, it is evident that airline delays, air system delays, and late aircraft delays are the most significant contributors to flight disruptions, with comparable frequencies. This indicates a strong correlation among these delay factors in the context of flight disruptions. These delay factors are interconnected and have the potential to impact each other. And Security delays have the least chance of happening.</p><p><strong>Flight Delays due to Airline issues</strong></p><p>Below are the graphs depicting the number of delays caused by airline issues for each airline, as well as a comparison to the total number of flights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*Z6f8jHAP2r68dV6gv9JLYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ScaobIWXfqriFzrbvV8nbg.png" /></figure><p>Again Southwest had the highest number of delays due to airline issues, But Spirit Air Lines has the highest delay rate (14.74%) due to Airline Issues. And Alaska Airlines has least delay rate 4.85% due to Airline Issues.</p><h3>Problematic Airports</h3><p>Lastly, I would like to quickly review airports that experience significant delays and cancellations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*YTw-MzhnTHsAtWzZAJJ6cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*VAGXrTOJR-0774ho5RMv6A.png" /></figure><p>Based on the provided data, the following list showcases the airports with the highest number of flight cancellations and delays. Notably, O’Hare International Airport (ORD) in Chicago holds the record for the highest count in both categories. Additionally, there are several airports that appear in the top rankings for both cancellations and delays.</p><h3>Insights &amp; Recommendations</h3><p>Based on the analysis, the following insights can be drawn:</p><ol><li>Flights show a seasonal trend, with July having the highest volume and February the lowest, potentially influenced by the shorter month.</li><li>There are fewer flights scheduled on the 31st due to fewer months with 31 days, and a lower volume of flights towards month-end and on Saturdays.</li><li>Southwest Airlines had the highest number of flight cancellations (16,043), while American Eagle Airlines had the highest cancellation rate (5.1%).</li><li>Hawaiian Airlines Inc had both lowest number of flight cancellations and cancellation rate (0.22%) as well.</li><li>Southwest Airlines has the highest number of cancellations due to airline issues, while American Eagle Airlines has the highest cancellation rate (0.84%) among all airlines, Suggesting American Eagle Airlines is unreliable when it comes to Flight cancellations.</li><li>In 2015, a total of 415,513 flights experienced departure delays with an average delay time of 9.4 minutes, and Southwest Airlines had the highest number of airline delays. But Spirit Airlines has the highest delay rate (14.74%) due to Airline Issues. Suggesting Spirit Airlines is unreliable when it comes to Flight Delays.</li><li>O’Hare International Airport (ORD) in Chicago has the highest number of flight cancellations and delays, with other airports also appearing in top rankings for both categories.</li></ol><p><strong><em>The code is available on GitHub: </em></strong><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Analysis-and-Visualization-of-Airline-Flight-Delays-Data-Unveiling-Patterns-and-Insights">https://github.com/SriVenkataSatyaAkhilMalladi/Analysis-and-Visualization-of-Airline-Flight-Delays-Data-Unveiling-Patterns-and-Insights</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab86e639905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Auto ML work better than my manually-developed model? Part-2]]></title>
            <link>https://medium.com/@msvs.akhilsharma/does-auto-ml-work-better-than-my-manually-developed-model-part-2-d517fcaabd03?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d517fcaabd03</guid>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[k-fold-cross-validation]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Mon, 08 May 2023 08:51:13 GMT</pubDate>
            <atom:updated>2023-05-08T09:47:08.025Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read my last medium article about me comparing my manually built model to the AUTO ML model, Please check the below link</p><p><a href="https://medium.com/@msvs.akhilsharma/does-auto-ml-work-better-than-my-manually-developed-model-5445b154cf">https://medium.com/@msvs.akhilsharma/does-auto-ml-work-better-than-my-manually-developed-model-5445b154cf</a></p><p>My Model(Light GBM):- Accuracy(0.917), False negative rate(0.47)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHGirk3hPU4kATEF.png" /></figure><p>Auto ML Model :- Accuracy(0.911), False negative rate(0.27)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CYx37Qy8YmcJumh9.png" /></figure><p>To reduce the false negative rate of my model, I plan to leverage AUTO ML’s capabilities. Through a SHAP analysis, I discovered that the features considered significant in my manual model are slightly different from those in AUTO ML’s model. Furthermore, while I selected Light GBM for my model, AUTO ML used GBM. Although my model has a higher overall accuracy than AUTO ML’s, I suspect that my hyper-parameter and feature selection might cause a higher false negative rate.</p><p>Consequently, I intend to include additional features I previously excluded from my manual model. These features are deemed important by AUTO ML. Additionally, I will use Bayesian optimization hyperparameter tuning in my LIGHT GBM model. And for this purpose, I will be using Optuna.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*yFQCukdPVN1l2hDEB2RYGw.png" /></figure><p>Optuna is a hyperparameter optimization framework that automates the tuning process for machine learning models. It uses Bayesian optimization to find the best hyperparameters, supports multiple frameworks, and saves time and effort in the tuning process.</p><p>To address overfitting, K-fold cross-validation will be implemented along with the use of Optuna. This will enable the evaluation of the LightGBM model’s performance with varying hyperparameters and minimize the objective function by calculating the average performance over k-folds.</p><p>FINAL OUTPUT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*_6hbbxowTNlMB4_f20Xoeg.png" /></figure><h4>Accuracy: 0.9668253351466873</h4><h4>False negative ratio: 0.18</h4><h4>False positive ratio: 0.013</h4><h4>Precision: 0.884968242766408</h4><h4>Recall: 0.8109506359129123</h4><h4>F1 Score: 0.8463442069741283</h4><p>In the end, I not only improved the false negative ratio(0.18) compared to AUTO ML(0.27) but also significantly increased the accuracy(0.917~0.966).</p><p>By utilizing AUTO ML, I was able to enhance my own model. However, it’s important to remember that Auto ML should not be used as a replacement for fundamental knowledge of machine learning principles and techniques. Rather, it can simplify the process by providing guidance on which model to select and which features are most important.</p><p><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Medium-Article">GitHub - SriVenkataSatyaAkhilMalladi/Medium-Article: Does Auto ML work better than my manually-developed model?</a></p><p>Refernces</p><p><a href="https://optuna.readthedocs.io/en/stable/">Optuna: A hyperparameter optimization framework - Optuna 4.1.0 documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d517fcaabd03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Auto ML work better than my manually-developed model?]]></title>
            <link>https://medium.com/@msvs.akhilsharma/does-auto-ml-work-better-than-my-manually-developed-model-5445b154cf?source=rss-47537d3e4f66------2</link>
            <guid isPermaLink="false">https://medium.com/p/5445b154cf</guid>
            <category><![CDATA[h2o]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[lightgbm]]></category>
            <dc:creator><![CDATA[Sri]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 03:01:40 GMT</pubDate>
            <atom:updated>2022-12-18T03:59:59.115Z</atom:updated>
            <content:encoded><![CDATA[<p>Automated machine learning (AutoML) is a process of automating the end-to-end process of applying machine learning to a problem, including the selection and optimization of features.</p><p>Does this means will AutoML save us hours from Feature selection, setting Hyperparameters, and trying to find the best Model?</p><p>To Understand it better I will be taking up a Dataset and I will analyze in both methods(AUTOML and my own model) to see which one works better and why?</p><p>For this example, I’m taking the following data set.</p><p><a href="https://www.kaggle.com/datasets/henriqueyamahata/bank-marketing">Bank Marketing</a></p><p>Which is a Binary Classification dataset, Where the classification goal is to predict if the client will subscribe to a term deposit? It has 21 columns, where Y is our to-be-predicted (or) output column and 20 input variables (or) possible features where 10 are categorical in nature and 10 are numerical.</p><h3>ML Data Cleaning and Feature Selection</h3><p>Firstly I cleaned my data, <strong>Removal of unwanted columns</strong>, <strong>Handled missing data</strong>, <strong>Removal Duplicates, and</strong> <strong>Managing Unwanted outliers</strong> if any.</p><p>Later with Labelencoder, I transformed Categorical variables, I used dummies as well but it created too many columns and made the model a bit complex. I found Labelencoding to be better in this example.</p><p>Feature selection: I have chosen two methods to analyze the variables present in DataSet. They are</p><p>1. Pearson Correlation</p><p>2. Select K best</p><p>With help of the above methods and also understanding the Hist plots of each variable and their distributions, I dropped a few variables and ended up choosing the rest as my features.</p><h3>Modeling and Interpretability</h3><p>Now I have to choose the right model for my dataset. For this step I have written a function that runs the modeling steps for me on the following models and returns <strong>Accuracy</strong>, <strong>Mean squared error, R² score, </strong>and<strong> Classification Report </strong>for<strong> </strong>each model.</p><p>1. Logistic Regression</p><p>2. Random Forest</p><p>3. Decision Tree</p><p>4. KNN</p><p>5. SVM</p><p>6. Light bgm</p><p>7. XG Boost</p><p>8.GradientBoosting</p><p>I found that Light GBMis the best of all with high accuracy, precision, and f1-score. Followed closely by GradientBoosting and XG Boost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5HT-euwyvHgOdBJyIzxDQ.png" /></figure><p>But mainly I will be considering the Confusion Matrix for the evaluation of the models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Asl-VMNpZW795l8c1Ru_Q.png" /></figure><p>Error(No)/false positives : 487/3645 = 0.1336</p><p>Error(Yes)/false negatives: 227/473 = 0.62</p><p><strong>Hyperparameter tuning:</strong></p><p>After tuning the hyperparameters as below, we can see a significant improvement in the Confusion Matrix.</p><p>LGBMClassifier(max_depth=20, min_child_samples=40, n_estimators=200, random_state=100, verbose=0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI_DGWyU88HV1-hm4hDiGw.png" /></figure><p>Error(No)/false positives : 120/3645 = 0.0329</p><p>Error(Yes)/false negatives: 227/473 = 0.47</p><h3>AutoML</h3><p>Now I will be using initial cleaned data(without missing values and outliers), But I won’t remove any variables/columns. While AUTOML can do the feature selection itself, it won’t clean the data at times. In general, Auto ML is focused on automating the selection and training of machine learning models, rather than the preprocessing of the data.</p><p>Here I will be using the H2O AutoML framework, H2O is an open-source and distributed in-memory machine-learning platform developed by H2O.ai. H2O supports both R and Python. It supports the most widely used statistical and machine learning algorithms including gradient-boosted machines, generalized linear models, deep learning, and more. H2O includes an Automated Machine Learning module and uses its own algorithms to create pipelines. It uses an exhaustive search for feature engineering methods and model hyper-parameters to optimize pipelines.</p><p>AutoML has chosen the below as my model for the dataset.</p><pre>H2OGradientBoostingEstimator : Gradient Boosting Machine<br>Model Key: GBM_1_AutoML_6_20221217_214255</pre><p>This model created 70 trees and the evaluation metrics are as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbQg9Q1G9ptxPt3hTTlSVg.png" /></figure><h3>Evaluation</h3><p>We can see from the above confusion matrices we can observe that:</p><p>while the false positive error of AUTO ML(0.0655) is more than my Light GBM model(0.0329), The false negative rate is worse for Light GBM model(0.47) compared to AutoML(0.27).</p><p>Considering <strong>False Negatives</strong> we can suggest that AutoML has performed better than the model manually developed by me. It can be because of two reasons.</p><ol><li>Not being able to tune the right Hyperparameters to my model, While the hyperparameters that I have set did definitely work very well. I could have chosen better hyperparameters. (while I did use GradientBoosting in my manual model as well I didn’t set any parameters for it). Probably with the right set of parameters my manual model would have definitely beaten AUTOML’s.</li><li>Better feature selection. AutoML selected the perfect set of features that work exceptionally well together.</li></ol><p>With the right Hyperparameters, the False negatives of my model would have been low as well.</p><h3><strong>SHAP Analysis</strong></h3><p>For an even better understanding and interpretability of the above models, Let’s use shap analysis on them. We have to install and import shap.</p><p><strong>Shap analysis of manual model:</strong></p><p>Important features according to Light bgm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YTEh3PjZPRdDknySxLl-Q.png" /></figure><p>Duration, emp.var.rate, euribor3m, and campaign are the most impactful features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIH8-z494A-NZMsNIv0v7w.png" /></figure><p>From above we can see that duration is very significant, emp.var.rate, and euribor3m is significant as well. A low campaign can have a significant impact as well.</p><p><strong>Shap analysis of manual model:</strong></p><p>Important features according to AUTOML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6smWHErlb-8vkuYAnm0Pw.png" /></figure><p>Duration, nr.employed, euribor3m, job, and month are the most impactful features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zqTHIruhuohGcdr3GaEDg.png" /></figure><p>SHAP differences:</p><p>While I dropped month and cons.conf.idx since they are not shown as important in either Pearson Correlation or Select K best. I can see that they are being impactful according to AUTO ML.</p><h3><strong>Conclusion</strong></h3><p>While in this example Auto ml performed better to obtain reduced <strong>False negatives error</strong>, this generally need not be the case. However, it is important to note that Auto ML is not a substitute for a thorough understanding of machine learning principles and techniques. Rather it can simplify the process for us, Like suggesting which model can we choose or what features are the most important ones.</p><p><strong>Code:</strong></p><ul><li><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Medium-Article/blob/main/Final_project_LightBGM.ipynb">Medium-Article/Final_project_LightBGM.ipynb at main · SriVenkataSatyaAkhilMalladi/Medium-Article</a></li><li><a href="https://github.com/SriVenkataSatyaAkhilMalladi/Medium-Article/blob/main/Final_project_AutoML.ipynb">Medium-Article/Final_project_AutoML.ipynb at main · SriVenkataSatyaAkhilMalladi/Medium-Article</a></li></ul><h3><strong>References:</strong></h3><ul><li><a href="https://github.com/aiskunks/Skunks_Skool/blob/main/INFO_6105/6105/6105_H2O_automl_lending_club.ipynb">Skunks_Skool/6105_H2O_automl_lending_club.ipynb at main · aiskunks/Skunks_Skool</a></li><li><a href="https://towardsdatascience.com/explain-any-models-with-the-shap-values-use-the-kernelexplainer-79de9464897a">Explain Any Models with the SHAP Values — Use the KernelExplainer</a></li><li><a href="https://medium.com/dataman-in-ai/explain-your-model-with-the-shap-values-bc36aac4de3d">Explain Your Model with the SHAP Values</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5445b154cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>