<?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 Anand Gupta on Medium]]></title>
        <description><![CDATA[Stories by Anand Gupta on Medium]]></description>
        <link>https://medium.com/@anand.gupta1202?source=rss-5dff47fb814a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YpNXj7rDaYwMtYiSsxg_nQ.jpeg</url>
            <title>Stories by Anand Gupta on Medium</title>
            <link>https://medium.com/@anand.gupta1202?source=rss-5dff47fb814a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:41:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anand.gupta1202/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[When AI Reliability Is a Clinical Requirement]]></title>
            <link>https://medium.com/tech-wysa/when-ai-reliability-is-a-clinical-requirement-7c4a965faff7?source=rss-5dff47fb814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c4a965faff7</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mental-health-awareness]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[self-help]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Anand Gupta]]></dc:creator>
            <pubDate>Tue, 12 May 2026 09:28:10 GMT</pubDate>
            <atom:updated>2026-05-12T15:53:52.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Wysa’s Stateful AI Gateway: Architecting Zero-Downtime Reliability for Mental Health</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjJkbjokZrpZmgQyrPd8VQ.png" /></figure><h3>What’s at stake?</h3><p>Wysa is an AI-guided self-help tool. Our users come to us during some of the hardest moments of their lives, dealing with anxiety, depression, grief, panic, and crisis. Wysa is not intended as a crisis support service, but when someone opens a conversation about a panic attack at 2 AM or is in the middle of a conversation about stress at work, the AI on the other end must recognise the gravity of the situation and respond immediately and accurately.</p><p>This is the context that shapes every infrastructure decision we make. A failed conversation request in a self-help conversation means someone in distress is staring at a loading spinner, or worse, an error message. The tolerance for failure in this domain is, for all practical purposes, zero.</p><p>Wysa processes over 3M AI invocations, and out of them, 700K AI requests per month need routing across multiple large language model providers and geographic regions. Each of these requests might involve a user mid-conversation about self-harm, a coaching session on managing workplace stress, or a guided sleep exercise. The content varies, but the requirement is to serve every request quickly.</p><p>That requirement, at that scale, is why we built a centralized stateful AI gateway. Not because we wanted architectural elegance (though that was a welcome result), but because we couldn’t risk the consequences of not having one. This paper describes what we built and what we learned in the process.</p><h3>The multi-provider problem</h3><p>Wysa relies on multiple LLM providers, each deployed across two to three geographic regions. That adds up to 15+ distinct routing targets for any given AI request. Each provider has a different API, different rate-limiting behavior, different failure modes, and a different latency profile. None of this is under our control.</p><p>Most companies scaling AI products end up with multiple providers, whether by choice (cost optimization, capability differences across models) or by necessity (no single provider offers the reliability guarantees a production system needs).</p><p>Mental wellbeing makes this harder in ways most teams don’t anticipate.</p><p>One such challenge is that each LLM provider applies content moderation and safety guardrails to their APIs. The moderation is designed to prevent harmful content generation across general-purpose use cases: consumer chatbots, writing assistants, coding tools, and search.</p><p>But in the mental wellbeing domain, user conversations routinely touch the exact topics those guardrails are designed to flag: self-harm, suicidal ideation, substance abuse, trauma, and emotional crisis. A prompt that is entirely appropriate in a clinical context can, and does, trigger provider-side moderation filters.</p><p>At the single-provider level, the result is that clinically valid prompts get rejected. At the multi-provider level, the problem is worse. If Provider A handles a self-help prompt correctly and then goes down, the obvious move is to fail over to Provider B. Except Provider B might block that same prompt. The fallback path just failed for a reason that has nothing to do with the general availability of the LLM, but more on this challenge later.</p><p>Building a multi-provider AI infrastructure in mental wellbeing is not the same as building it for general-purpose applications. The failure modes are different, and some of them are invisible if you are only thinking about uptime.</p><h3>Design principles</h3><figure><img alt="Wysa’s AI Gateway" src="https://cdn-images-1.medium.com/max/1024/1*73bFE7BUXy_qz8QibO29AQ.png" /></figure><p>The Wysa Stateful AI Gateway sits between all of Wysa’s products and the LLM providers they depend on. Every AI request flows through it. Here are the principles that shaped its design.</p><h3>Proactive problem detection</h3><p>Standard circuit breakers are reactive. They find out a provider is down because a user’s request fails, then they open the circuit to stop further requests. The user who triggered the discovery absorbs the impact.</p><p>In mental wellbeing care, that model doesn’t work. A broken session for a person in crisis is a failure to provide support, not a data point in a retry log.</p><p>So the gateway runs a health monitoring system that background-tests every provider and region combination. Every N seconds, the system sends lightweight test prompts and measures success rates, latency, and error frequency.</p><p>Instead of a binary healthy/unhealthy status, the system tracks a gradient: healthy, degraded, unhealthy, down, and recovering. A provider can be technically online but slow enough that routing traffic to it would hurt the user experience. A model coming back from an outage gets tested before it handles live traffic again.</p><p>The routing layer always has fresh health data. It never needs to send a real user’s request into the unknown to find out whether a provider is working, which also helps us with our compliance posture.</p><h3>Fall back at every level</h3><p>When a request comes in, the gateway builds a prioritized list of targets. The preferred model in the preferred region comes first. If that target is degraded or down (as determined by the health monitor, not by a failed request), the system moves to the same LLM model in another region. Then, a comparable LLM model from a different provider is targeted. Then to another provider entirely.</p><p>With multiple providers and multiple regions each, the fallback chain for a single request can be two to six targets deep before the system runs out of options. In practice, a request almost never reaches the third or fourth fallback. But the depth is there because the cost of exhausting the chain and returning an error is, in our domain, unacceptable.</p><p>All of this routing happens in milliseconds. The user sees a response. They do not see the decision tree that produced it.</p><figure><img alt="Wysa’s health state machine that detects the health status for each LLM provider and model" src="https://cdn-images-1.medium.com/max/1024/1*eP_P6lNVAXHkFyeCBsNKAA.png" /></figure><h3>Run guardrails once, call models in parallel</h3><p>Of all the design choices, this one had the most measurable impact.</p><p>Wysa’s AI architecture is layered. A single content generation task often requires calling multiple models: one for classification, one for generation, one for safety checks, and so on. Before the gateway existed, each of these calls was made independently by the service that needed it. Each call ran input guardrails, made an API request, and ran output guardrails. The safety checks were thorough, but redundant. The same input was being validated three or four times.</p><p>The gateway changed this. Because all requests now flow through a single system, we were able to restructure the execution path. Input guardrails run once, at the point of entry. Model calls that can happen in parallel do happen in parallel. Output guardrails run once, on the aggregated result. The safety coverage is identical. The redundant work is gone.</p><p>That restructuring is the main reason the gateway reduced end-to-end latency by approximately one second, despite being an additional infrastructure layer. We did not just add a routing system but used this centralization as an opportunity to rethink how execution worked.</p><h3>Segregating monitoring, routing, and execution</h3><p>The health monitor does not know how routing decisions are made. The routing logic does not execute requests. The execution layer does not make health assessments. Each component has one job and can be updated, scaled, or debugged independently. This decision of compartmentalising has paid off in practice. When we need to adjust health thresholds or add a new provider, the change is isolated to one component.</p><h3>The moderation paradox in mental health AI</h3><p>We want to spend time on a challenge that doesn’t get enough attention, and one we’ve had to work through directly.</p><p>LLM providers invest significantly in content moderation. Their systems are designed to prevent the generation of harmful content: graphic violence, hate speech, instructions for self-harm, and sexual content involving minors. These protections are important and exist for good reason. But the default moderation posture is calibrated for general-purpose use cases. A customer support chatbot, a coding assistant, a creative writing tool. In those contexts, a prompt mentioning suicide or self-harm is almost certainly something the model should refuse to engage with.</p><p>In mental wellbeing, the opposite is true. A user telling Wysa that they have been thinking about hurting themselves is not generating harmful content. They are reaching out for help. The appropriate response can not be a refusal or a content filter. It should be a clinically informed, empathetic reply that takes their distress seriously and connects them with the right resources, as needed.</p><p>During our initial integration with multiple providers, we discovered that clinically appropriate prompts were being flagged, filtered, or outright rejected by provider-side moderation. Anything touching suicidal ideation, self-harm, substance abuse, or severe emotional distress was hitting guardrails designed for very different contexts.</p><p>At the single-provider level, this was a solvable problem: work with the provider’s trust and safety team, demonstrate the clinical context, and negotiate a moderation configuration that preserves the safety intent while allowing mental health support content through.</p><p>At the multi-provider level, it became much harder. Each provider has different moderation sensitivities, different content taxonomies, and different thresholds for what gets flagged. A prompt that Provider A handles correctly might be blocked by Provider B. The fallback routing we built for reliability can be undermined by moderation inconsistency. Your failover breaks if the backup provider rejects the prompt.</p><p>Resolving this required engaging directly with the safety and trust teams at each of our providers. In each case, we had to demonstrate our clinical use case, explain why certain content categories needed different treatment in a mental health support context, and work through the configuration options available. These were not quick conversations. They required relationship-building, documentation of our clinical protocols, and in some cases, multiple rounds of moderation tuning before things worked correctly.</p><p>Additionally, providers update their moderation policies. New model versions sometimes ship with different safety behaviors. Each update requires us to validate that our self-help support content is still flowing correctly across all providers.</p><p>If you are building AI products in healthcare, crisis intervention, elder care, or any other sensitive domain, expect this friction. The default moderation posture of major LLM providers will get in your way. It is a cost you will not find in any pricing page or API documentation. If you are using multiple providers, you pay it multiple times. Budget accordingly, both in engineering time and in relationship-building with provider teams.</p><h3><strong>What 1.5 million requests taught us</strong></h3><p>The Wysa Stateful AI Gateway has been running in production since January 2026. In the first three months, it routed over 1.5 million LLM requests across all providers and regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFIr7_GHW9gDfCaKpwN4eA.png" /></figure><h3>Reliability at scale</h3><p>Across 1.5 million requests, the gateway had zero attributable downtime. Every request that entered the system received a response.</p><p>We want to be transparent about what we learnt from monitoring this system since Jan 26. The health monitor has been running continuously since launch: tens of thousands of health checks, latency trend data, jitter measurements, and a record of the health state of every provider-region combination over time. That data accumulates value. It improves routing decisions, surfaces latency patterns we would not otherwise see, and gives us reason to believe the system will respond correctly when an outage does occur.</p><h3>Performance: the unexpected gain</h3><p>Another surprising result from the first two months was the latency improvement. Adding an infrastructure layer between our services and LLM providers made responses approximately one second faster at p95.</p><p>In most cases, more infrastructure means more overhead. Tell someone you added a routing and monitoring layer on top of their API calls, and they’ll assume you made things slower.</p><p>The gain came from two sources. First, guardrail deduplication: input and output safety checks that were previously running on every individual model call now run once. Second, parallel execution: model calls that were being made sequentially (because each service managed its own calls independently) are now fired simultaneously, where the dependency graph allows it.</p><p>Neither of these optimisations was possible in the pre-gateway architecture, where each service owned its own provider interactions. Centralizing the request path did not just add resilience but opened up optimizations we could not have made otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7gwK20ZU-PhxeQQmqw3Cg.png" /></figure><h3>Operational clarity</h3><p>Before the gateway, every service that needed an LLM call managed API keys separately, maintained separate provider configurations, and handled errors independently. Debugging a failed request meant figuring out which service made the call, which provider it went to, what the error was, and whether the same thing was happening elsewhere.</p><p>Now there is one entry point, one set of logs, one place to look. API keys are managed centrally. Provider configurations are maintained in one location. When something looks off, the debugging path is straightforward. For our operations team, this has been the most immediately valuable change.</p><p>Centralization also made instrumentation traceable. We track request volumes, latencies, error rates, and per-provider health state across all regions in Grafana dashboards. A Slack bot wired into the same telemetry pipeline pushes automated alerts the moment a provider degrades, an outage begins, or latency jitter crosses our thresholds. The on-call engineer typically learns about a provider issue before the provider’s own status page reflects it.</p><h3>Future Directions</h3><p>Currently, our gateway focuses on a primary objective: verifying model availability and ensuring reliable routing. Looking ahead, we see significant opportunities for further optimization, such as implementing cost-aware routing to automatically select the most economical provider among those currently healthy.</p><p>Our goal in sharing these insights is to support the broader community of developers working in sensitive fields. Any organization developing therapeutic AI, tools for crisis intervention, or systems for clinical decision support will inevitably encounter the moderation hurdles we have detailed. By documenting our journey, we hope to enable others to bypass unnecessary trial and error and benefit from the lessons we have learned.</p><blockquote><strong><em>Disclaimer</em></strong><em>: Wysa is not designed to assist with crises such as abuse, severe mental health conditions that may cause feelings of suicide, harm to self, and any other medical emergencies. Wysa cannot and will not offer medical or clinical advice. It can only suggest that users seek advanced and professional medical help. Please reach out to your country-specific suicide hotline in case of an emergency.</em></blockquote><blockquote><em>You must be at least 18 years of age to use Wysa. If you are between 13 and 18 years of age, please read through the Terms of Service and Privacy Policy along with your parents or legal guardian to understand eligibility before use. Wysa is not designed to be used by children under 13.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c4a965faff7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-wysa/when-ai-reliability-is-a-clinical-requirement-7c4a965faff7">When AI Reliability Is a Clinical Requirement</a> was originally published in <a href="https://medium.com/tech-wysa">Tech @ Wysa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Talk NLP: Your Guide to the Magic of Natural Language Processing!]]></title>
            <link>https://medium.com/@anand.gupta1202/guide-to-natural-language-processing-980e3162cf55?source=rss-5dff47fb814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/980e3162cf55</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[understanding]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Anand Gupta]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 18:33:56 GMT</pubDate>
            <atom:updated>2023-08-27T18:33:56.947Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>If the thought of computers talking like humans, understanding emotions from text, or instant language translation intrigues you, this is your read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WXA5A3vwTUAluhCF" /><figcaption>Photo by <a href="https://unsplash.com/@katietreadway?utm_source=medium&amp;utm_medium=referral">Katie Treadway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>NLP? What’s the Buzz About?</h3><p>Alright, let’s demystify things. Natural Language Processing, aka NLP, is like giving computers a crash course in human language. It’s the tech that lets computers understand what we’re saying, make sense of it, and even respond like your chatty friend. Think Siri, Alexa, or Google Assistant — that’s NLP in action!</p><h3>Should You Care?</h3><p>If you’re into:</p><ul><li>Tech Magic: Watching how computers talk our language.</li><li>Smart Writing: Making your devices do the typing for you.</li><li>Language Sleuthing: Finding info like a pro in heaps of text.</li><li>Global Chats: Talking to anyone, anywhere, in any language.</li><li>Feeling the Feels: Knowing if folks are cheering or jeering online.</li></ul><p>Then you should know about the basics of NLP and its real world use cases. So, let’s start with the basics for this blog.</p><h3>NLP Basics</h3><p>Enough with the hype — let’s get into the nitty-gritty. Here are some building blocks of NLP:</p><h4>1. Tokenization</h4><p>Imagine chopping a sentence into bite-sized pieces. That’s tokenization! We’re breaking down text into chunks — words, phrases, or even individual letters — so we can work our magic on them.</p><h4>2. Part-of-Speech Tagging</h4><p>Ever play “noun, verb, adjective” with words? Well, that’s part-of-speech tagging for you. Computers give words labels like “verb” or “noun” to understand their role in sentences.</p><h4>3. Named Entity Recognition (NER)</h4><p>Let’s spot the stars! NER helps us identify names of people, places, dates, and more in text. It’s like playing detective with words.</p><h4>4. Sentiment Analysis</h4><p>Are words happy, sad, or just meh? Sentiment analysis checks the emotional vibes of text. It’s like teaching machines to read between the lines.</p><h4>5. Word Embeddings</h4><p>Ever wonder how machines understand synonyms? That’s word embeddings — they’re like secret codes that let machines grasp the context and meaning behind words.</p><p><strong>Note from the Author:</strong></p><p>I hope you enjoyed this quick journey into the world of Natural Language Processing (NLP). My aim with this blog was to provide a beginner-friendly glimpse into the exciting possibilities that NLP brings to the table.</p><p>While we’ve touched on the basics here, more articles on each aspect of NLP are in the pipeline. Until next time, happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=980e3162cf55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection on Indian Roads using TensorFlow]]></title>
            <link>https://medium.com/@anand.gupta1202/object-detection-on-indian-roads-using-tensorflow-1cb29a3f8846?source=rss-5dff47fb814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb29a3f8846</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Anand Gupta]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 19:43:29 GMT</pubDate>
            <atom:updated>2019-10-20T11:25:28.026Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about how I used Google’s Object Detection Model on Indian roads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GRQ_TWk7WluAKG70" /><figcaption>Photo by <a href="https://unsplash.com/@atharva_tulsi?utm_source=medium&amp;utm_medium=referral">Atharva Tulsi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Origin:</h3><p>First of all, let’s talk about the dataset. The dataset containing all the relevant data can be found here. The dataset consists of images obtained from a front-facing camera attached to a car. The car was driven around Hyderabad, Bangalore cities and their outskirts. The images are mostly of 1080p resolution, but there are also some images with 720p and other resolutions.</p><p>To download the data you click on <strong>Dataset -&gt; Download</strong>. Before the data starts to download you have to sign in with your account.</p><p>Once, the download is complete there will be 2 folders available :</p><ol><li>Detection Folder</li><li>Segmentation Folder</li></ol><p>Since I am working on detecting objects, I worked on the Detection folder.</p><h3>Inside the folder:</h3><p>Inside the detection folder, there are 3 main things:</p><ol><li>JpegImages Folder — This folder contains all the pictures that are extracted from the videos recorded while driving around some Indian cities.</li></ol><p>2. Annotation Folder — This folder contains all the annot files for each training image in a “.xml”. The annot files are in the Pascal VOC format.</p><p>3. There are also 3 “.txt” files named — train, test, val. These files contain the relative path to each image in the folder which states whether the files will be used for train, test or val which is validation.</p><blockquote>Note: I have tried to implement different executions of other models like Yolo, Yolo-v3 but since they did not work correctly, I am choosing to write only about the one that did.</blockquote><h3>Choosing what to execute:</h3><p>I was reading articles before working on this project, on the Object Detection API by Google — how it is a single stop solution to implement all the major models of computer vision and decided to give it a go.</p><p>Next most important thing was to choose what model I wanted to execute to detect objects from the images. <br>The Object Detection API has the capability to execute many different types of models, like ssd_mobilenet_v1, faster_rcnn_resnet50 to name a few.</p><p>The complete list of models and the weights that they are trained on can be found in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md">Tensorflow detection model zoo</a>.</p><p>Each model named here has 2 columns listed beside it. One is for “<em>Speed</em>” — how quickly can a model predict and another is “<em>mAP</em>” — which loosely translates to how accurate the model is usually (based on test conditions).<br><em>Point to note</em> here is that there is usually a tradeoff between speed and accuracy in these models</p><p>So after reviewing all the models, I decided to go with ssd_inception_v2_coco as it provides a good trade-off between speed and accuracy.</p><h3>Implementing the model</h3><p>Well, to be honest, the best step by step guide on how to implement the model is given <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html">here</a>. The tutorial has detailed writeup on how to go about executing the model and all the best practice ways to do it like setting up a workspace.</p><p>But here are some of <em>my</em> pointers/learnings that I followed while working on this problem.</p><ul><li><strong>Don’t mess around with your original anaconda environment</strong> if you are not confident.<br>I use anaconda for my projects locally and I have a bad history with goofing up the original installation of anaconda which resulted in multiple errors while using the TensorFlow with GPU. This in turn can lead to multiple resets and uninstall of PATH variables, GPU drivers, etc<br>The best solution to this problem would be to make a new Conda environment for this project. I am linking an excellent blog/tutorial on how to start with this <a href="https://towardsdatascience.com/tensorflow-gpu-installation-made-easy-use-conda-instead-of-pip-52e5249374bc">here</a>.</li><li><strong>There is a big flaw that I discovered much later </strong>while working with this dataset.<br>As I have already discussed that the dataset consists of JPEGImages and XML files. The images and the xml files (should ideally) have a 1-to-1 relationship i.e. for every “.jpg” training image there should be a “.xml” file.<br>Unfortunately such is not the scenario for the dataset provided here.</li><li><strong>Processing and Separation of files</strong> are important due to the above-mentioned reason.<br>So here is what I did. Since the images provided were of 3 types:<br>1. Train — for training <br>2. Test — for testing<br>3. Val — for validation<br>So I wrote a script to read the file name of every training image and check if the corresponding xml file exists. If yes, then copy both the image and xml file to another folder called “training”.<br>Repeat the process for test and val, only that the test images don’t have any corresponding xml files obviously.</li><li>During the part where you need to install Protobuf, be careful <strong>not to install the version 3.5 or more</strong>. This will save you a lot of time by utilising the multi-file selection wildcard (i.e *.proto)</li><li>While converting the .xml to .csv and from .csv to .record I copy-pasted the scripts and executed them using Jupyter Notebooks. I was easy to edit and provide easy debug on the code lines. Also, I could change the way the script was talking inputs based on my new folder structure.</li><li>While executing the custom training of your model be sure to lower the training batch number based on your machine’s capabilities. Otherwise it may lead to errors and training will stop.</li></ul><p>After following the <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html">tutorial </a>to implement a ssd_inception_v2_coco model I had to test it on the images of Indian traffic/roads.</p><p>Here are some of the output images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqI4BKZu6BX8uJxT0kl8EA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3k-_AQqSt6yytNDlMvlUQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wajVGUL3JKcyh4d-XuvcrQ.jpeg" /></figure><p>As we can see that the model does a pretty good job of detecting relevant objects on the input images with a moderate confidence rate.</p><h3>End Notes:</h3><p>While I did want to train on custom data (I actually did it halfway before running into a bunch of errors and dependency issues) I feel the pre-trained labels works fairly for images of Indian roads and traffic.</p><p>While work on autonomous cars have miles to go (no pun intended) before being able to tackle the chaotic and unstructured nature of Indian roads, working on object detection models are definitely the way forward.</p><p>Also, please comment on this article if you have executed yolov3 in keras or darknet in a windows machine before.</p><blockquote>Hope you liked this article and it was informative.</blockquote><blockquote>I would like to request you to please let me know in case you spot any errors.</blockquote><blockquote>You can also mail me at anand.gupta1202@gmail.com for any queries.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb29a3f8846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kaggle’s Credit Card Fraud Dataset]]></title>
            <link>https://medium.com/@anand.gupta1202/kaggles-credit-card-fraud-dataset-82d48b9d7cb1?source=rss-5dff47fb814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82d48b9d7cb1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Anand Gupta]]></dc:creator>
            <pubDate>Mon, 19 Aug 2019 15:15:07 GMT</pubDate>
            <atom:updated>2019-08-19T15:15:07.186Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describes how I used different machine learning models to try to predict credit card fraud and see which works best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B6UrjxwnwH5w-ZOB" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why do this?</h3><p>Well, I am studying data science at <a href="https://www.appliedaicourse.com/">AAIC</a> and as a case study, I am required to analyze and write a blog about a problem where I applied Machine Learning models to help solve the problem.</p><h3>Getting the data</h3><p>The data for credit card fraud case study can be found <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">here</a>. It is a Kaggle link from where you can download the data and work on it.</p><h3>Initial Findings (EDA)</h3><p>After importing the necessary packages and reading the data into a pandas dataframe, we start analyzing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*MXBi4l954nLtjPAgQnun5g.png" /><figcaption>credit card data info</figcaption></figure><p>With the <strong><em>info()</em></strong> method we can see :</p><ul><li>all the columns</li><li>all data types</li><li>whether any columns contain null or not as its values</li></ul><p>We can also see by the numbers written beside the names that there are <strong><em>no missing data in any of the columns.</em></strong></p><p>Next up we analyse the “time” column in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*7OizrmqErqAGxy-_nuDWXg.png" /></figure><p>We can see that the data distribution for “time” is not <a href="https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">uniform</a>.</p><p>Next up is the “Class” column in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*2kfQ3Jd54rXu90bt3qlvaQ.png" /></figure><p>Here we can see that the distribution for “time” data is very much skewed, with the almost non-existent amount of data for Class 1.</p><p>Things to Note:</p><ul><li><strong>Class 0</strong> = Authentic Transaction</li><li><strong>Class 1</strong> = Fraudulent Transaction</li></ul><p>Well, let’s see if we can get any insights from the data that belongs to Class 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*xJz5YBLgiH9EM2nMQRZEXw.png" /></figure><p>Here, in this graph, we can see that most of the fraudulent data are below amount 500.</p><p>Note:</p><p>We don’t have any information about what the unit of the amount is, i.e. whether it is USD, INR or even if it is the actual amount figure (i.e. scaled or not).</p><p>Next up let us see what the distribution of all the columns is like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KENmFBr0xq2kb3s6sYsabw.png" /></figure><p>From the histogram above we can see that most of the data columns are scaled (apart from amount and time). So the next step is to scale the data of these columns.</p><p>We do the scaling with the help of <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html">Robust Scaler</a> as it uses interquartile range so that it is robust to outliers.</p><h3>Split to Train Test</h3><p>Now to split the data to train and test, we use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html"><strong>StratifiedShuffleSplit</strong></a>.</p><p>We chose this because,</p><blockquote>This cross-validation object is a merge of StratifiedKFold and ShuffleSplit, which returns stratified randomized folds. The folds are made by preserving the percentage of samples for each class.</blockquote><p>As this is a imbalanced dataset, preserving the class percentage samples is needed. Otherwise it may so happen that the sampled fold doesn&#39;t have any data of the minor class.</p><h3>Classifier Models</h3><p>In the next few sections of this article, we will go through some classification models and see how they fare in their performance metric(s).</p><h3>Model 0 — Dummy Classifier</h3><p>This dummy model generates predictions by respecting the training set’s class distribution. But in our case, as we have seen that the class is very skewed for Class 0, the model will almost always predict ‘0’ and it is most likely to be right.</p><p>So, <strong>Accuracy as a classification metric is not the ideal scenario here</strong>. <br><a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">Here</a> is an amazing article to shed light on this matter.</p><p>So we take the AUC (Area Under the Curve) value instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*pJvUXC03uhzvbFkEnNKlmA.png" /></figure><p>Here, we can see that the dummy classifier model has an AUC of 0.4991.</p><p>So we get a base value of metric to improve, in the next models.</p><h3>Model 1 — Logistic Regression</h3><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">Logistic Regression</a> with parameter tuning of ‘C’ and scoring as ‘f1_micro’ to get proper f1 values for imbalanced dataset classes</p><pre>clf = LogisticRegression(random_state=10)<br>param_grid={‘C’: [0.01, 0.1, 1, 10, 100]}<br>scoring = ‘f1_micro’<br>GS = GridSearchCV(clf, param_grid, scoring = scoring, cv = sss.split(x_train, y_train), n_jobs = -1)<br>LR_GS = GS.fit(x_train, y_train)</pre><p>In the code snippet above we can see the following things:</p><ul><li>Using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV </a>to do parameter tuning.</li><li>Parameter tuning of ‘C’ of LogisticRegression()</li><li>Using the metric of ‘f1_micro’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*RrwG9se6bIcXaxNZQMlZqg.png" /></figure><p>This graph shows the ROC curve of model 1 with an AUC of 0.7805.</p><p>This is an better than the AUC value of the Dummy classifier.</p><h3>Model 2 — Logistic Regression</h3><p>Logistic Regression with parameter tuning of ‘C’ and ‘class_weight’.</p><p>The ‘class_weight’ parameter helps in a imbalanced dataset by penalising the wrong classification of smaller classes more. Also scoring metric is ‘roc_auc’.</p><pre>clf = LogisticRegression(random_state=10, penalty=’l1&#39;)<br>param_grid = {‘C’: [0.01, 0.1, 1, 10, 100],<br>              ‘class_weight’:[{0:.1,1:.9}, {0:.0017,1:0.9983},<br>                              {0:.3,1:.7}]}<br>scoring = ‘roc_auc’<br>RS = RandomizedSearchCV(clf, param_grid, scoring=scoring,<br>                        cv=sss.split(x_train, y_train), n_jobs=-1)<br>LR_RS = RS.fit(x_train, y_train)</pre><p>In the above code snippet, the “class weight” parameter is tuned using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html">RandomizedSearchCV</a> and the way it takes the value for class_weight is Weights associated with classes in the form {class_label: weight}.for example) is:</p><pre>{0:.1,1:.9}</pre><p>where 0:.1 represents that for Class 0 to give weight 0.1 and for Class 1 to give weight 0.9. This is mainly done so that the model is penalized more for wrongly classifying class 1 as the quantity of data in that class is less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*pAAMQH8hPuKucy2SZONzgQ.png" /></figure><p>Here, we can see that by tuning the class_weights parameter the AUC value for Model 2 has improved a lot compared to other models before this.</p><h3>Model 3— XGBClassifier</h3><p>Next, we see how the classification task fares when used with <a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn">xgboost classifier</a>.</p><pre>params = { ‘min_child_weight’: [0.5, 1, 2],<br>           ‘gamma’: [1, 1.5, 2, 5],<br>           ‘subsample’: [0.5, 0.8, 1.0],<br>           ‘max_depth’: [3, 5, 7],<br>           ‘scale_pos_weight’:[10, 100, 300] }<br>xgb = XGBClassifier(learning_rate=0.02, n_estimators=500,<br>                    objective=’binary:logistic’,<br>                    verbosity=2, nthread=-1)<br>rs_xgb = RandomizedSearchCV(xgb, param_distributions=params,<br>                            scoring=’roc_auc’, cv=3, verbose=2,<br>                            n_jobs=-1, random_state=10)<br>rs_xgb.fit(x_train, y_train)</pre><p>Like previous models, we first tune the parameters and hyperparameters, namely :</p><ul><li>min_child_weight</li><li>gamma</li><li>subsample</li><li>max_depth</li><li>scale_pos_weight</li></ul><p>All the details of what each parameter and hyperparameter does can be found <a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*urtBG1WXcrQDk9txYB5m7A.png" /></figure><p>As we can see that the XGBoost Classifier AUC is 0.9275 which is almost the same as the previous model.</p><h3>Data Sampling</h3><p>Since we are working with such an imbalanced dataset, it would be better to upsample the data. So we used this lovely package called <a href="https://imbalanced-learn.readthedocs.io/en/stable/install.html">imbalanced-learn</a>.</p><pre>sm = SMOTEENN(random_state=10)<br>x_train_res, y_train_res = sm.fit_sample(x_train, y_train)</pre><p>The SMOTEENN is a technique which reduces the noisy sample generation problem by SMOTE to give us better sample data. More about it can be found <a href="https://imbalanced-learn.readthedocs.io/en/stable/combine.html#combine">here.</a></p><h3>Model 4— Keras Model</h3><p>Keras model to fit and validate train and test set respectively.</p><pre>model = Sequential()<br>model.add(Dense(32, input_dim=30, activation=’relu’)) model.add(Dense(16, activation=’relu’))<br>model.add(Dense(8, activation=’relu’))<br>model.add(Dense(1, activation=’sigmoid’))<br>model.compile(loss=’binary_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])<br>model.fit(x_train_res, y_train_res, epochs=20, batch_size=5000)</pre><p>In this code snippet above we are building a neural network with <a href="https://keras.io/">Keras</a>.</p><p>The neural network :</p><ul><li>has 3 hidden layers with 32, 16, 8 neurons in each layer respectively.</li><li>The input parameter/dimension is 30 which is the number of columns the dataset has</li><li>We are using relu as the activation function for all the layers except the last one, where the activation function is sigmoid for classification.</li><li>Also the other parameters given are loss = “binary_crossentropy”, optimizer = “adam” and metric as “accuracy”</li></ul><p>After fitting the model on the sampled training data we predict on the test data and plot the AUC for this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*UpjDVNs06OGzN0UvWWkRJg.png" /></figure><p>As we can see the AUC has increased to 0.9634 now.</p><p>So, there definitely is an improvement with up-sampled data and simple neural networks.</p><h3>Model 5— Logistic Regression (to detect the importance of sampled data)</h3><p>Next up let us see if the data sampling improves the original logistic regression model that we used.</p><pre>clf = LogisticRegression(random_state=10)<br>param_grid={‘C’: [0.01, 0.1, 1, 10, 100]}<br>scoring = ‘f1_micro’</pre><pre>GS = GridSearchCV(clf, param_grid, scoring=scoring, cv=3, n_jobs=-1) LR_GS_new = GS.fit(x_train_res, y_train_res) </pre><pre>y_pred = LR_GS_new.best_estimator_.predict(x_test)</pre><p>Here we are using the same Logistic Regression model as we used in the very beginning, but with up-sampled data (using imblearn, as discussed above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*bEPLj5HaFGui4yiFodKIwg.png" /></figure><p>As we have seen before, the AUC for the same model was 0.7805.</p><p>But, with the same model and with up-sampled data we can achieve an AUC of 0.9482, which underlines the importance of up-sampling.</p><h3>Conclusion</h3><p>After all the model enumeration we can conclude the performance as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Yb9bHW5hBJUs4pqmWHPUfw.png" /></figure><p>After going through the article we can say few things:</p><ul><li>As the data was imbalanced, it was important to address this issue before we trained any model on it. This was further proved right when we saw the difference in AUC value between Model 5 and 1.</li><li>EDA on the original dataset is always important for any problem, as was the case here too.</li><li>Also we can see that the Logistic Regression Model can also give decent results (AUC 0.9029) if we can tune the parameters a bit (like “class_weights” and “C”). Of course it won’t work every time as it depends on the data and the problem statement also.</li><li>The best performance (AUC value) among all the models was by the Keras neural network (Model 4)</li></ul><p>Hope you liked this article and it was informative.</p><p>As this is my first post, I would like to request you to please let me know in case you spot any error.</p><p>You can also mail me at anand.gupta1202@gmail.com for any queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d48b9d7cb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>