<?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 shubham badaya on Medium]]></title>
        <description><![CDATA[Stories by shubham badaya on Medium]]></description>
        <link>https://medium.com/@shubhambadaya17?source=rss-4229022f361c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*emsNqO2XewQ3HyZ8y45z1Q.jpeg</url>
            <title>Stories by shubham badaya on Medium</title>
            <link>https://medium.com/@shubhambadaya17?source=rss-4229022f361c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:33:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubhambadaya17/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[I Built an AI Analyst. Here’s What Nobody Tells You About Making One That’s Actually Trustworthy.]]></title>
            <link>https://medium.com/@shubhambadaya17/i-built-an-ai-analyst-heres-what-nobody-tells-you-about-making-one-that-s-actually-trustworthy-b78b8cf0db0b?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b78b8cf0db0b</guid>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 12:07:23 GMT</pubDate>
            <atom:updated>2026-09-10T03:25:44.901Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Lessons from building an agentic analytics copilot that turns plain-English questions into real answers and the failure modes that don’t show up in the demo.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ObFnRTPCEWdsTY4W" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Everyone’s seen the demo. You upload a CSV, type “what drives revenue?”, and a confident paragraph of insight appears. It looks like magic. Then you ship it to someone who actually makes decisions with the numbers, and you discover the gap between <em>impressive</em> and <em>trustworthy</em> is enormous.</p><p>I spent weeks closing that gap. Here’s what I learned — the architecture decisions that mattered, and the mistakes I’d warn anyone away from.</p><h3>1. The one rule that makes or breaks the whole thing: LLMs don’t do math</h3><p>This is the foundation everything else sits on. Large language models are probabilistic text generators. Asking one to compute an average is asking it to <em>predict what an average looks like</em> — and it’ll predict a very plausible, very wrong number.</p><p>So the core design principle: decouple reasoning from calculation. The LLM only ever does two things — <em>write code</em> and <em>write prose</em>. Every actual number comes from running real pandas in a sandbox on the real data. The model proposes; a deterministic engine disposes.</p><p>This single decision means your numbers are reproducible regardless of which model you use or how badly it hallucinates. It’s the difference between “the AI says revenue is $2.1M” and “here’s the code that computed $2.1M from your data, and here’s what it means.”</p><p>Takeaway: If your analyst tool lets the LLM emit numbers directly, you don’t have an analyst. You have a confident intern who never opens the spreadsheet.</p><h3>2. Running code is not the same as correct code (this one bites everyone)</h3><p>Here’s the failure that kept me up at night. The user asks for “average <em>plan value</em> by brand.” The model writes clean, valid pandas — that averages the <em>handset price</em> column instead. It runs perfectly. It returns a beautiful chart. And it’s completely wrong, with zero error to warn anyone.</p><p>Catching crashes is easy. Catching <em>silently answering the wrong question</em> is the actual hard problem, and most tools don’t even try.</p><p>The fix that worked: a correctness gate. After the code runs, a separate LLM pass looks at the question, the code, and the result and asks one thing — <em>does this actually answer what was asked?</em> Not “did it run.” If it spots a wrong column, wrong aggregation, or a missing filter, it regenerates the analysis once with a specific fix instruction.</p><p>When I tested it, it caught exactly the handset-vs-plan-value mix-up and flagged “wrong column or metric.” That’s the bug a human reviewer would catch — and now the machine does too.</p><p>Takeaway: Add a verification step that checks <em>relevance</em>, not just execution. The scariest bugs are the ones that don’t throw.</p><h3>3. Structured output is your backbone — and your most fragile point</h3><p>The entire pipeline runs on the model returning structured JSON that conforms to a strict schema (I used Pydantic). The code, the chart spec, the insights, the confidence score — all typed objects. This is what lets you wire agents together reliably.</p><p>It’s also where everything breaks. Constrained decoding on complex nested schemas drove one model family into <em>runaway repetition loops</em> — it would echo instructions into a string field until it hit the token ceiling and returned truncated, invalid JSON. The fix was counterintuitive: stop using native schema enforcement, embed the schema in the prompt as text, and validate after. Plus a whole layer of schema-rewriting (inlining references, flattening optionals) because the model’s parser rejected standard JSON Schema.</p><p>Takeaway: Budget real engineering time for structured output reliability. It’s not a one-liner — it’s a subsystem. And test it on your <em>most nested</em> schema, not your simplest.</p><h3>4. Don’t make the model answer a question you wouldn’t pay an analyst to answer blind</h3><p>Two more behaviors separated “demo” from “colleague”:</p><p>Ask before assuming. If someone asks “how do we improve ARPU?” but no revenue metric is defined anywhere in the data or business glossary, a good analyst doesn’t guess what ARPU means — they ask. So the system pauses and asks a clarifying question instead of inventing a definition. It feels slower. It’s the difference between a tool you trust and one you double-check.</p><p>Show your work before doing it. For deep questions, it lays out its plan and assumptions <em>first</em>. Decision-makers don’t want a black box; they want to see the reasoning and correct it early.</p><p>Takeaway: The most “intelligent” behavior is often <em>restraint</em> — asking, planning, and admitting uncertainty.</p><h3>5. Make it skeptical of its own answers</h3><p>LLMs are confidently wrong and wrongly confident. Two guardrails helped enormously:</p><ul><li>A self-critique pass. Before the answer reaches the user, a “skeptical senior analyst” persona reviews it against the evidence: every claim must be supported by the numbers, overreaching gets trimmed, caveats get surfaced (small sample, proxy metric, correlation ≠ causation), and the confidence score gets <em>grounded</em> in the actual data rather than the model’s vibe.</li><li>Tie claims to statistics. If the answer says a difference is “significant,” there’d better be a test with p &lt; 0.05 backing it. If the test says it’s <em>not</em> significant, the answer must say so rather than overstating the effect. Significance isn’t a word the model gets to use for free.</li></ul><p>Takeaway: Build in an adversary. The model that wrote the answer should not be the only model that gets a vote on whether it’s true.</p><h3>6. Feed it enough evidence to be right</h3><p>A subtle one. I was passing the model only the first 5 rows of each intermediate result as “context” for synthesis. For a multi-step investigation, that’s like asking someone to summarize a report after reading every fifth sentence. The insights came out shallow and occasionally just wrong about the overall shape of the data.</p><p>Bumping previews to a fuller slice (and always sending the <em>primary</em> result table in full) measurably improved depth. Tokens are cheap; thin context is expensive.</p><p>Takeaway: “Context window management” often gets framed as <em>trimming</em>. Just as often, the bug is you trimmed too much.</p><h3>7. Route by complexity — don’t pay for a brain you don’t need</h3><p>Not every question needs a five-agent reasoning DAG. “How many active users?” should be fast and cheap. “What drives churn and what should we do about it?” deserves the full multi-step investigation with a planner, statistical validation, and synthesis.</p><p>So a router classifies each question and sends it down one of a few paths — a fast single-shot model for simple lookups, a heavier reasoning model with an iterative investigation loop for open-ended ones, and a dedicated path for predictive/ML questions. Latency and cost track the actual difficulty.</p><p>One detail that mattered: the investigation loop needs a hard cap. An open-ended “explore this” agent will happily explore forever. A step ceiling (with graceful synthesis of whatever it found) bounds cost and latency without breaking simpler queries that finish in one step anyway.</p><p>Takeaway: Tiered routing isn’t premature optimization — it’s the difference between a tool people use and a tool people expense once.</p><h3>8. Even the charts lie if you let them</h3><p>A bonus from the visualization layer:</p><ul><li>Averages hide distributions. A bar chart of “average value by segment” looks authoritative and tells you almost nothing about spread or outliers. Box plots and histograms earn their keep.</li><li>Don’t crowd unrelated dimensions onto one axis. A chart that put handset brand, geography, and plan tier on the same axis invited meaningless comparisons (“Apple vs Metro vs ₹3999?”). Faceting into small multiples — one clean panel per dimension — fixed it.</li></ul><p>Takeaway: A chart is an argument. Make sure it’s making the right one.</p><h3>So, should you build an agentic analyst?</h3><p>Yes — but go in clear-eyed. The architecture that makes it <em>trustworthy</em> is mostly defensive: deterministic math, correctness gates, self-critique, statistical discipline, honest persistence. The fun generative part is maybe 20% of the work. The other 80% is making sure the confident paragraph is actually <em>true</em> — and being honest, in the product itself, about when it isn’t.</p><p>The demo takes a weekend. Trust takes the other eight weeks. That’s the part nobody tells you.</p><p><em>Built with a deterministic pandas sandbox, a multi-agent reasoning pipeline, and an unreasonable number of “wait, why is it confidently wrong” debugging sessions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b78b8cf0db0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs Demystified: A Guide for Business Leaders]]></title>
            <link>https://medium.com/@shubhambadaya17/llms-demystified-a-guide-for-business-leaders-de07df6b055c?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/de07df6b055c</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 17:04:34 GMT</pubDate>
            <atom:updated>2025-09-21T17:04:34.019Z</atom:updated>
            <content:encoded><![CDATA[<p>Generative AI is everywhere, and it’s hard to ignore. Recently, while trying to understand how it really works, I went down the path of exploring older approaches like Bag of Words, Word2Vec, and RNNs, before finally reaching <strong>Transformers</strong> — the foundation of today’s Large Language Models (LLMs).</p><p>At a high level, four key ideas explain how LLMs work:</p><ul><li><strong>Embeddings</strong></li><li><strong>Attention Mechanism</strong></li><li><strong>Transformer Architecture</strong></li><li><strong>Training</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6ka9N9RFOsvNEg7ICDbHg.png" /></figure><p>Let’s break these down with simple examples.</p><h3>1. Transformers (The Brain of the Model)</h3><p>Think of a transformer as the <strong>engine</strong> of the AI brain.<br> It decides how words in a sentence connect to each other.</p><p>Example: In <em>“the cat sat on the mat”</em>, it understands that <strong>the cat</strong> is sitting, not the mat.</p><p>👉 <strong>Analogy:</strong> Like a movie director, deciding which actor (word) should get the spotlight in a scene.</p><h3>2. Embeddings (The Memory System)</h3><p>Words, sentences, or even images are turned into numbers called <strong>embeddings</strong>. These numbers capture <strong>meaning</strong>, not just spelling.</p><p>Example: <em>“King”</em> and <em>“Queen”</em> have similar meanings, so their embeddings are close together in this number-world.</p><p><strong>Analogy:</strong> Like organizing a giant library — romance books are kept near each other, science books in another corner.</p><h3>3. Attention Mechanism (The Spotlight)</h3><p>Attention helps the model decide which words matter most in a sentence.</p><p>Example: If you ask, <em>“What did the cat sit on?”</em>, the model pays more attention to <strong>“mat”</strong> than to <strong>“cat”</strong>.</p><p><strong>Analogy:</strong> Like highlighting important lines in a textbook while studying.</p><h3>4. Training (How It Learns)</h3><p>LLMs don’t just “know things” — they learn through stages:</p><ol><li><strong>Pretraining</strong> — Reading massive amounts of text (books, websites, articles) to learn grammar, facts, and style.<br> Analogy: Like a student reading the whole internet to build general knowledge.</li><li><strong>Fine-tuning</strong> — Adjusting on smaller, curated datasets for specific tasks (e.g., coding, medical Q&amp;A, customer service).<br>Analogy: A doctor who studies medicine broadly, then specializes in cardiology.</li><li><strong>RLHF (Reinforcement Learning with Human Feedback)</strong> — Improving through human feedback: “This answer is good, this is bad.”<br> Analogy: A trainee getting better by practicing with a coach’s guidance.</li></ol><h3>✅ Putting It All Together</h3><ul><li><strong>Embeddings = how it stores meaning</strong></li><li><strong>Attention = how it focuses</strong></li><li><strong>Transformers = how it processes</strong></li><li><strong>Training = how it learns</strong></li></ul><p>Combined, these allow LLMs to predict the next word in a sentence very effectively — which translates into skills like answering questions, summarizing reports, writing emails, or even generating code.</p><p><strong>Not sure what to read next? I’ve picked another article for you:</strong></p><p><a href="https://medium.com/@shubhambadaya17/data-science-fundamentals-often-asked-in-interviews-292a2dfd8826">Data science fundamentals often asked in interviews</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de07df6b055c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Explain Random Forest to Non-Tech Audience]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@shubhambadaya17/how-to-explain-random-forest-to-a-non-tech-audience-442056487fe4?source=rss-4229022f361c------2"><img src="https://cdn-images-1.medium.com/max/989/1*wJPcvnEzvCP7dQE3p0vHtQ.png" width="989"></a></p><p class="medium-feed-snippet">PDP, Shap, LIME</p><p class="medium-feed-link"><a href="https://medium.com/@shubhambadaya17/how-to-explain-random-forest-to-a-non-tech-audience-442056487fe4?source=rss-4229022f361c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@shubhambadaya17/how-to-explain-random-forest-to-a-non-tech-audience-442056487fe4?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/442056487fe4</guid>
            <category><![CDATA[lime]]></category>
            <category><![CDATA[pdp]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[data-science-fundamentals]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 11:59:07 GMT</pubDate>
            <atom:updated>2024-09-02T04:14:13.895Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding Big Data File Formats: Their Types and Importance]]></title>
            <link>https://medium.com/@shubhambadaya17/understanding-big-data-file-formats-their-types-and-importance-eafacd91ac3b?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eafacd91ac3b</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 13:45:03 GMT</pubDate>
            <atom:updated>2024-07-03T13:57:30.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yumIM4MtQPDtxtuE" /><figcaption>Photo by <a href="https://unsplash.com/@alterego_swiss?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Introduction to File Formats in Big Data</blockquote><p>In the realm of big data, the choice of file format is crucial for efficient data storage, retrieval, and processing. With the sheer volume of data generated today, it’s not feasible to rely solely on traditional file formats like CSV, JSON, and XML. These formats, while familiar and widely used, have limitations in terms of performance and scalability when dealing with large datasets. This article delves into why different file formats are necessary in big data, exploring their classification and the specific needs they address.</p><h4>Why Different File Formats in Big Data?</h4><p>Traditional file formats like CSV, JSON, and XML are popular for their simplicity and ease of use. However, they fall short when it comes to handling big data for several reasons:</p><ol><li>Storage Efficiency: Traditional formats store data as text, which increases storage size. For example, storing the number ‘12345678’ as a string takes 16 bytes, whereas storing it as an integer takes just 4 bytes.</li><li>Processing Speed: Converting text data to its intended type (e.g., from string to integer) during processing incurs a time penalty.</li><li>I/O Operations: Reading and writing text files is slower, particularly with large datasets.</li><li>Parallel Processing: Formats like XML and JSON are not splittable, limiting the ability to process data in parallel.</li></ol><p>To overcome these limitations, specialized file formats are used in big data environments. These formats are designed to optimize storage, processing, and scalability.</p><h3>Classification of File Formats</h3><p>Broadly, file formats can be classified into two categories: row-based and column-based.</p><h4>Row-Based File Formats</h4><p>Row-based file formats store data row by row. Examples include <strong><em>CSV</em></strong> and <strong><em>Avro</em></strong>. These formats are easier to write but can be inefficient for reading selected columns and compressing data.</p><p>Example:</p><pre>[[1, john, 26, 20K], [2, sam, 23, 12K], [3, tom, 28, 30K]]</pre><h4><strong>Column-Based File Formats</strong></h4><p>Column-based file formats store data column by column. Examples include ORC and Parquet. These formats are efficient for reading selected columns and compressing data but can be harder to write.</p><p>Example:</p><pre>[[1, 2, 3], [john, sam, tom], [26, 23, 28], [20K, 12K, 30K]]</pre><blockquote>Specialized File Formats in Big Data</blockquote><h4>Avro</h4><ul><li>Type: Row-based</li><li>Storage:<strong> </strong>Data is stored in binary format, making it storage-efficient. The schema (metadata) is stored in binary and JSON formats.</li><li>Advantages:</li><li>Excellent for schema evolution, allowing easy addition, removal, or renaming of columns.</li><li>Suitable for ETL operations where reading entire rows is necessary.</li><li>Ideal for the landing zone of a data lake.</li></ul><h4>ORC (Optimized Row Columnar)</h4><ul><li>Type: Column-based</li><li>Storage: Highly optimized for reading and writing operations, supports advanced compression techniques.</li><li>Advantages:</li><li>Efficient for querying large datasets with complex queries.</li><li>Supports lightweight compression and indexing, speeding up data retrieval.</li></ul><h4>Parquet</h4><ul><li>Type:<strong> </strong>Column-based</li><li>Storage: Stores data in a columnar format with efficient compression and encoding schemes.</li><li>Advantages:</li><li>Excellent for read-heavy operations where only a subset of columns are needed.</li><li>Reduces I/O operations by reading only the required columns.</li></ul><h4>Conclusion</h4><p>The choice of file format in big data is not merely a matter of preference but a critical decision impacting storage efficiency, processing speed, and overall scalability. While traditional file formats like CSV, JSON, and XML have their place, they are often inadequate for big data needs. Specialized formats like Avro, ORC, and Parquet offer significant advantages in terms of storage efficiency, processing speed, and support for complex data operations. By understanding the strengths and weaknesses of each format, organizations can make informed decisions to optimize their big data workflows.</p><h4>Not sure what to read next? I’ve picked another article for you:</h4><ul><li><a href="https://medium.com/@shubhambadaya17/spark-memory-allocation-for-driver-and-executor-ad013574321a">Spark memory allocation for driver and executor — beginner-friendly</a></li><li><a href="https://medium.com/@shubhambadaya17/asked-python-interview-questions-for-data-science-24b1c6b6588c">Asked Python interview questions for data science/engineering.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eafacd91ac3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark memory allocation for driver and executor — beginner-friendly]]></title>
            <link>https://medium.com/@shubhambadaya17/spark-memory-allocation-for-driver-and-executor-ad013574321a?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad013574321a</guid>
            <category><![CDATA[spark-executor]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[out-of-memory]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 02:21:43 GMT</pubDate>
            <atom:updated>2024-06-11T06:53:04.498Z</atom:updated>
            <content:encoded><![CDATA[<p>I have often been asked to debug Spark applications, and sometimes it gets quite complex to explain why someone encounters out-of-memory errors, as it results from a variety of factors.</p><p>In this article, we will discuss Spark memory allocation for both the driver and executor, and how understanding these allocations can help in avoiding out-of-memory errors.</p><h3>Driver Memory Breakdown</h3><p>Assume, we submitted one spark application to the yarn cluster. the yarn resource manager will allocate a spark application master(AM) and start your driver in the AM,</p><p>The driver will start with the memory you just allocated. There are 2 components to the driver memory and the total memory requested for the driver is the sum of both.</p><p>1. <strong>spark.driver.memory</strong>: usually set by the user. Keep to minimum e.g. 1G to 4G.</p><p>2. <strong>spark.driver.memoryOverhead : </strong>default value is max(10% of spark.driver.memory or 384 MB) used by container process or any other non-JVM process.</p><p>3. YARN allocates the requested driver memory + the higher value between 10% of requested memory and 384 MB for container overhead.</p><p>So in total YARN resource manager will launch a container of size 4G + 0.4 GB = 4.4 GB.</p><p>Now we have 3 limits.</p><p>1. The spark driver JVM cannot use more than 4 G</p><p>2. Your non-JVM process cannot use more than 0.4G</p><p>3. The overall container cannot use more than 4.4 GB</p><blockquote><strong><em>If any of them exceeds, we will get an out-of-memory error for the driver.</em></strong></blockquote><h3>Executor Memory Breakdown</h3><p>Now the driver has started and it will request yarn RM for executors. Each executor memory will be the sum of the following 4 components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*Y111rhYveiWSJT5A2Aitgg.png" /></figure><p>Now in our case above for executor, again we have 3 limits</p><ol><li>8G for JVM processes</li><li>0.8G for non-JVM process</li><li>container physical limit of 8.8 G</li></ol><blockquote><strong><em>If any of them exceeds, we will get an out-of-memory error for the executor.</em></strong></blockquote><p>There are 2 more things which we need to consider.</p><ol><li><strong>What is the physical memory limit at the worker node?</strong></li></ol><p>This is usually set by the yarn admin and can be checked on the cluster config page or using the below properties. we can’t have any executor which has more than a physical limit</p><ul><li>yarn.scheduler.maximum-allocation-mb</li><li>yarn.nodemanager.resource.memory-mb</li></ul><p>2. <strong>What is the PySpark executor memory?</strong></p><p>We don’t need to worry about Pyspark memory if we write code in Scala or Java. However, if we are working in pyspark, then we need to worry about pyspark memory. Since Python is a non-jvm process, it will consume the overhead memory.</p><p><strong>In case of memory overhead error, increase the memory overhead limit or provide pyspark memory separately.</strong></p><p>In Summary,</p><p>A Spark container’s total memory is divided into two sections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*FwWVCo6Osb55noAPOJ-hMQ.png" /></figure><ol><li><strong>Heap Memory:</strong> This is the main memory for the JVM process running inside the container. It’s called driver memory if the container holds the Spark driver, and executor memory if it holds a Spark executor.</li><li><strong>Overhead Memory:</strong> This is separate memory managed by the operating system within the container. It’s used for various tasks, including network buffers for data shuffling and reading data from storage.</li></ol><p>Both parts are crucial for your Spark application to run smoothly. Insufficient overhead memory, often overlooked, can lead to Out-of-Memory (OOM) exceptions due to its role in network operations which is responsible for shuffling buffer, and reading data from external source like RDBMS.</p><p><strong>Not sure what to read next? I’ve picked another article for you:</strong></p><ul><li><a href="https://medium.com/@shubhambadaya13/understanding-normalized-vs-denormalized-schemas-in-data-warehousing-c686a7d509ae">Understanding Normalized vs. Denormalized Schemas in Data Warehousing</a></li><li><a href="https://medium.com/@shubhambadaya13/asked-python-interview-questions-for-data-science-24b1c6b6588c">Asked Python interview questions for data science/engineering.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad013574321a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Normalized vs. Denormalized Schemas in Data Warehousing]]></title>
            <link>https://medium.com/@shubhambadaya17/understanding-normalized-vs-denormalized-schemas-in-data-warehousing-c686a7d509ae?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c686a7d509ae</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-modelling]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 18:48:28 GMT</pubDate>
            <atom:updated>2024-06-01T18:48:28.891Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on an analytics project and using data from table X, have you ever wondered why data from table Y is not included in table X, and why only certain fields are kept in table X?</p><p>Or have you ever wondered how data flows into table X?</p><p>The flow of data into table X is a separate topic. In this article, we will take a high-level look at how data is stored.</p><p>You might have heard many terms about data storage, like facts, dimensions, partitioning, normalization, denormalization, third normal form, and more. This can be very confusing and create a barrier to learning.</p><p>I felt the same way while learning about data modeling. In a series of articles, I will do my best to explain these concepts in the simplest way possible.</p><p>In this article, we will discuss 2 concepts that we have to deal with while storing data i.e. <strong>normalized and denormalized schema.</strong></p><p>When designing a data warehouse, <strong>one of the critical decisions to make is whether to use a normalized or denormalized schema</strong>. Both approaches have their advantages and are suited to different scenarios. Here’s an in-depth look at normalized vs. denormalized schemas:</p><h3>Normalized Schema</h3><p><strong><em>Definition:</em></strong> Normalization is the process of organizing data to minimize redundancy means there should be no unnecessary or duplicate data in the table.</p><p>In a normalized schema, data is divided into multiple related tables, each containing a single type of concept.</p><p><strong>Example</strong>: consider the sales database below, there is one customer table, one orders table, and one seller table instead of a single table.</p><p>Table: Customer</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| customer_id   | int     |<br>| customer_name | varchar |<br>+---------------+---------+<br>customer_id is the primary key for this table.<br>Each row of this table contains the information of each customer in the WebStore.</pre><p>Table: Orders</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| order_id      | int     |<br>| sale_date     | date    |<br>| order_cost    | int     |<br>| customer_id   | int     |<br>| seller_id     | int     |<br>+---------------+---------+<br>order_id is the primary key for this table.<br>Each row of this table contains all orders made in the webstore.<br>sale_date is the date when the transaction was made between the customer (customer_id) and the seller (seller_id).</pre><p>Table: Seller</p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| seller_id     | int     |<br>| seller_name   | varchar |<br>+---------------+---------+<br>seller_id is the primary key for this table.<br>Each row of this table contains the information of each seller.</pre><p><strong>Key Characteristics:</strong></p><ol><li>Reduction of Redundancy: Data is stored in its most atomic form, reducing duplication i.e. less duplicity of data.</li><li>Complex Queries: Since data is in multiple tables, Often requires more complex queries with multiple joins to retrieve data.</li><li>Storage Efficiency: Generally requires less storage because of reduced data duplication.</li><li>Update Efficiency: Updates are more efficient since data is not duplicated across multiple locations. image if order info is in both the customer&#39;s table and in the orders table, then we need to update data at both places.</li><li>Data Integrity: Easier to maintain data integrity and enforce referential integrity. for example, if you want to only give customer data to another team, but not the order access to another team😉.</li></ol><p><strong>When to Use:</strong></p><ul><li>When data integrity is crucial.</li><li>When updates, inserts, and deletes are frequent.</li><li>When storage efficiency is a priority.</li><li>In OLTP (Online Transaction Processing) systems for example in banking.</li></ul><h3>Denormalized Schema</h3><p><strong>Definition</strong>: Denormalization is the process of combining tables to reduce the number of joins needed in queries, often resulting in some redundancy.</p><p><strong>Example</strong>: Instead of the 3 tables in the sales data warehouse above, we might have a single big table containing all the details.</p><p><strong>Key Characteristics:</strong></p><ol><li>Query Performance: Improved read performance with simpler and faster queries due to fewer joins.</li><li>Redundancy: Data duplication is common, which can lead to inconsistencies if not managed carefully.</li><li>Simplified Queries: Queries are simpler and often faster because they require fewer joins.</li><li>Increased Storage: Requires more storage due to duplicated data.</li><li>Complex Updates: Updates are more complex and prone to anomalies since multiple copies of the same data need to be kept in sync.</li></ol><p><strong>When to Use:</strong></p><ul><li>When read performance is a priority.</li><li>In data warehousing and OLAP (Online Analytical Processing) systems like hive where read-heavy operations are common.</li><li>When complex reporting and data retrieval are required.</li></ul><h3>Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r7BH3Bt7PJbqpenvbdR4g.png" /></figure><h3>Conclusion</h3><p>Choosing between a normalized and denormalized schema depends on the specific needs of your data warehouse:</p><ul><li>Normalized Schema: Best suited for environments where data integrity and storage efficiency are paramount, and where the workload involves frequent updates like <strong>banking</strong>.</li><li>Denormalized Schema: Best suited for environments where read performance and query simplicity are critical, and where the workload involves complex reporting and analytics like <strong>telecom</strong>.</li></ul><p>In many real-world scenarios, a hybrid approach is often used, where critical transactional data is kept normalized to ensure integrity, and non-critical, read-heavy data is denormalized to optimize performance.</p><p><strong>Not sure what to read next? I’ve picked another article for you:</strong></p><ul><li><a href="https://medium.com/@shubhambadaya13/asked-python-interview-questions-for-data-science-24b1c6b6588c">Asked Python interview questions for data science/engineering.</a></li><li><a href="https://medium.com/@shubhambadaya13/data-wrangling-in-pandas-vs-sql-a-comprehensive-comparison-e14a00fedd5d">Data Wrangling in Pandas vs SQL: A Comprehensive Comparison</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c686a7d509ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural network intuition]]></title>
            <link>https://medium.com/@shubhambadaya17/neural-network-intuition-abafa1b5d6a0?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/abafa1b5d6a0</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 05:20:58 GMT</pubDate>
            <atom:updated>2024-03-10T17:43:39.656Z</atom:updated>
            <content:encoded><![CDATA[<p>My post here is inspired by my subsequent reading of various textbooks on machine learning and deep learning. The aim here is to express the idea of neural networks concisely and intuitively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2zkvRWbyIEOY9hMt" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will try to understand the following:</p><ol><li>What is a neural network?</li><li>Input layer consideration.</li><li>How do they work and their components?</li></ol><h3>What is a neural network?</h3><blockquote>A network consists of <strong>layers of neurons</strong>.</blockquote><p>Now it leaves us with two more questions, layer and neurons?</p><p><strong>What are neurons?</strong></p><blockquote><strong><em>Mathematically, functions.</em></strong></blockquote><p>Neurons are function, which takes some input data and modifies the input data.</p><p><strong>What is a layer?</strong></p><p>A data-processing module or filter mechanism for data. Some data goes in, and it comes out in a more useful form.</p><p><strong>Hence, a neural network consists of chaining together simple layers that will implement a <em>form of progressive data distillation</em>.</strong></p><blockquote>Remember there is no such thing as an input layer, though the input is shown as a layer, in reality, we don’t have any input layer, we have inputs.</blockquote><h3>How is the number of input neurons determined?</h3><p>This is very important to understand, as every problem has a different type of input data. In a neural network, the number of input neurons is determined by the dimensionality of the input data. Each feature or aspect of the input data is typically represented by one input neuron.</p><p>For example:</p><ol><li><strong>Image Recognition</strong>: In the case of image recognition, if you’re working with grayscale images of size 28x28 pixels, each pixel can be considered a feature, so you would have 28x28 = 784 input neurons.</li><li><strong>Natural Language Processing (NLP)</strong>: In NLP tasks like sentiment analysis, you might represent each word using a one-hot encoding or word embedding. If you’re working with a fixed-size vocabulary of, say, 10,000 words, you would have 10,000 input neurons.</li><li><strong>Time Series Analysis</strong>: In time series analysis, each time step could be considered a feature. For example, if you’re analyzing stock prices with a time window of the last 30 days, you might have 30 input neurons.</li></ol><h3>How do neural networks work?</h3><p><strong>Imagine you’re trying to solve a puzzle</strong>. Each neuron is like a person trying to figure out their part of the puzzle. They receive some information (<em>input</em>), process it (<em>apply weights and biases</em>), and pass on their piece of the puzzle to the next person (<em>next layer</em>). As information flows through the network(<em>training</em>), it gradually pieces together the solution.</p><p>In the whole process of training, we need help with other things to solve the puzzle:</p><ol><li><strong>Loss Function:</strong></li></ol><p><strong>The loss function is like a scorekeeper</strong>, telling you how well your network is doing to solve the problem. It compares the network’s output to the actual correct answer and gives you a measure of how far off the network’s prediction is. The goal of training the neural network is to minimize this loss function, essentially making the network better at solving the problem.</p><blockquote>Imagine you’re playing a game, and the loss function is like keeping track of how many moves it takes you to solve the puzzle. The fewer moves you need, the lower your score (loss).</blockquote><p><strong>2. Optimizer:</strong></p><p>The optimizer is like the coach who helps the neural network learn from its mistakes. It adjusts the weights and biases of the neurons based on the information provided by the loss function. The optimizer’s job is to find the best way to tweak the network’s parameters to minimize the loss.</p><blockquote>Think of the optimizer as someone giving you hints on how to solve the puzzle more efficiently.</blockquote><p><strong>3. Metric:</strong></p><p>Imagine you’re playing a game, and while the loss function keeps track of how many moves it takes you to solve the puzzle, the metric might also tell you how accurately you’re placing the pieces. It gives you a different perspective on your performance.</p><blockquote>Understand it more like a destination.</blockquote><p><strong>Not sure what to read next? I’ve picked another article for you:</strong></p><ul><li><a href="https://medium.com/@shubhambadaya13/data-science-fundamentals-often-asked-in-interviews-292a2dfd8826">Data science fundamentals often asked in interviews</a></li><li><a href="https://medium.com/@shubhambadaya13/data-wrangling-in-pandas-vs-sql-a-comprehensive-comparison-e14a00fedd5d">Data Wrangling in Pandas vs SQL: A Comprehensive Comparison</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abafa1b5d6a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Wrangling in Pandas vs SQL: A Comprehensive Comparison]]></title>
            <link>https://medium.com/@shubhambadaya17/data-wrangling-in-pandas-vs-sql-a-comprehensive-comparison-e14a00fedd5d?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e14a00fedd5d</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 14:55:58 GMT</pubDate>
            <atom:updated>2024-01-15T14:25:38.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Frequently, I find myself navigating between SQL and Pandas in my work. On certain days, I find myself crafting queries directly on the database, while on other days, I delve into working with flat files. Although I’m well-versed in executing SQL operations, when it comes to working with flat files in pandas, I sometimes face uncertainties about translating SQL processes into the corresponding pandas operations. In response to this, I am currently in the process of developing a comprehensive guide that aims to assist beginners in Pandas, especially when transitioning from a background in SQL.</p><p>To lay the groundwork for this guide, let’s first establish a fundamental understanding.</p><blockquote>There are multiple ways to perform the below operations. However, I am showing below the most basic operations.</blockquote><h4>Why do we need pandas when we can run queries on a database?</h4><ol><li>As pandas is in-memory, once the data is loaded. querying the data is very fast. While in SQL each query will take its time to hit the database.</li><li>When working on a data analysis project, we need to view results, iterate, and visualize, where pandas is helpful.</li><li>When the data size is such that it can’t fit in memory, then use SQL or PySpark.</li></ol><h4>1. How to read CSV in Pandas?</h4><pre>import pandas as pd<br>df = pd.read_csv(&#39;data.csv&#39;) ## replace data.csv with file path where csv is placed<br><br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ngf_G0YSgKHHs2qXPsfkqQ.png" /></figure><h3>2. How to use sql SELECT statement in pandas?</h3><p><strong>SQL:</strong></p><pre>SELECT ShopID , price FROM df</pre><p><strong>Python:</strong></p><p>Method 1: Use <strong>[ ]</strong> to select desired columns.</p><pre>#Select all rows and columns &#39;ShopID&#39; and &#39;price&#39;<br>df[[&#39;ShopID&#39;, &#39;price&#39;]] </pre><p>Method 2: Use <strong>loc</strong> to access rows and columns by label.</p><pre># Select all rows and columns &#39;ShopID&#39; and &#39;price&#39;<br>df.loc[:, [&#39;ShopID&#39;, &#39;price&#39;]]</pre><p>Method 3: Use <strong>iloc</strong> to access rows and columns by integer position.</p><pre># Select all rows for columns at indices 0 and 2<br>df.iloc[:, [0, 1]]  </pre><p>Method 4: Use <strong>boolean</strong></p><pre>mask = [True, True, False]  # Select first and second columns<br>df.loc[:, mask]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8NsSecYmIOMrlEv7zLiLg.png" /></figure><h4><strong>3. How to apply sql WHERE condition in Python?</strong></h4><p>SQL: Select all row here price is greater than 4</p><pre>select * from df where price &gt; 4</pre><p>Python:</p><pre><br>df[df[&#39;price&#39;] &gt; 4]</pre><p>SQL: Select all row here price is greater than 5 and product is ‘scissor’</p><pre>select * from df where price &gt; 5 and product = &#39;scissor&#39;</pre><p>Python:</p><pre>df[(df[&#39;product&#39;] == &#39;scissor&#39;) &amp; (df[&#39;price&#39;] &gt; 5)]</pre><p>SQL: select all rows where price is 2 and 4.</p><pre>select * from df where price in (2,4)</pre><p>Python:</p><pre>values_to_keep = [2, 4]<br>df[df[&#39;price&#39;].isin(values_to_keep)]</pre><h3>4. How to do sql group by in pandas?</h3><p><strong>Method 1:</strong></p><p><em>Find the avg price by shopID</em></p><pre>df.groupby(&quot;ShopID&quot;)[&quot;price&quot;].mean()</pre><p><strong>Method 2:</strong></p><p><em>Find the count of products in each shop excluding NULL.</em></p><pre># count will not inlcude null values<br>df.groupby([&quot;ShopID&quot;, &quot;product&quot;]).count() </pre><p><strong>Method 3:</strong></p><p><em>Find the count of products in each shop including NULL.</em></p><pre># size will include count of null values<br>df.groupby([&quot;ShopID&quot;, &quot;product&quot;]).size() </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhtuwSqkzKCoBtLJUEXv6g.png" /></figure><p><strong>Method 4:</strong></p><p><em>Use as_index = False, to keep them as df columns.</em></p><pre>df.groupby([&quot;ShopID&quot;, &quot;product&quot;], as_index = False).size()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sntYhKx8bpkeCfcmSJtsvQ.png" /></figure><p>Method 5:</p><pre>df.groupby([&quot;ShopID&quot;, &quot;product&quot;])[&#39;price&#39;].agg([&#39;min&#39;, &#39;max&#39;]).reset_index()</pre><p><strong>Note:</strong> The reset_index() function is used to convert the grouped result back to a DataFrame.</p><h3>5. How to apply group by having a clause</h3><p>In SQL we can directly use having after group by. However, in Python, it is a 2-step process.</p><p>Step-1. calculate a grouped df</p><p>Step-2. Apply a filter.</p><pre># Group by &quot;shopID&quot; and calculate the avg price for each shopID<br>grouped_df = df.groupby(&#39;ShopID&#39;)[&#39;price&#39;].mean()<br><br><br># # Filter groups where the sum is greater than a threshold (e.g., 5)<br>filtered_groups = grouped_df[grouped_df &gt; 5]<br><br># # Display the result<br>filtered_groups</pre><h3>6. How to use case when statement in pandas</h3><p>Method 1: If a single condition</p><pre>import numpy as np<br># Create a new column &#39;Age Group&#39; using np.where<br>df[&#39;Price Group&#39;] = np.where(df[&#39;price&#39;] &gt;= 6, &#39;High&#39;, &#39;Low&#39;)<br><br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTAHMp8n78RLT_AIPtRusg.png" /></figure><p>Method 2: If multiple conditions</p><pre>conditions = [<br>    df[&#39;price&#39;] &lt; 4,<br>    (df[&#39;price&#39;] &gt;= 4) &amp; (df[&#39;price&#39;] &lt; 8),<br>    df[&#39;price&#39;] &gt;= 8<br>]<br>choices = [&#39;low&#39;, &#39;med&#39;, &#39;high&#39;]<br><br>df[&#39;Price Group&#39;] = np.select(conditions, choices, default=&#39;Invalid Price&#39;)<br><br>print(df)</pre><h3>7. How to apply windows function in pandas</h3><pre>df[&#39;rolling_mean&#39;] = df[&#39;price&#39;].rolling(window=3).mean()<br><br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJk-ENhY3x5IwYgQPBSzmA.png" /></figure><pre>## rank in pandas<br>df[&#39;rank&#39;] = df.groupby(&#39;ShopID&#39;)[&#39;price&#39;].transform(&#39;rank&#39;)</pre><pre>## dense rank in pandas<br>df[&#39;Dense_Rank&#39;] = df.groupby(&#39;ShopID&#39;)[&#39;price&#39;].transform(lambda x: x.rank(method=&#39;dense&#39;))<br><br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1-zmgG4e7EKfXUI1Zqnng.png" /></figure><h3>8. How to join dataframes in pandas</h3><p>Create a data frame (grouped_df) with avg price on the shop and join the same with the initial dataframe <strong>df</strong>.</p><pre># find the avg price per shop and join it with df<br>grouped_df = df.groupby(&#39;ShopID&#39;, as_index = False)[&#39;price&#39;].mean()<br><br># column rename {oldname : newname} with the use of inplace argument<br>grouped_df.rename(columns={&#39;price&#39;: &#39;avg_price_on_shop&#39;}, inplace = True)</pre><p><strong>Note:</strong></p><ol><li>Many Pandas methods have <strong>inplace</strong> as an optional parameter, and its default value is often False. This means that, by default, Pandas operations return a new modified object.</li><li>Using <strong>inplace</strong>=True can be memory-efficient when dealing with large datasets, as it avoids creating unnecessary copies of the data.</li><li>Modifying objects <strong>inplace</strong> can make the code less readable and more error-prone, especially for complex operations. Consider using the non-inplace version of methods if readability and clarity are important.</li></ol><pre># join the dataframes to find the avg price per shop<br>result = pd.merge(df, grouped_df, left_on=&#39;ShopID&#39;,right_on=&#39;ShopID&#39;, how=&#39;inner&#39;)<br><br>print(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bVYkY3HJIuFBtC39bSXXQ.png" /></figure><h3>9. How to read pandas data frame from oracle database(exa)?</h3><pre><br>import pandas as pd<br>import cx_Oracle<br><br># Set up Oracle connection parameters<br>oracle_connection = {<br>    &#39;user&#39;: &#39;your_username&#39;,<br>    &#39;password&#39;: &#39;your_password&#39;,<br>    &#39;dsn&#39;: &#39;your_oracle_dsn&#39;  # e.g., &#39;localhost:1521/your_service_name&#39;<br>}<br><br># Connect to Oracle database<br>connection = cx_Oracle.connect(**oracle_connection)<br><br># SQL Query to retrieve data from a table<br>sql_query = &quot;SELECT * FROM your_table_name&quot;<br><br># Read data into a Pandas DataFrame<br>df = pd.read_sql(sql_query, connection)<br><br># Close the database connection<br>connection.close()<br><br># Display the DataFrame<br>print(df)</pre><p><strong>Not sure what to read next? I’ve picked another article for you:</strong></p><ul><li><a href="https://medium.com/@shubhambadaya13/asked-python-interview-questions-for-data-science-24b1c6b6588c">Asked Python interview questions for data science/engineering.</a></li><li><a href="https://medium.com/@shubhambadaya13/data-science-fundamentals-often-asked-in-interviews-292a2dfd8826">Data science fundamentals often asked in interviews</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e14a00fedd5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data science fundamentals often asked in interviews]]></title>
            <link>https://medium.com/@shubhambadaya17/data-science-fundamentals-often-asked-in-interviews-292a2dfd8826?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/292a2dfd8826</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-anlytics]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 15:50:22 GMT</pubDate>
            <atom:updated>2024-01-20T13:42:53.611Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, I present and share the solution for theory and concept-related questions that were asked to me or I had asked in data science interviews.</h4><h4>1. What is Gradient descent?</h4><p>Gradient descent is an <strong>optimization algorithm</strong></p><p><strong>Why?</strong> Used in machine learning and deep learning to minimize the error or loss function of a model. To find weights and biases.</p><p><strong>How?</strong> By iteratively moving toward the steepest decrease in the function.</p><blockquote>Gradient descent is older — much, much older — than machine learning.</blockquote><h4>2. What is the difference between a t-test and a z-test?</h4><p>T-tests and z-tests are statistical methods used for hypothesis testing, specifically for comparing the means of two groups.</p><p>The main difference between the two lies in the context in which they are applicable and the assumptions they make.</p><p><strong>Type of Data:</strong></p><ul><li>Z-test: Typically used when the sample size is large (usually n &gt; 30) or when the population standard deviation is known.</li><li>T-test: Used when the sample size is small (typically n &lt; 30) or when the population standard deviation is unknown.</li></ul><p><strong>Population Standard Deviation:</strong></p><ul><li>Z-test: Assumes that the population standard deviation is known.</li><li>T-test: Does not assume knowledge of the population standard deviation and instead estimates it from the sample data.</li></ul><p><strong>Sample Size:</strong></p><ul><li>Z-test: Suitable for large sample sizes, where the central limit theorem ensures that the sampling distribution of the sample mean is approximately normal.</li><li>T-test: More appropriate for small sample sizes, where the normality assumption of the sampling distribution is not guaranteed, but the t-distribution provides a better approximation.</li></ul><p><strong>Formula:</strong></p><ul><li>Z-test: Uses the standard normal distribution (z-distribution) for hypothesis testing.</li><li>T-test: Uses the t-distribution for hypothesis testing, which has heavier tails compared to the normal distribution, reflecting the increased uncertainty associated with estimating the population standard deviation from a small sample.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kll-IBnSX1wKVUkg.png" /><figcaption>Image Source: <a href="https://medium.com/@dhaval.sony.504/know-t-distribution-z-test-765fb34a2ef3">https://medium.com/@dhaval.sony.504/know-t-distribution-z-test-765fb34a2ef3</a></figcaption></figure><p><strong>Example:</strong></p><ul><li>Z-test: If you were comparing the average height of a sample of 200 adults to a known population average height.</li><li>T-test: If you were comparing the average test scores of a sample of 25 students to the average scores of the entire student population.</li></ul><p>In summary, choose between a z-test and a t-test based on the <strong>size of your sample</strong> and <strong>whether you know the population standard deviation</strong>.</p><p>If the sample size is large and the population standard deviation is known, a z-test may be appropriate.</p><p>If the sample size is small or the population standard deviation is unknown, a t-test is often more suitable.</p><h4>3. What is the p-value?</h4><p>In the general hypothesis testing procedure, we will have some hypotheses about the population parameter and we investigate it using a sample extracted from the population.</p><p>A p-value is nothing but the probability of observing such a sample from the population given that the null hypothesis is true, if the probability is too small, we doubt the accuracy of a null hypothesis and reject it, otherwise, we accept the Null hypothesis by saying we don’t have enough evidence to reject the null hypothesis.</p><blockquote>The <em>p-</em>value reflects the strength of evidence against the null hypothesis.</blockquote><p>P-value helps the statistician to draw conclusions on the Null hypothesis and is always between 0 and 1.</p><ul><li>P- Value &gt; 0.05 denotes weak evidence against the null hypothesis which means the null hypothesis cannot be rejected.</li><li>P-value &lt; 0.05 denotes strong evidence against the null hypothesis which means the null hypothesis can be rejected.</li><li>P-value=0.05 is the marginal value indicating it is possible to go either way.</li></ul><h4>4. In which scenario results from random forest models can be better than gradient boosting models?</h4><ol><li>RFs can handle extremely high dimensional datasets which makes them an excellent choice when dealing with a large number of variables.</li><li>GBM cannot work effectively with such high-dimensional data due to overfitting issues.</li></ol><h4>5. What are bias and variance in modeling?</h4><p>Bias: relates to the model’s simplicity and its ability to capture the underlying patterns</p><p>Variance: relates to the model’s flexibility and its sensitivity to fluctuations in the training data.</p><p>The goal of machine learning is to find a model that achieves a balance between bias and variance to generalize well to new, unseen data.</p><h4>6. Why gradient boosting is prone to overfitting?</h4><p>There are multiple factors influencing overfitting in boosting algorithms. However, they can be characterized as shown below:</p><ol><li><strong>Complexity of Weak Learners:</strong> If the weak learners are too complex or have too much depth, there’s a higher risk of overfitting</li><li><strong>Number of Iterations (Boosting Rounds):</strong> Increasing the number of boosting rounds can lead to overfitting</li><li><strong>Data Characteristics:</strong> If the dataset is noisy or has outliers, boosting algorithms may be more susceptible to fitting the noise.</li></ol><p><strong>Not sure what to read next? I’ve picked other articles for you:</strong></p><p><a href="https://medium.com/@shubhambadaya13/asked-python-interview-questions-for-data-science-24b1c6b6588c">Asked Python interview questions for data science/engineering.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292a2dfd8826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand clustering in data science without mathematics]]></title>
            <link>https://medium.com/@shubhambadaya17/clustering-in-data-science-without-mathematics-0baea27102c0?source=rss-4229022f361c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0baea27102c0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[shubham badaya]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 10:34:42 GMT</pubDate>
            <atom:updated>2024-03-09T04:38:29.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R8_lNbkor7MxKlHq" /><figcaption>Photo by <a href="https://unsplash.com/@melpoole?utm_source=medium&amp;utm_medium=referral">Mel Poole</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Frequently, we find ourselves questioning the nature of clustering, its distinctions from classification, and the general methods employed in clustering. In this article, I aim to unravel these queries specifically for beginners. For in-depth mathematical details, I recommend consulting books. However, to cultivate an intuitive understanding of clustering, please turn to this article.</p><p>In this article, we will try to understand the following:</p><ol><li>What is clustering?</li><li>How it is different from classification problems.</li><li>How clustering is done?</li></ol><h4><strong>What is Clustering?</strong></h4><p>Clustering is a technique used in data analysis to <strong>group similar objects</strong> or data points <strong>based on certain characteristics</strong> or attributes.</p><p>For example suppose, you have a set of marbles of various colors like blue, green red. You want to cluster them based on color. So, green ones will form Group 1, red ones will be in Group 2, yellow ones will be in Group 3, and blue ones will be in Group 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/0*xGK_AvN20_QNkCNw.png" /><figcaption>Example 1 (source: <a href="https://www.baeldung.com/java-k-means-clustering-algorithm">https://www.baeldung.com/java-k-means-clustering-algorithm</a>)</figcaption></figure><p>In the above example, the <strong>objects are marbles</strong> and the <strong>characteristic is color</strong>.</p><h4>How clustering is different from classification?</h4><blockquote>Clustering is about finding patterns in data without any prior knowledge, while classification is about predicting labels, categories, or groups.</blockquote><p>In clustering, a <strong>complete dataset(i.e. there is no concept of training and test dataset) </strong>is used to find groups, whereas in classification the model is trained first on a training dataset with groups already known, and new observation labels are predicted later.</p><h4>How clustering is done?</h4><p>As explained earlier, we cluster data based on characteristics. In the above explanation, it was color for us. Now how algorithm understand if 2 data points are the same or not?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*yjP9KAc1V9KHCJq4" /><figcaption>Example 2: Source (<a href="https://statisticsbyjim.com/basics/k-means-clustering/">https://statisticsbyjim.com/basics/k-means-clustering/</a>)</figcaption></figure><p>Consider the data above in the example 2. There are multiple companies in the dataset. Each company or row will be considered a vector. The distance between each row is calculated the same way the distance between 2 vectors is calculated. Each feature/attribute will be a dimension. Hence this is a 4-D problem. Closest rows will be clubbed together to form clusters. In short, a simple distance metric will be used to calculate the similarity between 2 pairs.</p><p>This distance metric will differ depending on the problem statement. The most preferred one is Euclidean, however, there are plenty of such metrics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0baea27102c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>