<?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 Debaditya Samanta on Medium]]></title>
        <description><![CDATA[Stories by Debaditya Samanta on Medium]]></description>
        <link>https://medium.com/@halfdeb?source=rss-89149fdf64f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3GbTwMA1FGtmPBUDAhrEwQ.png</url>
            <title>Stories by Debaditya Samanta on Medium</title>
            <link>https://medium.com/@halfdeb?source=rss-89149fdf64f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:35:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@halfdeb/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[Great Software Begins Here: Diving into Object-Oriented Analysis & Design (Part 1)]]></title>
            <link>https://medium.com/@halfdeb/great-software-begins-here-diving-into-object-oriented-analysis-design-part-1-e14f776b4455?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e14f776b4455</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 18:58:56 GMT</pubDate>
            <atom:updated>2026-06-01T18:58:56.842Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Real-world software is more than just code. Here is what I learned from chapter 1 of Head First Object-Oriented Analysis &amp; Design.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtUGtv2_aAYmq81Ccb8qYg.png" /></figure><h3>Stop Fixing the Symptom: What a Guitar Shop Taught Me About Writing Better Code</h3><p>There’s a moment every developer recognises. The app is running. The tests pass. You shipped it on time. And then a week later, the client calls and says things aren’t working.</p><p>Not “broken” in a stack-trace way. More like….. <em>wrong</em>. Quietly, frustratingly wrong in a way that’s hard to pin down until you realise the whole thing was solving the wrong problem from the start.</p><p>That’s the story at the heart of <em>Head First Object-Oriented Analysis &amp; Design</em>, and it’s one of the most quietly devastating lessons in software development: your code can be completely correct and still completely fail.</p><p>Let me tell you about Rick.</p><h3>Rick’s Guitar Shop</h3><p>Rick owns a guitar store. He hired a developer to replace his handwritten inventory ledger with a proper software system. The developer built a <strong>Guitar </strong>class, an <strong>Inventory</strong> class, and a <strong>search()</strong> method. It compiled. It ran. It looked like software.</p><p>The customers started walking out empty-handed.</p><p>A customer named Erin came in asking for a Fender Stratocaster with Alder wood. Rick ran the search. Nothing. He knew he had that guitar. He’d just restrung it. But the system returned zero results every time.</p><p>The developer’s instinct and honestly, most of ours, would be to open the code and start hunting for a bug. But here’s the thing: <strong>there was no bug</strong>. The code was doing exactly what it was told. The problem was what it was told to do.</p><p>The search was case-sensitive. Erin said “Stratocaster”. The database stored “stratocaster”. Game over.</p><p>But that’s not even the real problem. The real problem is that nobody asked <em>what does a good search actually need to do?</em> before writing a single line of code. Nobody distinguished between what the system was failing at (the symptom) and why it was failing by design(the actual problem).</p><p>This confusion between symptom and root cause is one of the most expensive mistake in software development.</p><h3>Analysis vs Design: Getting the Order Right</h3><p>Before we look at how to fix Rick’s system, it’s worth pausing on a distinction that most tutorials either gloss over or skip entirely: the difference between<strong> analysis</strong> and <strong>design</strong>.</p><p>These two words get thrown around interchangeably, but they mean genuinely different things.</p><p><strong>Object-Oriented Analysis (OOA)</strong> is about understanding <em>what </em>you’r building. It lives in the perfect domain, the real world. What does customer actually need? What are the real objects involved? What relationship exist between them? This phase is deliberately independent of any programming language or framework. You should be able to do it with a whiteboard and a pen.</p><p><strong>Object-Oriented Design (OOD) </strong>is about deciding<em> how </em>to build it. This is where classes, data structures, algorithms, and architectural decisions come in.</p><p>The mistake Rick’s developer made was jumping straight to design without spending any time on <em>what.</em> And you simply cannot design your way out of misunderstood problem.</p><p>A useful way to think about it: OOA is the map, OOD is the route. You can plan the most elegant route in the world, but if you don’t know where you’re going, you’ll end up somewhere wrong very efficiently.</p><h3>What Are We Actually Solving?</h3><p>So let’s do what the developer didn’t. Let’s analyse Rick’s real requirements.</p><p><strong>Functional requirements </strong>describe what the system must do:</p><ul><li>Allow searching by builder (Fender, Gibson, Martin, and so on)</li><li>Allow searching by guitar type (acoustic or electric)</li><li>Allow searching by wood type</li><li>Return <em>all</em> matching guitars, not just one</li><li>Match regardless of capitalisation</li><li>Handle partial model name matches. So “Strat” can find “Stratocaster”</li></ul><p><strong>Non-functional requirements </strong>describe constraints and quality expectations:</p><ul><li>Search must respond quickly</li><li>The interface must be usable by someone who isn’t a developer</li></ul><p>The distinction matters. “Search by builder” is functional, it describes a behaviour. “Search must respond within two seconds” is non-functional. It describes a quality standard. Both are real requirements. Both are routinely ignored.</p><p>had the original developer written these down and walked through them with Rick before opening his IDE, the case-sensitivity problem would have surfaced before a single line of code was written. That is the entire point of analysis.</p><h3>The First Design Mistake: Strings Everywhere</h3><p>Here’s roughly what the original <strong>Guitar</strong> class looked like:</p><pre>public class Guitar<br>{<br>  public string SerialNumber { get; set; }<br>  public decimal Price { get; set; }<br>  public string Builder { get; set; } // &quot;Fender&quot;, &quot;fender&quot;, &quot;FENDER&quot;...<br>  public string Model { get; set; }<br>  public string Type { get; set; } // &quot;acoustic&quot;, &quot;Acoustic&quot;, &quot;ACOUSTIC&quot;...<br>  public string BackWood { get; set; }<br>  public string TopWood { get; set; }<br>}</pre><p>Every field that should be a fixed category is a free-text string. This is a silent disaster. There is nothing stopping someone entering “Fender”, “fender”, “Feder”(a typo), or “fEnDeR”. All doubt would fail to match each other, and your search would quietly return nothing with no error, no warning, and no clue why.</p><p>The fix is immediate and obvious once you see it: <strong>use enumerations.</strong></p><pre>public enum Builder<br>{<br>  Fender, Martin, Gibson, Collings, Olson, PaulReedSmith, Any<br>}<br><br>public enum GuitarType { Acoustic, Electric }<br><br>public enum Wood<br>{<br>  IndianRosewood, BrazilianRosewood, Mahogany,<br>  Maple, Cocobolo, Cedar, Adirondack, Alder, Sitka<br>}</pre><p>Enums enforce valid values at compile time. You cannot accidentally type “Fender” with a lowercase f. You cannot store a wood type that does not exist in the domain. Comparisons become simple checks instead of fragile string juggling. This one change eliminates an entire class of bugs before they can happen, not by being clever, but by making the invalid unpresentable.</p><h3>The second Mistake: One Class Doing Too Much</h3><p>Even with enums, the original <strong>Guitar </strong>class had a deeper structural problem. It was trying to be two things at once:</p><ul><li>A <strong>physical object </strong>with a unique identity :- a serial number, a price tag</li><li>A <strong>specification </strong>describing what kind of guitar it is :- builder, model, type, woods</li></ul><p>These are genuinely different concepts, and mixing them creates real friction. When Erin searches for a guitar, she doesn’t know its serial number. She doesn’t know the price. She knows she wants a Fender, Stratocaster, Electric, with Alder back and top. She is describing a <em>specification, </em>not a particular physical guitar.</p><p>If we pass a full <strong>Guitar</strong> object into the search method, we have to invent fake values for <strong>SerialNumber </strong>and <strong>Price</strong> just to satisfy the constructor. That is the system leaking its own internal confusion back onto the person using it.</p><p>The solution is to separate the two concepts cleanly:</p><pre>public class GuitarSpec<br>{<br>    public Builder Builder { get; }<br>    public string Model { get; }<br>    public GuitarType Type { get; }<br>    public Wood BackWood { get; }<br>    public Wood TopWood { get; }<br><br>    public GuitarSpec(Builder builder, string model, GuitarType type,<br>                      Wood backWood, Wood topWood)<br>    {<br>        Builder = builder;<br>        Model = model;<br>        Type = type;<br>        BackWood = backWood;<br>        TopWood = topWood;<br>    }<br>}<br><br>public class Guitar<br>{<br>    public string SerialNumber { get; }<br>    public decimal Price { get; set; }<br>    public GuitarSpec Spec { get; }<br><br>    public Guitar(string serialNumber, decimal price, GuitarSpec spec)<br>    {<br>        SerialNumber = serialNumber;<br>        Price = price;<br>        Spec = spec;<br>    }<br>}</pre><p>Notice that <strong>Guitar</strong> now has a <strong>GuitarSpec</strong> rather than absorbing all those fields directly. This is <strong>composition, </strong>one of the most practical structural tools in object-oriented design. And the relationship is intuitive: every guitar has a spec, but a spec is not a guitar.</p><p>When searching, you hand the system a <strong>GuitarSpec</strong>, no serial number, no price, no invented values needed. The system matches your spec against the specs of every guitar in stock and returns the real <strong>Guitar</strong> object that qualify. The API tells the truth about what it actually needs.</p><h3>The Single Responsibility Principle in Practise</h3><p>There is a well-known principle behind this design decision: the <strong>Single Responsibility Principle (SRP).</strong></p><p>A class should have one reason to change. That is it. Just one.</p><p>When your <strong>Guitar </strong>class held everything — identity, pricing, and every descriptive attribute. It had multiple reason to change. Add a new guitar attribute? Change <strong>Guitar. </strong>Change how prices work? Change <strong>Guitar</strong>. Change how you search matching works? Still <strong>Guitar.</strong> One class has become a load-bearing wall that half the system leans on.</p><p>With the separation, the picture clears up immediately:</p><ul><li><strong>GuitarSpec </strong>changes when the attributes describing a guitar change.</li><li><strong>Guitar</strong> changes when the structure of guitar identity or pricing changes.</li><li><strong>Inventory </strong>changes when the logic for storing or finding guitars changes.</li></ul><p>Each class is smaller, focused, and easier to reason about in isolation. If you return to this codebase in six months and need to add a “number of strings” field, you know exactly where it belongs. It is what separates a maintainable system from a minefield.</p><h3>Building a Search That Actually Works</h3><p>With the structural problems resolved, the search logic itself becomes much cleaner. Here is a version that handles case-insensitive matching and partial model name lookups:</p><pre>public IList&lt;Guitar&gt; Search(GuitarSpec searchSpec)<br>{<br>    var results = new List&lt;Guitar&gt;();<br><br>    foreach (var guitar in guitars)<br>    {<br>        // Enum comparisons are exact — no case issues possible<br>        if (searchSpec.Builder != guitar.Spec.Builder) continue;<br>        if (searchSpec.Type != guitar.Spec.Type) continue;<br>        if (searchSpec.BackWood != guitar.Spec.BackWood) continue;<br>        if (searchSpec.TopWood != guitar.Spec.TopWood) continue;<br><br>        // Model name: case-insensitive, allows partial match<br>        if (!string.IsNullOrEmpty(searchSpec.Model) &amp;&amp;<br>            guitar.Spec.Model.IndexOf(<br>                searchSpec.Model,<br>                StringComparison.OrdinalIgnoreCase) &lt; 0)<br>            continue;<br><br>        results.Add(guitar);<br>    }<br><br>    return results;<br>}</pre><p>Two details are worth calling out. First: <strong>StringComparison.OrdinalIgnoreCase. </strong>This is C#’s clean way of saying “compare these strings without caring about capitalisation. “One parameter. No <strong>.ToLower() gymnastics. </strong>No fragile manual normalisation that you’ll inevitable apply inconsistently.</p><p>Second: <strong>IndexOf(…) ≥ 0 </strong>rather than a direct equality check. This turns the model name match into a substring search. “Strat” will now find “Stratocaster.” The customer finds what she’s looking for. Tick makes a sale. The problem is actually solved.</p><p>You can also pull the matching logic directly onto <strong>GuitarSpec:</strong></p><pre>public bool Matches(GuitarSpec other)<br>{<br>    if (other.Builder != Builder) return false;<br>    if (!string.IsNullOrEmpty(other.Model) &amp;&amp;<br>        !Model.Equals(other.Model, StringComparison.OrdinalIgnoreCase))<br>        return false;<br>    if (other.Type != Type) return false;<br>    if (other.BackWood != BackWood) return false;<br>    if (other.TopWood != TopWood) return false;<br>    return true;<br>}</pre><p>This makes <strong>Matches() </strong>independently unit-testable. You can feed it input combinations without touching <strong>Inventory</strong> at all.</p><h3>Value Objects and Why Equality Matters</h3><p>Because <strong>GuitarSpec</strong> is used as comparison object, it should behave like a <em>value.</em><strong><em> </em></strong>Two <strong>GuitarSpec</strong> instances with identical fields should be considered equal, the same way two <strong>DateTime </strong>objects representing midnight on the same day are equal regardless of being different objects in memory.</p><p>In C#, you get this by implementing <strong>IEquatable&lt;T&gt;</strong>:</p><pre>public class GuitarSpec : IEquatable&lt;GuitarSpec&gt;<br>{<br>    // ... properties and constructor ...<br><br>    public bool Equals(GuitarSpec? other)<br>    {<br>        if (other is null) return false;<br>        return Builder == other.Builder &amp;&amp;<br>               string.Equals(Model, other.Model,<br>                   StringComparison.OrdinalIgnoreCase) &amp;&amp;<br>               Type == other.Type &amp;&amp;<br>               BackWood == other.BackWood &amp;&amp;<br>               TopWood == other.TopWood;<br>    }<br><br>    public override int GetHashCode() =&gt;<br>        HashCode.Combine(Builder, Model?.ToLowerInvariant(),<br>                         Type, BackWood, TopWood);<br>}</pre><p>This also opens the door to using <strong>GuitarSpec </strong>as a dictionary key, useful if you later want to group guitars by spec for faster lookups as inventory grows.</p><p>And notice that <strong>GuitarSpec</strong> has no setters. Once created, it does not change. This <strong>immutability </strong>is intentional. Value objects should not mutate after construction. It makes them thread-safe, predictable, and far easier to reason about, especially when the same spec object gets passed around multiple methods.</p><h3>The Bigger Picture: A Better Workflow</h3><p>Everything we fixed traces back to the same root cause: the original developer skipped analysis and jumped into implementation. A more grounded workflow looks like this:</p><ul><li><strong>Requirements: </strong>Talk to Rick. Write down what the system actually needs to do, and the quality it needs to do it at. Distinguish functional from non-function.</li><li><strong>Analysis:</strong> Identify the real world objects. What are the nouns in the problem domain? Guitar. Spec. Customer. Inventory. What do they need? How do you relate? Stay out of your IDE at this stage.</li><li><strong>Design: </strong>Decide how to represent those objects in code. Introduce enums. Separate <strong>Guitar</strong> from <strong>GuitarSpec. </strong>Define the search contract. Make intentional choices, not accidental ones.</li><li><strong>Implementation:</strong> Write the code. At this point it should feel almost inevitable, because the design has already done the hard thinking.</li><li><strong>Testing and iteration: </strong>Write tests. See what breaks. Go back and refine. Expect requirements to evolve, they always do. <br>This is not a rigid waterfall process. You will loop back constantly. But you should always begin at step one, and you should never skip steps two and three. The cost of skipping them is not paid immediately, it is paid later, compound, when everything needs to change and the codebase resists.</li></ul><h3>Bad Design vs Good Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKWQiRAQSpe4Lr9Cf8ce3g.png" /></figure><p>The left column is not incompetent code. It is the code most of us write when we skip analysis and go straight to “make it work.” The right column is what you get what you slow down and think first. The difference in effort at the design stage is maybe two hours. The difference in maintenance cost over a year is immeasurable.</p><h3>The Real Lesson</h3><p>Rick’s story is not really about guitars. It is about the danger of confusing <em>motion</em> with <em>progress.</em></p><p>Writing code feels productive. Opening your IDE and typing feels like building something. And it is, but if you are building the wrong thing with wrong structure, every line of code is debt you will pay back later. Usually with interest.</p><p>The habit of asking “what is the actual problem here?” before writing anything is one of the highest-leverage skills a developer can build. It costs an hour of conversation and a whiteboard.</p><p>It saves weeks of refactoring.</p><p>Object-oriented analysis and design is not an academic exercise or a box to tick before the real work begins. It <em>is</em> the real work. It is how you make sure that what you build is actually solves what you were asked to solve.</p><p>Rick’s customers were walking out the door not because the developer was bad at coding. They walked out because nobody stopped to ask what “good search” actually meant before the first class was written.</p><p>Don’t be that developer.</p><p><em>The concepts in this article are drawn from Head First Object-Oriented Analysis &amp; Design, Chapter 1. Code examples are written in modern C# and adapted for clarity.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e14f776b4455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ AZ-900 Series — Part 1: Demystifying Cloud Computing and Azure Fundamentals]]></title>
            <link>https://medium.com/@halfdeb/%EF%B8%8F-az-900-series-part-1-demystifying-cloud-computing-and-azure-fundamentals-7dbd0552a5bc?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dbd0552a5bc</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-fundamentals]]></category>
            <category><![CDATA[az900]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 11:53:53 GMT</pubDate>
            <atom:updated>2025-04-14T11:53:53.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌩️ AZ-900 Series — Part 1: Demystifying Cloud Computing and Azure Fundamentals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*-6JOZTMv34_gYa4wXMTF9A.png" /></figure><p>Welcome to <strong>Part 1 of our deep-dive series</strong> into <strong>Azure Fundamentals (AZ-900)</strong> — your ultimate beginner-friendly guide to everything cloud and Azure. Whether you’re new to cloud computing or preparing for the AZ-900 certification exam, this series is your one-stop shop for understanding the foundational concepts, best practices, and real-world use cases.</p><p>In this first part, we focus on <strong>Cloud Computing Concepts </strong>breaking down the core ideas that power Azure and modern cloud platforms. So, grab a coffee (or a Red Bull), and let’s get into it.</p><h3>☁️ What is Cloud Computing?</h3><p>At its core, <strong>Cloud Computing</strong> is the <strong>on-demand delivery of computing services</strong> — such as servers, storage, databases, networking, software, analytics, and intelligence — <strong>over the internet</strong>, rather than owning and maintaining physical infrastructure.</p><p>Think of it like switching from buying DVDs to streaming movies on Netflix. Instead of investing in and maintaining your own servers, you access computing resources from a cloud provider like Microsoft Azure, and <strong>only pay for what you use</strong>.</p><h3>🔑 Key Characteristics:</h3><ul><li><strong>On-demand self-service</strong> — Spin up resources anytime without human interaction.</li><li><strong>Broad network access</strong> — Access services via standard networks and devices.</li><li><strong>Resource pooling</strong> — Shared infrastructure to serve multiple users efficiently.</li><li><strong>Rapid elasticity</strong> — Scale resources automatically or on-demand.</li><li><strong>Measured service</strong> — Transparent billing based on usage.</li></ul><h3>💡 Azure App Services: Running Code with Zero Headache</h3><p>Azure offers multiple ways to host and run applications, and <strong>App Services</strong> are among the most popular options:</p><h4>Web App</h4><p>A <strong>Web App</strong> lets you deploy and scale web applications quickly without worrying about underlying infrastructure.</p><ul><li><strong>Languages supported:</strong> .NET, Java, Python, PHP, Node.js, Ruby</li><li><strong>Features include:</strong> Auto-scaling, load balancing, custom domains, SSL, CI/CD integrations</li><li><strong>Use case:</strong> Hosting dynamic websites, RESTful APIs, or eCommerce portals</li></ul><p>🧠 <em>“You upload your code, Azure takes care of the rest.”</em><br> It’s like PaaS magic.</p><h4>Function App</h4><p><strong>Function Apps</strong> fall under <strong>Azure Functions</strong>, enabling you to run small pieces of code (functions) <strong>triggered by events</strong>.</p><ul><li><strong>Serverless</strong> — No infrastructure management, pay-per-execution</li><li><strong>Triggers:</strong> HTTP requests, queues, timers, database changes</li><li><strong>Use case:</strong> Auto-resizing images on upload, sending notifications, data processing jobs</li></ul><p>🧠 <em>“Write code that reacts to events — without worrying about the servers.”</em></p><h4>Logic App</h4><p><strong>Logic Apps</strong> help you <strong>build automated workflows</strong> with minimal or no code using a drag-and-drop interface.</p><ul><li><strong>Connectors available:</strong> Outlook, Salesforce, Twitter, Azure SQL, SharePoint, SAP, and hundreds more</li><li><strong>Ideal for:</strong> Business process automation, integrations, and enterprise workflows</li><li><strong>Example:</strong> “When a new email arrives, save attachment to OneDrive and send an SMS alert.”</li></ul><p>🧠 <em>“Enterprise-grade IFTTT (If This Then That) meets visual designer.”</em></p><h3>📦 Azure Containers: Pre-Packaged Simplicity</h3><p>Containers are <strong>lightweight, portable units</strong> of software that bundle everything your app needs to run: code, runtime, dependencies, and config files.</p><p>With <strong>Azure Container Instances</strong> and <strong>Azure Kubernetes Service (AKS)</strong>, you can:</p><ul><li><strong>Run containers in seconds</strong> without managing VMs</li><li><strong>Ensure consistency</strong> across development, testing, and production</li><li><strong>Scale effortlessly</strong> for microservices or modern app architectures</li></ul><p>🧠 <em>“If it works in dev, it’ll work in prod. No more ‘it works on my machine’ nightmares.”</em></p><h3>🔐 The Shared Responsibility Model</h3><p>Security in the cloud is a <strong>shared duty</strong> between Azure and you, the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsekyqnyyH62r2D-ITRsfQ.png" /></figure><p>🛡️ Example: Azure ensures the underlying VM host is secure, but you’re responsible for setting up firewalls, installing patches, and managing user access on the VM.</p><h3>🌍 Cloud Deployment Models</h3><p>Azure supports multiple cloud deployment models — each with its own use cases and trade-offs.</p><h3>☁️ Public Cloud</h3><p>Resources are owned and operated by a third-party cloud provider and delivered over the internet.</p><ul><li><strong>Scalable &amp; cost-effective</strong></li><li><strong>Ideal for:</strong> Startups, SaaS products, non-sensitive workloads</li></ul><h3>🏢 Private Cloud</h3><p>Resources are used exclusively by a single organization.</p><ul><li><strong>Hosted on-prem or by a third-party</strong></li><li><strong>High security and control</strong></li><li><strong>Ideal for:</strong> Financial institutions, healthcare, government</li></ul><h3>🔀 Hybrid Cloud</h3><p>Combines public and private clouds, allowing data and applications to move between them.</p><ul><li><strong>Flexibility for diverse workloads</strong></li><li><strong>Best of both worlds</strong></li><li><strong>Ideal for:</strong> Legacy systems, data sovereignty, compliance scenarios</li></ul><h3>⚠️ Challenges in Cloud Computing</h3><p>Despite its benefits, cloud computing does come with its own set of hurdles:</p><h4>Cost Predictability</h4><ul><li>Billing is based on <strong>usage</strong> (e.g., per second/hour/month)</li><li>Leaving a VM or database running when not in use = wasted cost</li><li>Unused resources = surprise bill</li></ul><h4>Complexity in Pricing</h4><ul><li>Each service has its own pricing metrics: storage per GB, compute per second, network usage, etc.</li><li>Without good governance, costs can spiral quickly</li></ul><h3>🧾 How You’re Billed</h3><p>Azure’s pay-as-you-go model means you’re billed based on <strong>consumption</strong>:</p><ul><li><strong>Compute:</strong> Per minute/second (VMs, Functions, App Services)</li><li><strong>Storage:</strong> Per GB stored and read/write operations</li><li><strong>Networking:</strong> Based on outbound data transfer</li><li><strong>Operations:</strong> Each read/write/query in Cosmos DB or Event Hub can be billed</li></ul><p>🔍 <strong>Pro Tip:</strong> Use the <a href="https://azure.microsoft.com/en-us/pricing/calculator/"><strong>Azure Pricing Calculator</strong></a> to estimate your monthly cost <strong>before deploying</strong>.</p><h3>✅ Wrapping Up Part 1</h3><p>We’ve just laid the foundation for understanding <strong>Azure and the world of cloud computing</strong>. Here’s what we’ve covered:</p><ul><li>What cloud computing is (and why it matters)</li><li>Core Azure App Services: Web App, Function App, and Logic App</li><li>Containers and their benefits</li><li>The Shared Responsibility Model</li><li>Deployment models: Public, Private, Hybrid</li><li>Key pricing considerations and challenges</li></ul><h3>🧭 What’s Next? (Coming in Part 2…)</h3><p>In <strong>Part 2</strong>, we’ll cover the <strong>core benefits of cloud computing</strong>:</p><ul><li><strong>High availability</strong></li><li><strong>Scalability &amp; Elasticity</strong></li><li><strong>Fault tolerance &amp; Disaster recovery</strong></li><li><strong>Governance, compliance, and identity management</strong></li><li>And how <strong>Azure delivers</strong> on all of them.</li></ul><h3>🙌 Final Thoughts</h3><p>Cloud computing has completely transformed the way we build, deploy, and scale applications. Azure provides the tools, platforms, and services to help businesses innovate faster and more securely than ever before. But like every powerful tool, understanding the fundamentals is key.</p><p>Whether you’re prepping for the AZ-900 or just exploring the cloud, mastering these basics will help you build a strong foundation for the road ahead.</p><p><strong>Follow this series for more deep dives, simplified breakdowns, and real-world tips to crush your AZ-900 journey and beyond.</strong> ☁️🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dbd0552a5bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Service Bus: A Comprehensive Guide]]></title>
            <link>https://medium.com/@halfdeb/azure-service-bus-a-comprehensive-guide-9e01fba7967b?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e01fba7967b</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 06:40:12 GMT</pubDate>
            <atom:updated>2024-10-11T06:40:12.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxCmphUS5Ff5j8y2k0Aucg.png" /></figure><h3>Azure Service Bus: Introduction</h3><p>Azure Service Bus is a cloud-based messaging service from Microsoft Azure designed for secure, reliable, and asynchronous communication between various applications and services. It supports seamless integration across cloud-based, on-premises, and hybrid environments, enabling developers to build decoupled, scalable, and resilient systems. Service Bus is ideal for applications that require advanced messaging capabilities such as load balancing, high availability, and fault tolerance.</p><p>Supporting multiple messaging protocols and standards, Azure Service Bus is highly adaptable for various scenarios. It is particularly suited for systems that benefit from asynchronous communication without tight coupling, such as microservices architectures, distributed systems, and IoT applications.</p><h3><strong>Key Characteristics of Azure Service Bus</strong></h3><p><strong>Reliable Asynchronous Messaging</strong>:<br>Service Bus supports asynchronous messaging, allowing it to store messages temporarily when a receiving application is not immediately available. This ensures that messages are not lost, maintaining high reliability even during network interruptions or high traffic. Messages are stored across multiple Azure data centers, offering high durability and availability.</p><p><strong>Advanced Messaging Capabilities</strong>:</p><ul><li><strong>First-in-First-Out (FIFO)</strong>: Messages are processed in the order they arrive, which is crucial for workflows that require sequential processing.</li><li><strong>Batching and Sessions</strong>: Service Bus supports message batching, which improves efficiency and reduces overhead. Sessions enable stateful processing, allowing messages with the same session ID to be processed together.</li><li><strong>Transactions</strong>: Service Bus supports transactional operations, which means that multiple actions can be executed as a single unit. In case of an error, all operations can be rolled back, preserving data integrity.</li><li><strong>Dead-Lettering</strong>: Service Bus automatically moves undeliverable messages to a dead-letter queue, allowing for separate inspection and handling of these messages, which aids in error management.</li><li><strong>Duplicate Detection</strong>: This feature identifies and ignores duplicate messages within a specified time frame, ensuring idempotent message delivery.</li></ul><p><strong>Message Delivery Guarantees</strong>:</p><ul><li><strong>At Least Once Delivery</strong>: Service Bus guarantees that each message is delivered at least once, even in the presence of transient errors. This may occasionally result in duplicate messages but ensures that no messages are lost.</li><li><strong>Optional Ordered Delivery</strong>: Although FIFO is provided by default, unordered delivery can be configured based on specific application requirements, offering flexibility.</li></ul><h3><strong>Core Components of Azure Service Bus</strong></h3><h4><strong>Queues</strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LuElYKgJU8TI7ZUy" /></figure><p>Service Bus queues reliable, one-to-one messaging, storing messages until the reciever is ready to process them. This means that senders and reciever is ready to process them. This means that senders and receivers do not need to be online simultaneously. Queues also support message locking, preventing multiple receivers from processing the same message locking, preventing multiple receivers from processing the same message concurrently. Once a message is locked, it cannot be accessed by another receiver until it is processed or the lock expires.</p><h4><strong>Topics and Subscriptions</strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9qjF3HpLH-dELJm" /></figure><ul><li><strong>Topics</strong>: Service Bus topics enable one-to-many messaging, allowing multiple subscribers to receive messages on the same topic, making them suitable for broadcast scenarios.</li><li><strong>Subscriptions</strong>: Each topic can have multiple subscriptions, which function as virtual queues. When a message is sent to a topic, it is duplicated across all subscriptions. Subscriptions can have filters to deliver only relevant messages to each subscriber, allowing for complex and tailored messaging workflows.</li></ul><h3>Understanding Shared Access Policies in Azure Service Bus</h3><p>Shared Access Policies allow for the creation of access permissions for different users or applications. By defining policies with specific rights, you can control which actions are allowed on queues, topics, or the namespace itself, enhancing both security and flexibility.</p><ul><li><strong>Role-Based Access</strong>: Policies enable role-based access, assigning permissions based on the role associated with each policy.</li><li><strong>Granular Permission Control</strong>: Permissions can be set at the namespace level or for specific queues or topics, allowing precise control for complex systems.</li></ul><h4><strong>Access Rights</strong>:</h4><p>Three primary permissions are supported:</p><ul><li><strong>Send</strong>: Grants permission to send messages.</li><li><strong>Listen</strong>: Grants permission to receive messages.</li><li><strong>Manage</strong>: Allows full control over the resource, including configuration and deletion.</li></ul><p>Each policy generates a unique connection string for secure authentication and access, with both primary and secondary strings provided for added security and ease of key rotation.</p><h3><strong>Operations on Messages in Azure Service Bus</strong></h3><ul><li><strong>Complete</strong>: Marks a message as processed, removing it from the queue or subscription.</li><li><strong>Abandon</strong>: Releases a message back to the queue if it cannot be processed, making it available for re-processing.</li><li><strong>Defer</strong>: Temporarily sets aside a message, allowing for prioritized handling of other messages.</li><li><strong>Dead-letter</strong>: Moves a problematic message to a dead-letter queue for analysis and potential reprocessing.</li></ul><h3><strong>Locks in Azure Service Bus</strong></h3><p>Message locking is a core feature that ensures reliable message processing. It temporarily claims a message while it is being processed, preventing simultaneous access by multiple receivers.</p><ul><li><strong>Peek-Lock Mode</strong>: The recommended mode where messages are locked until processed or the lock expires. After processing, the receiver calls Complete. If unable to process, it can call Abandon or Defer, or allow the lock to expire.</li><li><strong>Receive and Delete Mode</strong>: This mode immediately removes messages from the queue upon receipt, with no locking. It is suitable for scenarios where occasional message loss is acceptable.</li></ul><p>In Peek-Lock mode, the lock can be renewed if additional processing time is needed, with a default lock duration of 30 seconds (configurable up to 5 minutes).</p><h3>Dead-Letter Queue (DLQ)</h3><p>The DLQ stores messages that exceed the maximum delivery attempts or are explicitly dead-lettered by the receiver. Messages in the DLQ can be inspected, modified, or redirected back to the main queue, providing a mechanism to manage problematic messages and prevent system issues.</p><h3>Conclusion</h3><p>In conclusion, Azure Service Bus is a versatile and robust messaging platform that supports reliable, scalable, and asynchronous communication across distributed systems. With advanced features like dead-lettering, duplicate detection, and transactional support, it enables developers to build resilient applications that can handle complex messaging requirements. Its flexibility in message delivery and access control further ensures that Azure Service Bus can be tailored to meet diverse business needs, making it an essential tool for modern, decoupled architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e01fba7967b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Variational Autoencoders (VAEs)]]></title>
            <link>https://medium.com/@halfdeb/understanding-variational-autoencoders-vaes-617a477879b5?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/617a477879b5</guid>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genarative-ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 14:06:51 GMT</pubDate>
            <atom:updated>2024-10-04T14:06:51.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*778AnslsLVoQT7pENs2QYg.png" /></figure><h3>Introduction to Variational Autoencoders (VAEs)</h3><h4>What are VAEs?</h4><p>Variational Autoencoders (VAEs) are a type of generative model used in machine learning and statistics to generate new data samples similar to those in a given dataset. They are particularly effective in tasks such as image generation, text synthesis, and more. VAEs combine principles from neural networks and Bayesian inference, enabling them to learn complex data distributions.</p><h4>The Basics of Autoencoders</h4><p>Before diving into VAEs, it’s essential to understand the concept of autoencoders. An autoencoder is a type of neural network trained to replicate its input. It consists of two main components:</p><ul><li><strong>Encoder</strong>: Compresses the input data into a lower-dimensional representation, often referred to as the “latent space.”</li><li><strong>Decoder</strong>: Reconstructs the original input data from the compressed representation.</li></ul><p>The objective of an autoencoder is to minimize the difference between the input and the output, typically measured using a loss function like Mean Squared Error.</p><h4>What Makes VAEs Different?</h4><p>While traditional autoencoders simply compress data, VAEs take a probabilistic approach. Instead of learning a fixed representation, they learn a distribution over the latent space. This allows VAEs to generate new data samples by sampling from this learned distribution.</p><h3>How Do VAEs Work?</h3><h4>The Encoder and Decoder in VAEs</h4><p><strong>Encoder</strong>: In a VAE, the encoder outputs the parameters of a probability distribution, typically a Gaussian (normal) distribution. Specifically, for each input data point, the encoder produces:</p><ul><li><strong>Mean (μ)</strong>: The center of the distribution.</li><li><strong>Variance (σ²)</strong>: A measure of how spread out the distribution is.</li></ul><p><strong>Latent Space Sampling</strong>: To generate a representation from the learned distribution, we use a technique called the “reparameterization trick.” Instead of directly sampling from the Gaussian distribution, we first sample from a standard normal distribution (mean 0, variance 1) and then transform it using the parameters from the encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*IlhnrrEU3mdLqQXgdLBdkQ.png" /></figure><p>Where <strong>ϵ</strong> is a random sample from a standard normal distribution.</p><ul><li><strong>Decoder</strong>: The decoder takes the sampled latent vector <strong>z</strong> and attempts to reconstruct the original input data. It produces parameters for the output distribution, which is also typically a Gaussian distribution.</li></ul><h3>The Loss Function</h3><p>The objective of training a VAE is to minimize a loss function that consists of two components:</p><ul><li><strong>Reconstruction Loss</strong>: This measures how well the VAE can reconstruct the original input from the latent representation. It quantifies the difference between the input <strong>x</strong> and the reconstructed output <strong>x’</strong>. A common choice for this is the binary cross-entropy loss.</li><li><strong>KL Divergence</strong>: This term measures how much the learned distribution diverges from a prior distribution, typically a standard normal distribution. KL divergence ensures that the learned latent space is regularized and encourages smoothness:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*2btvxvV29r8e9KcwozMaHQ.png" /></figure><p>Where <strong>q(z∣x)</strong> is the learned distribution and <strong>p(z)</strong> is the prior.</p><h4>Overall Loss Function</h4><p>The total loss function <strong>L</strong> for a VAE can be expressed as the sum of the reconstruction loss and the KL divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*seAW9Q6lBsiOxuCQL_wYyw.png" /></figure><p>Where:</p><ul><li>The reconstruction loss measures how accurately the model can reconstruct the input from the latent space.</li><li>The KL divergence term regularizes the latent space by penalizing the deviation from the prior distribution.</li></ul><h3>Training the VAE</h3><p>Training a VAE involves using backpropagation to minimize the total loss function over many iterations. During this process, the encoder learns to produce useful latent representations, while the decoder learns to accurately reconstruct the input.</p><h4>Applications of VAEs</h4><ul><li><strong>Image Generation</strong>: One of the most exciting applications of VAEs is generating new images. By sampling from the latent space, we can create images that are similar to those in the training set but not exact replicas, leading to novel artwork or designs.</li><li><strong>Data Imputation</strong>: VAEs are also useful for filling in missing data. By leveraging the learned distributions, they can predict and generate plausible values for absent entries.</li><li><strong>Anomaly Detection</strong>: In tasks like fraud detection, VAEs can identify outliers by measuring how well they reconstruct known data points. High reconstruction errors might indicate anomalous behavior.</li><li><strong>Semi-Supervised Learning</strong>: VAEs can enhance classification tasks, especially when labeled data is scarce. By generating data in the latent space, they can help improve the performance of classifiers.</li><li><strong>Reinforcement Learning</strong>: In this domain, VAEs can model state representations, enabling agents to better understand their environment and make informed decisions.</li></ul><h3>Mathematical Foundations</h3><h4>Latent Space</h4><p>Imagine you have a big box of LEGO bricks. Each LEGO brick represents a piece of information — like an image, a sound, or any other type of data. A Variational Autoencoder (VAE) is like a special machine that learns to organize these LEGO bricks into a smaller, more manageable box called the latent space.</p><p>The latent space is like a hidden room where we keep all the important LEGO bricks sorted neatly. Instead of having thousands of bricks scattered everywhere, we can represent them using just a few key features, like color, size, and shape. When we train a VAE, it learns to map complex objects (like images) into this simplified latent space. Each point in this space represents a unique combination of features that make up the data.</p><h4>Latent Space Representation</h4><ul><li>In a VAE, we have an encoder that transforms our input data x into a latent variable z. This can be represented as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*ul5SzNg2Cmrvmu1c-YFy2w.png" /></figure><ul><li>Think of this as picking a specific LEGO brick from a well-organized shelf, each z is a point representing important features of x.</li></ul><h4>KL Divergence</h4><ul><li>To ensure our latent space is well-organized, we introduce the concept of KL Divergence. Imagine we have a party where we need to dress up in specific costumes. If everyone shows up dressed however, they want, it can get chaotic! KL Divergence measures how one probability distribution (the way our LEGO bricks are arranged) differs from a preferred distribution.</li><li>In VAEs, we want our learned distribution q(z|x) (how we arrange our LEGO bricks) to be close to a prior distribution p(z) (the preferred style, like a standard normal distribution). The formula is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*WG0Jixii5mVtYt6HUAgZvA.png" /></figure><ul><li>This ensures that the way we organize our LEGO bricks doesn’t stay too far from the expected style, keeping our latent space tidy.</li></ul><h4>Reparameterization Trick</h4><ul><li>Now, let’s introduce the reparameterization trick-a clever method that helps us sample smoothly from our latent space without getting tangled up. Instead of sampling directly from q(z|x), we express z as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*IlhnrrEU3mdLqQXgdLBdkQ.png" /></figure><ul><li>Here, μ and σ are the mean and standard deviation of our latent variable as determined by the encoder, and ϵ is noise sampled from a standard normal distribution N(0,I).</li><li>Think of it as having a magical LEGO brick that can change its shape and size. You pull it, reshape it accordingly to the features you need, and still maintain its essential properties. This trick allows us to learn effectively while sampling from our organized space.</li></ul><h4>Decoding</h4><ul><li>The decoder takes our organized latent representation and reconstructs the original data:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*Kd2lm6dXZDGXZe9fpmaPDg.png" /></figure><ul><li>This means that for each point z (a specific arrangement of LEGO bricks), the decoder outputs a reconstructed version of data x’ (a new LEGO creation).</li></ul><h4>Loss Function</h4><p>TO train our VAE, we optimize a loss function that combines how well we reconstruct the data and how organized our latent space is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*vasunNBY-Qg-sVEbLGE64Q.png" /></figure><p>The first term measures the reconstruction quality (how well we build our new LEGO model), while the second tern ensures we stick to our costume guidelines (keeping the latent space neat).</p><h3>Building an Autoencoder with the MNIST Dataset</h3><p>In this section, we will walk through the process of building and training and autoencoder using the MNIST dataset, a classic dataset in the machine learning community. An autoencoder is a type of neural network used for unsupervised learning, specifically for dimensionality reduction or feature learning. The goal of the autoencoder is to learn a compressed representation of the input data and then reconstruct it as accurately as possible.</p><h4>STEP 1: Importing Required Libraries</h4><p>First, we need to import the necessary libraries. We will be using Keras, high-level neural networks API, along with NumPy for numerical computations and Matplotlib for visualization:</p><pre>from keras.layers import Input, Dense<br>from keras.models import Model<br>from keras.datasets import mnist<br><br>import numpy as np<br><br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><h4>STEP 2: Data Exploration</h4><p>Next, we load the MNIST dataset, which consists of images of handwritten digits. The dataset is split into training and testing sets. We also examine the structure of the data:</p><pre>#Load our MNIST dataset.<br>(XTrain, YTrain), (XTest, YTest) = mnist.load_data()<br><br>print(&#39;XTrain class = &#39;,type(XTrain))<br>print(&#39;YTrain class = &#39;,type(YTrain))<br><br># shape of our dataset.<br>print(&#39;XTrain shape = &#39;,XTrain.shape)<br>print(&#39;XTest shape = &#39;,XTest.shape)<br>print(&#39;YTrain shape = &#39;,YTrain.shape)<br>print(&#39;YTest shape = &#39;,YTest.shape)<br># Number of distinct values of our MNIST target<br>print(&#39;YTrain values = &#39;,np.unique(YTrain))<br>print(&#39;YTest values = &#39;,np.unique(YTest))<br># Distribution of classes in our dataset.<br>unique, counts = np.unique(YTrain, return_counts=True)<br>print(&#39;YTrain distribution = &#39;,dict(zip(unique, counts)))<br>unique, counts = np.unique(YTest, return_counts=True)<br>print(&#39;YTest distribution = &#39;,dict(zip(unique, counts)))</pre><ul><li><strong>Shapes of the Dataset:</strong> We check the dimensions of the training and testing datasets. The training set contains 60,000 images, and the test set contains 10,000 images, each of size 28x28 pixels.</li><li><strong>Class Distribution:</strong> We analyze the distribution of classes (digits 0–9) in both training and testing sets to ensure that the dataset is balanced.</li></ul><h4>STEP 3: Data Preprocessing</h4><p>Before training our autoencoder, we normalize the pixel values of the images to a range of [0, 1] and reshape them into a flat vector of 784 pixels (28x28):</p><pre># Data normalization.<br>XTrain = XTrain.astype(&#39;float32&#39;) / 255<br>XTest = XTest.astype(&#39;float32&#39;) / 255<br># data reshapping.<br>XTrain = XTrain.reshape((len(XTrain), np.prod(XTrain.shape[1:])))<br>XTest = XTest.reshape((len(XTest), np.prod(XTest.shape[1:])))<br><br>print (XTrain.shape)<br>print (XTest.shape)</pre><h4>STEP 4: Building the Autoencoder</h4><p>We construct the autoencoder model, which consists of an encoder and a decoder. The encoder reduces the dimensionality of the input, while the decoder reconstructs the input from this compressed representation:</p><pre>nputModel = Input(shape=(784,))<br>EncodedLayer = Dense(32, activation=&#39;relu&#39;)(InputModel)<br>DecodedLayer = Dense(784, activation=&#39;sigmoid&#39;)(EncodedLayer)<br><br>AutoencoderModel = Model(InputModel, DecodedLayer)<br># we can summarize our model.<br>AutoencoderModel.summary()</pre><ul><li>Input Layer: Accepts vectors of size 784.</li><li>Encoded Layer: A dense layer with 32 neurons, applying ReLU activation.</li><li>Decoded Layer: A dense layer that reconstructs the input back to 784 dimensions used sigmoid activation.</li></ul><h4>STEP 5: Model Compilation and Training</h4><p>We compile the model using the Adadelta optimizer and binary crossentropy loss function, which is suitable for our binary output:</p><pre># Let&#39;s train the model using adadelta optimizer<br>AutoencoderModel.compile(optimizer=&#39;adadelta&#39;, loss=&#39;binary_crossentropy&#39;)<br><br>history = AutoencoderModel.fit(XTrain, XTrain,<br>                    batch_size=256,<br>                    epochs=100,<br>                    shuffle=True,<br>                    validation_data=(XTest, XTest))<br># Make prediction to decode the digits<br>DecodedDigits = AutoencoderModel.predict(XTest)</pre><ul><li>Training: The model is trained for 100 epochs, using 256 samples per batch.</li></ul><h4>STEP 6: Model Evaluation</h4><p>After training, we can evaluate the model’s performance by plotting the training and validation loss:</p><pre>def plotmodelhistory(history): <br>    plt.plot(history.history[&#39;loss&#39;])<br>    plt.plot(history.history[&#39;val_loss&#39;])<br>    plt.title(&#39;Autoencoder Model loss&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>    plt.xlabel(&#39;Epoch&#39;)<br>    plt.legend([&#39;Train&#39;, &#39;Test&#39;], loc=&#39;upper left&#39;)<br>    plt.show()<br><br># list all data in history<br>print(history.history.keys())<br># visualization of the loss minimization during the training process<br>plotmodelhistory(history)</pre><h4>STEP 7: Visualizing Results</h4><p>Finally, we visualize the original images alongside their reconstructed version to assess the performance of the autoencoder:</p><pre>n=5<br>plt.figure(figsize=(20, 4))<br>for i in range(n):<br>    ax = plt.subplot(2, n, i + 1)<br>    # input image<br>    plt.imshow(XTest[i+10].reshape(28, 28))<br>    plt.gray()<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)<br>    ax = plt.subplot(2, n, i + 1 + n)<br>    # Image decoded by our Auto-encoder<br>    plt.imshow(DecodedDigits[i+10].reshape(28, 28))<br>    plt.gray()<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)<br>plt.show()</pre><p>This allows us to visually assess how well our autoencoder has learned to reconstruct the original images from their compressed representations.</p><h3>Conclusion</h3><p>Variational Autoencoders (VAEs) represent a significant advancement in the field of generative models, bridging the gap between traditional autoencoders and probabilistic graphical models. By learning a distribution over the latent space rather than a fixed representation, VAEs enable the generation of new, high-quality data samples that mirror the underlying characteristics of the training dataset.</p><p>Through a combination of the encoder, which maps input data to a probabilistic latent space, and the decoder, which reconstructs the original input, VAEs provide a powerful framework for diverse applications. Their capacity to generate images, fill in missing data, detect anomalies, and enhance semi-supervised learning makes them invaluable tools in modern machine learning.</p><p>The foundational concepts of latent space, KL divergence, and the reparameterization trick allow VAEs to maintain a well-structured representation of the data, facilitating effective sampling and generation. The overall training process, driven by the optimization of a comprehensive loss function, ensures that VAEs balance reconstruction quality with the need for a regularized latent space.</p><p>The practical implementation using the MNIST dataset serves as a testament to the effectiveness of VAEs in learning meaningful representations and performing robust reconstructions. By leveraging the strengths of neural networks and probabilistic methods, VAEs open new avenues for exploration in generative modeling, contributing to advancements in fields such as computer vision, natural language processing, and beyond. As research in this area progresses, we can anticipate even more innovative applications and enhancements to the VAE framework, solidifying its role as a cornerstone of contemporary machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617a477879b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Web API: A Comprehensive Guideline]]></title>
            <link>https://medium.com/@halfdeb/asp-net-web-api-a-comprehensive-guideline-ec6a41d3aea3?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec6a41d3aea3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 13:38:35 GMT</pubDate>
            <atom:updated>2024-10-06T16:33:01.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faSb_dWv8cCXchhpH9vKtQ.png" /></figure><h3>Introduction to Web API</h3><p>Imagine you’ve built a website connected to a database, and now you need to create Android and iOS apps that connect to the same database. A common issue arises when each application has to implement its own logic to communicate with the database. This creates several challenges:</p><ul><li><strong>Duplicate logic</strong> for each platform.</li><li><strong>Error-prone code</strong> since business logic is scattered across applications.</li><li><strong>Direct database access</strong> isn’t allowed by some front-end frameworks.</li><li><strong>Maintenance</strong> becomes hard as you need to update logic in multiple places.</li></ul><p>To solve this, we introduce a <strong>Web API</strong> project between the database and applications. Rather than having apps directly access the database, they communicate with the Web API, which handles all the requests and interactions with the database.</p><p>For example, if you want to use Google Maps in your apps or on the website, you’d use the <strong>Google Maps API</strong> to get data. If you want to post data, an API lets you submit it to the provider. Similarly, you can use APIs to access cloud storage, submit updates, or delete data.</p><h4>Advantages of a Web API:</h4><ul><li><strong>Front-End Isolation</strong>: The front-end doesn’t directly interact with the database.</li><li><strong>Eliminate Redundant Logic</strong>: Write business logic once in the API instead of duplicating it across applications.</li><li><strong>Extend Functionality</strong>: Easily extend your applications through the API.</li><li><strong>Abstraction and Security</strong>: API abstracts the complexities of the backend, adding an additional layer of security.</li></ul><h3>What is ASP.NET Web API?</h3><p>ASP.NET Web API is a powerful framework that enables developers to build HTTP services, consumable by a wide range of clients, including web browsers, mobile applications, and desktop software. It is particularly suited for building RESTful services, which use the principles of REST (Representational State Transfer) to facilitate communication over the web through standard HTTP methods. This flexibility makes Web API an excellent choice for creating services that integrate seamlessly across various platforms and devices.</p><p>At its core, ASP.NET Web API is built on top of the ASP.NET framework, which offers a robust ecosystem of libraries, tools, and frameworks. With Web API, developers can create services capable of returning data in multiple formats, such as JSON or XML, depending on the client’s needs. This adaptability is crucial in today’s technology landscape, where different devices and applications may require varying data representations.</p><p>In essence, Web API acts as a bridge between different software systems, allowing them to communicate with each other in a standardized manner. This is achieved through HTTP requests directed at specific endpoints defined within your application. By adhering to RESTful principles, you can create APIs that are intuitive and easy to use, enhancing the developer experience and promoting broader adoption of your services.</p><h3>Key Concepts</h3><h4>HTTP Protocol</h4><p>HTTP (HyperText Transfer Protocol) is the foundation of data communication on the World Wide Web. It defines how messages are formatted and transmitted, and how web servers and browsers should respond to various commands. Every interaction with a web resource involves an HTTP request, which consists of a method (such as GET or POST), a URL (the resource being requested), headers (additional metadata), and sometimes a body (data sent with the request).</p><p>When you access a website, your browser sends an HTTP request to the server hosting that site. The server processes the request, interacts with any necessary databases or services, and returns an HTTP response. This response typically includes a status code indicating the result of the request, along with the requested data if applicable.</p><p>HTTP has evolved over the years, with versions like HTTP/1.1, HTTP/2, and the more recent HTTP/3, each improving performance, security, and the efficiency of data transfers.</p><h4>REST</h4><p>REST (Representational State Transfer) is an architectural style for designing network applications. It leverages a stateless communication protocol — most commonly HTTP — and defines a set of constraints that developers should follow to create scalable and maintainable web services. The key concepts of REST include:</p><ul><li><strong>Statelessness</strong>: Each request from a client contains all the information needed to process it, with no reliance on stored context on the server.</li><li><strong>Resource-Based</strong>: RESTful services revolve around resources, which are identified by URLs. Each resource can be manipulated using standard HTTP methods.</li><li><strong>Use of Standard HTTP Methods</strong>: RESTful services utilize standard HTTP methods like GET (retrieve data), POST (create data), PUT (update data), and DELETE (remove data). This standardization simplifies interaction between clients and the service.</li></ul><p>By adhering to these principles, your API becomes easier to understand, flexible, and scalable, enabling you to accommodate growth in both user base and features without major restructuring.</p><h4>API (Application Programming Interface)</h4><p>An API is a set of rules and protocols for building software applications. It defines the methods and data structures that developers can use to interact with a particular software component, whether it’s a web service, library, or operating system. In web development, an API specifies how different software components should communicate over the internet, enabling the exchange of data and functionality between applications.</p><p>For ASP.NET Web API, the focus is on building HTTP-based APIs that expose resources and operations to clients. These APIs serve various purposes, from simple data retrieval to executing complex business logic. Acting as intermediaries between the client and server, they facilitate communication and ensure that clients can efficiently access and manipulate the resources they need.</p><h4>Controllers</h4><p>In ASP.NET Web API, controllers are essential components responsible for handling incoming HTTP requests. Each controller is a class that inherits from ApiController and is typically organized around a specific resource, such as BooksController for handling book-related operations. Controllers contain action methods that correspond to different HTTP verbs (GET, POST, PUT, DELETE) and define how to process requests related to the resource.</p><p>When a request is made to the API, the routing system in ASP.NET Web API determines which controller and action method should handle the request, based on the URL and HTTP method. This separation of concerns results in cleaner code and easier maintenance, as each controller focuses on a specific set of operations.</p><p>For example, in a book API, the BooksController would include methods like GetAllBooks, GetBookById, AddBook, and DeleteBook. Each method maps directly to a specific action the API can perform, enabling clients to interact with the book resource seamlessly.</p><h4>Routes</h4><p><strong>Routing</strong> in ASP.NET Web API is the mechanism that maps incoming HTTP requests to the appropriate controller and action method. The routing system uses URL patterns defined in the application to determine how requests are handled. For example, a request to /api/books would be routed to the Get method of the BooksController, while a request to /api/books/1 would be routed to the Get(int id) method, where &quot;1&quot; is the ID of the requested book.</p><p>By default, ASP.NET Web API uses convention-based routing, where the URL structure follows a predefined pattern. However, developers can define custom routes to handle more complex scenarios. This flexibility allows for clean, meaningful URLs that enhance the usability and discoverability of your API.</p><p>Additionally, routes can include parameters, constraints, and defaults, enabling developers to create a robust routing configuration that accommodates various request patterns and requirements.</p><h4>Models</h4><p><strong>Models</strong> in ASP.NET Web API represent the data structures that your API will work with. They define the properties and data types corresponding to the resources exposed by your API. For instance, in a book API, a Book model could have properties like Id, Title, Author, and ISBN. These models are essential for serializing and describing data between the client and server.</p><p>Models can also include validation attributes to enforce rules regarding the data being submitted. For example, you could use attributes like [Required] to ensure that certain fields are present when creating a new book. This validation is performed automatically by the framework, helping to ensure that your API only processes valid data.</p><p>Defining models helps centralize your data structures, making it easier to manage changes and ensuring consistency across your API. It also facilitates documentation and improves the developer experience, as models provide a clear definition of the data your API expects and returns.</p><h3>Creating a Simple ASP.NET Web API Project</h3><p>Let’s walk through the steps to create a simple ASP.NET Web API project that manages a collection of books:</p><ol><li><strong>Open Visual Studio</strong>: Start by launching Visual Studio.</li><li><strong>Select Create a New Project</strong>: In the startup window, click on “Create a new project.”</li><li><strong>Choose Project Type</strong>: In the project template selection window, search for “ASP.NET Web Application,” select it, and then click Next.</li><li><strong>Configure Your Project</strong>: Name your project (e.g., BookAPI) and choose a suitable location on your file system. After that, click Create.</li><li><strong>Select a Template</strong>: In the next window, select the “API” template. This template is pre-configured for building Web APIs and includes the necessary components to get started quickly.</li><li><strong>Understanding the Project Structure</strong>: After the project is created, you will see a Solution Explorer with a typical structure that includes:</li></ol><ul><li><strong>Controllers</strong>: This folder contains your API controllers, where the request-handling logic is implemented.</li><li><strong>Models</strong>: You can create your data models here to represent the data structure.</li><li><strong>Startup.cs</strong>: This file is where your application is configured, including service registration and middleware setup.</li></ul><h4>Creating a Model</h4><p>Now that your project structure is in place, let’s create a simple model for a book:</p><ol><li><strong>Right-click on the Models Folder</strong>: In the Solution Explorer, right-click on the Models folder.</li><li><strong>Select Add &gt; Class</strong>: Choose to add a new class.</li><li><strong>Name it </strong><strong>Book.cs</strong>: This class will represent a book in the API.</li><li><strong>Define the Book Class</strong>: In the Book.cs file, define your class with properties that describe a book:</li></ol><pre>public class Book <br>{     <br>    public int Id { get; set; }  // Unique identifier for each book<br>    public string Title { get; set; }  // Title of the book<br>    public string Author { get; set; }  // Author of the book<br>    public string ISBN { get; set; } // ISBN number <br>}</pre><p>This model encapsulates the data structure of a book, which the API will use to serialize and deserialize JSON objects when communicating with clients.</p><h4>Creating a Controller</h4><p>Next, you’ll create a controller to handle requests related to the book data:</p><ol><li><strong>Right-click on the Controllers Folder</strong>: In the Solution Explorer, right-click on the Controllers folder.</li><li><strong>Select Add &gt; Controller</strong>: Choose to add a new controller.</li><li><strong>Choose API Controller — Empty</strong>: This option provides a base class from which you can build your controller.</li><li><strong>Name it </strong><strong>BooksController.cs</strong>: This controller will manage book-related operations.</li><li><strong>Implement the Controller Logic</strong>: In the BooksController.cs file, implement the necessary methods to handle HTTP requests:</li></ol><pre>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br><br>public class BooksController : ApiController<br>{<br>    // In-memory list of books<br>    private static List&lt;Book&gt; books = new List&lt;Book&gt;<br>    {<br>        new Book { Id = 1, Title = &quot;1984&quot;, Author = &quot;George Orwell&quot;, ISBN = &quot;123456789&quot; },<br>        new Book { Id = 2, Title = &quot;The Great Gatsby&quot;, Author = &quot;F. Scott Fitzgerald&quot;, ISBN = &quot;987654321&quot; }<br>    };<br><br>    // GET api/books<br>    public IEnumerable&lt;Book&gt; Get()<br>    {<br>        return books;  // Return the list of books<br>    }<br><br>    // GET api/books/1<br>    public IHttpActionResult Get(int id)<br>    {<br>        var book = books.FirstOrDefault(b =&gt; b.Id == id);<br>        if (book == null)<br>        {<br>            return NotFound();  // Return 404 if the book is not found<br>        }<br>        return Ok(book);  // Return the found book<br>    }<br><br>    // POST api/books<br>    public IHttpActionResult Post([FromBody] Book book)<br>    {<br>        if (book == null)<br>        {<br>            return BadRequest(&quot;Invalid data.&quot;);  // Return 400 if the data is invalid<br>        }<br>        book.Id = books.Max(b =&gt; b.Id) + 1;  // Assign a new ID<br>        books.Add(book);  // Add the book to the list<br>        return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = book.Id }, book);  // Return 201 with the new book<br>    }<br><br>    // DELETE api/books/1<br>    public IHttpActionResult Delete(int id)<br>    {<br>        var book = books.FirstOrDefault(b =&gt; b.Id == id);<br>        if (book == null)<br>        {<br>            return NotFound();  // Return 404 if the book is not found<br>        }<br>        books.Remove(book);  // Remove the book from the list<br>        return StatusCode(System.Net.HttpStatusCode.NoContent);  // Return 204<br>    }<br>}</pre><p>In this code:</p><ul><li><strong>Get()</strong>: This method retrieves all books from the in-memory list.</li><li><strong>Get(int id)</strong>: This method retrieves a specific book by its ID and returns a 404 if not found.</li><li><strong>Post(Book book)</strong>: This method adds a new book to the list and returns a 201 status code upon successful creation.</li><li><strong>Delete(int id)</strong>: This method removes a book by its ID, returning a 204 status code if successful.</li></ul><h4>Understanding the Controller Code</h4><p>To understand how the controller functions:</p><ul><li><strong>Get()</strong>: This method allows clients to retrieve the entire list of books. When a GET request is made to /api/books, this method is invoked, returning all the books as an IEnumerable&lt;Book&gt;.</li><li><strong>Get(int id)</strong>: This method enables clients to request a specific book using its ID. It checks if the book exists in the list and returns it if found; otherwise, it responds with a 404 Not Found status.</li><li><strong>Post(Book book)</strong>: This method processes a POST request to add a new book to the collection. It first validates that the book object is not null, assigns a unique ID, adds it to the list, and returns a 201 Created status along with the new book in the response.</li><li><strong>Delete(int id)</strong>: This method handles DELETE requests to remove a book by its ID. It verifies if the book exists, and if so, removes it from the list, returning a 204 No Content status to indicate success.</li></ul><h4>Running Your API</h4><p>To test your newly created API:</p><ol><li><strong>Press F5 or Click Start</strong>: Run your project in Visual Studio. This will launch the built-in web server.</li><li><strong>Use Postman or Your Web Browser</strong>: You can now send requests to your API endpoints:</li></ol><ul><li><strong>GET all books</strong>: Use GET http://localhost:[port]/api/books to retrieve all books.</li><li><strong>GET a specific book</strong>: Use GET http://localhost:[port]/api/books/1 to get the book with ID 1.</li><li><strong>POST a new book</strong>: Use POST http://localhost:[port]/api/books with a JSON body representing the book to add a new book.</li><li><strong>DELETE a book</strong>: Use DELETE http://localhost:[port]/api/books/1 to delete the book with ID 1.</li></ul><p>These requests can be sent through Postman, where you can easily set the HTTP method and specify the URL, headers, and body as needed. This interaction allows you to test the API functionality and ensure it behaves as expected.</p><h3>What is Entity Framework?</h3><p>Entity Framework (EF) is an open-source Object-Relational Mapper (ORM) developed by Microsoft that enables .NET developers to work with relational data in a more intuitive and efficient manner. Instead of writing complex SQL queries to interact with a database, EF allows developers to manipulate data using C# objects, significantly reducing the amount of code and complexity involved in data operations. This abstraction layer translates the object-oriented programming model into a relational database schema, facilitating seamless interaction between the two paradigms.</p><p>At its core, EF serves as a bridge between your C# classes (often referred to as entities) and the database tables. Each entity corresponds to a table in the database, while the properties of these entities represent the columns in those tables. EF takes care of creating the SQL commands required to perform operations such as inserting, updating, and deleting records, thereby streamlining the development process.</p><p>The benefits of using Entity Framework are numerous. Firstly, it promotes a more maintainable codebase since developers can work with strongly typed objects rather than raw SQL strings. This leads to fewer runtime errors and easier refactoring as your data models evolve. Secondly, EF supports LINQ (Language Integrated Query), allowing developers to write type-safe queries directly in C#, which can be easier to read and write compared to traditional SQL. Finally, EF offers built-in mechanisms for handling relationships between entities, such as one-to-many and many-to-many, further simplifying the development of complex data models.</p><h3>Key Concepts of Entity Framework</h3><h4>DbContext</h4><p>The DbContext class is a fundamental component of Entity Framework, acting as a session between your application and the database. It provides the API for interacting with the data, managing entity objects, and handling changes to the data. When you create a DbContext class, you typically define DbSet properties that represent each table in the database.</p><p>For example, if you have a Book entity, you would create a DbSet&lt;Book&gt; property within your DbContext subclass. This property allows you to query and save instances of the Book entity to the database. The DbContext is also responsible for tracking changes made to entries during runtime. When you modify an entity and call the SaveChanges method, EF automatically generates the necessary SQL commands to persist those changes in the database.</p><p>Understanding the lifecycle of a DbContext is crucial. Typically, a DbContext instance is created per request in a web application, ensuring that changes are tracked for that particular operation. Once the request is complete, the DbContext is disposed of, releasing any resources it was using. It’s important to manage the lifetime of your DbContext carefully to avoid performance issues and memory leaks, especially in scenarios with high concurrency.</p><h4>DbSet</h4><p>The DbSet&lt;T&gt; class represents a collection of entities of a specific type, corresponding to a table in the database. For instance, if you define a DbSet&lt;Book&gt;, it represents the Books table, where instances of Book correspond to rows in that table.</p><p>You can perform various operations on a DbSet, such as querying, adding, or removing entities. For example, you might use the Add method to insert a new book into the database or the Remove method to delete an existing book. The DbSet also provides methods for querying, which can be combined with LINQ for more complex queries. For instance, you might write a query to find all books authored by a specific author or to paginate results based on certain criteria.</p><p>The power of DbSet lies in its ability to leverage the capabilities of LINQ, enabling you to construct expressive and concise queries. EF translates these LINQ queries into SQL commands, allowing you to interact with the database using familiar C# syntax.</p><h4>Entity</h4><p>An entity in Entity Framework is a class that represents a table in your database. Each property of the entity class corresponds to a column in that table, and each instance of the class represents a row. For example, a Book class might have properties such as Id, Title, Author, and ISBN, each representing a column in the Books table.</p><p>Entities can also include navigation properties that define relationships between different entities. For instance, if you have an Author class, you could include a navigation property in the Book class to represent the relationship between books and their authors. This allows EF to manage and enforce referential integrity between related entities, simplifying the complexity of managing relationships in a relational database.</p><p>When working with entities, you can also utilize data annotations or the Fluent API to configure additional behaviors, such as validation rules, relationships, and database-specific features. This configuration ensures that entities behave as expected when persisted to the database, allowing for seamless integration between your application and the data layer.</p><h4>Migration</h4><p>Database migrations in Entity Framework are a powerful feature that allows you to evolve your database schema over time as your model changes. When you make modifications to your entity classes — such as adding a new property or creating a new entity — you can create a migration that captures these changes and updates the database schema accordingly.</p><p>Migrations work by generating a series of code files that describe how to apply or revert changes to the database. Each migration includes an Up method that defines the operations required to apply the migration and a Down method that outlines how to revert those operations. This approach allows you to maintain version control over your database schema, making it easier to track changes and collaborate with other developers.</p><p>To create a migration, you typically use the Package Manager Console or the .NET CLI to run commands that scaffold a new migration based on the changes in your model. Once the migration is generated, you can review the code and apply it to the database with another command. This process ensures that your database remains in sync with your application’s data model, facilitating a smooth development experience.</p><h3>Setting Up Entity Framework in Your Project</h3><h4>Install Entity Framework</h4><p>To begin using Entity Framework in your ASP.NET Web API project, the first step is to install the Entity Framework package via NuGet. This process simplifies the integration of Entity Framework into your application by automatically downloading and configuring all necessary dependencies.</p><ol><li><strong>Open Visual Studio</strong>: Launch Visual Studio and load your ASP.NET Web API project.</li><li><strong>Manage NuGet Packages</strong>: Right-click on your project in the Solution Explorer and select <strong>“Manage NuGet Packages.”</strong></li><li><strong>Search for Entity Framework</strong>: In the NuGet Package Manager, type “EntityFramework” in the search box. When it appears in the results, click <strong>“Install”</strong> to add it to your project.</li></ol><p>Once installed, Entity Framework will be integrated into your project, allowing you to start defining your data models and context classes.</p><h4>Create a Database Context</h4><p>With Entity Framework installed, the next step is to create a DbContext class that will manage the database operations for your application.</p><ol><li><strong>Add a New Class</strong>: Right-click on the <strong>Models</strong> folder in your project and select <strong>“Add &gt; Class.”</strong> Name the class BookContext.cs.</li><li><strong>Define the Context Class</strong>: In this file, inherit from DbContext and define a DbSet&lt;Book&gt; property to represent the Books table.</li></ol><p>Here’s a basic implementation of the BookContext class:</p><pre>using System.Data.Entity;<br><br>public class BookContext : DbContext<br>{<br>    public BookContext() : base(&quot;name=BookDB&quot;) // Connection string name<br>    {<br>    }<br><br>    public DbSet&lt;Book&gt; Books { get; set; } // Represents the Books table<br>}</pre><p>In this code, the constructor calls the base class with the name of the connection string, which will be configured in the next step. The Books property serves as the access point for interacting with the Books table, allowing you to perform CRUD operations on book entities.</p><h4>Configuring the Connection String</h4><p>After defining your context, you need to set up a connection string in the <strong>Web.config</strong> file. The connection string specifies how to connect to the database, including the server name, database name, and security credentials.</p><ol><li><strong>Open Web.config</strong>: Locate the <strong>Web.config</strong> file in your project.</li><li><strong>Add Connection String</strong>: Inside the &lt;configuration&gt; section, add the following:</li></ol><pre>&lt;configuration&gt;<br>  &lt;connectionStrings&gt;<br>    &lt;add name=&quot;BookContext&quot;<br>         connectionString=&quot;Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=BookDB;Integrated Security=True&quot;<br>         providerName=&quot;System.Data.SqlClient&quot; /&gt;<br>  &lt;/connectionStrings&gt;<br>&lt;/configuration&gt;</pre><p>This connection string specifies that you will be using a local database (LocalDb), creating a database named <strong>BookDB</strong>. The Integrated Security=True setting indicates that Windows Authentication will be used to connect to the SQL Server instance.</p><h3>Creating Migrations</h3><p>Migrations are essential for evolving your database schema in tandem with your application’s model. Here’s how to enable and create migrations in your project:</p><h4>Step 1: Enable Migrations</h4><p>To enable migrations, you need to use the Package Manager Console in Visual Studio.</p><ol><li>Open <strong>Visual Studio</strong> and load your project.</li></ol><p>2. Go to <strong>Tools</strong> &gt; <strong>NuGet Package Manager</strong> &gt; <strong>Package Manager Console</strong>.</p><p>3. In the console, type the following command and press Enter:</p><pre>Enable-Migrations</pre><p>This command creates a <strong>Migrations</strong> folder in your project, which contains a configuration file where you can customize migration settings.</p><h4>Step 2: Add a Migration</h4><p>Once migrations are enabled, you can add a migration whenever you change your entity model. Here’s how to modify your model and create a corresponding migration:</p><ul><li><strong>Modify Your Model</strong>: For instance, if you decide to add a new property to your Book class, such as PublishedDate, update the class accordingly:</li></ul><pre>public class Book<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; }<br>    public string Author { get; set; }<br>    public string ISBN { get; set; }<br>    public DateTime PublishedDate { get; set; } // New property<br>}</pre><ul><li><strong>Add Migration</strong>: Run the following command in the Package Manager Console:</li></ul><pre>Add-Migration AddPublishedDateToBooks</pre><p>This command generates a new migration file in the Migrations folder, detailing the changes made to your model and how to apply them to the database.</p><h4>Step 3: Update the Database</h4><p>To apply the migration and update the database schema, execute:</p><pre>update-Database</pre><p>This command processes any pending migrations, executing the necessary SQL commands to modify the database structure accordingly. After running this command, the Books table in the database will now include the PublishedDate column, allowing you to store additional information about each book.</p><h3>Using Entity Framework in Your Controller</h3><p>Now that your context and migrations are set up, it’s time to integrate Entity Framework into your controller for performing CRUD operations.</p><h4>Update the Controller</h4><p>You will modify the BooksController to leverage the BookContext for accessing the database.</p><p>Here’s an updated version of your controller:</p><pre>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br> <br>public class BooksController : ApiController<br>{<br>    private readonly BookContext _context = new BookContext(); // DbContext instance<br> <br>    // GET api/books<br>    public IEnumerable&lt;Book&gt; Get()<br>    {<br>        return _context.Books.ToList(); // Get all books from the database<br>    }<br> <br>    // GET api/books/1<br>    public IHttpActionResult Get(int id)<br>    {<br>        var book = _context.Books.Find(id); // Find the book by ID<br>        if (book == null)<br>        {<br>            return NotFound();<br>        }<br>        return Ok(book);<br>    }<br> <br>    // POST api/books<br>    public IHttpActionResult Post([FromBody] Book book)<br>    {<br>        if (book == null)<br>        {<br>            return BadRequest(&quot;Invalid data.&quot;);<br>        }<br> <br>        _context.Books.Add(book); // Add the new book to the context<br>        _context.SaveChanges(); // Save changes to the database<br> <br>        return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = book.Id }, book);<br>    }<br> <br>    // DELETE api/books/1<br>    public IHttpActionResult Delete(int id)<br>    {<br>        var book = _context.Books.Find(id);<br>        if (book == null)<br>        {<br>            return NotFound();<br>        }<br>        _context.Books.Remove(book); // Remove the book from the context<br>        _context.SaveChanges(); // Save changes to the database<br>        return StatusCode(System.Net.HttpStatusCode.NoContent);<br>    }<br> <br>    protected override void Dispose(bool disposing)<br>    {<br>        if (disposing)<br>        {<br>            _context.Dispose(); // Dispose the context when done<br>        }<br>        base.Dispose(disposing);<br>    }<br>}</pre><h4>Controller Methods Explained</h4><ul><li><strong>Get()</strong>: This method retrieves all books from the database using the ToList() method on the Books DbSet. It returns a list of books to the client.</li><li><strong>Get(int id)</strong>: This method retrieves a specific book by its ID. It uses the Find method, which searches for the book in the Books DbSet. If the book is not found, it returns a 404 Not Found response.</li><li><strong>Post([FromBody] Book book)</strong>: This method handles incoming POST requests to add a new book. It first checks if the book object is valid. If valid, it adds the book to the Books DbSet and calls SaveChanges() to persist the data. It returns a 201 Created response with the newly created book.</li><li><strong>Delete(int id)</strong>: This method handles DELETE requests to remove a book by its ID. It checks if the book exists, removes it from the DbSet if found, and then calls SaveChanges() to update the database. If successful, it returns a 204 No Content status.</li><li><strong>Dispose(bool disposing)</strong>: This overridden method ensures that the BookContext is disposed of properly to release database connections and resources when the controller is no longer needed.</li></ul><h3>Conclusion</h3><p>In conclusion, both Entity Framework (EF) and ASP.NET Web API are powerful tools that work harmoniously to facilitate the development of modern web applications. Entity Framework acts as a bridge between the application’s object-oriented model and the underlying relational database, allowing developers to manipulate data seamlessly using C# objects instead of complex SQL queries. This abstraction not only simplifies data access but also enhances code maintainability and readability.</p><p>ASP.NET Web API provides a robust framework for building RESTful services, enabling the creation of APIs that can be consumed by various clients, including web applications, mobile apps, and third-party services. By integrating Entity Framework into an ASP.NET Web API project, developers can leverage EF’s capabilities for data management while exposing CRUD operations through a well-structured API. The combination of these technologies streamlines the development process, promotes best practices, and ultimately leads to the creation of scalable, maintainable, and efficient applications. Together, they empower developers to build data-driven solutions that meet the dynamic needs of users in today’s fast-paced digital landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec6a41d3aea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding TensorFlow: A Deep Dive into Machine Learning with Ease]]></title>
            <link>https://medium.com/@halfdeb/understanding-tensorflow-a-deep-dive-into-machine-learning-with-ease-4212e0a1a8f8?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4212e0a1a8f8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 18:51:30 GMT</pubDate>
            <atom:updated>2024-09-26T18:51:30.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsvXYss9ucuzN8IBcD_ztQ.png" /></figure><h3>Introduction</h3><p>In the rapidly evolving world of machine learning, <strong>TensorFlow</strong> has emerged as one of the most popular and versatile frameworks. It simplifies the process of building and deploying machine learning models, allowing developers to experiment with various tasks such as deep learning, neural networks, and other machine learning techniques. Developed by Google Brain, TensorFlow’s flexible architecture enables models to be deployed across multiple platforms, making it a top choice for both researchers and industry professionals.</p><p>This article will guide you through TensorFlow’s fundamental concepts, key features, and its core building block — <strong>tensors</strong>. Finally, we’ll walk through a practical example of building a linear regression model using TensorFlow 2.0.</p><h3>What is TensorFlow?</h3><p><strong>TensorFlow</strong> is an open-source framework designed to ease the development and deployment of machine learning models. From simple linear models to complex neural networks, TensorFlow offers support for various machine learning tasks.</p><h3>Key Features of TensorFlow</h3><ol><li><strong>Flexibility</strong>: TensorFlow’s architecture allows for easy model building and deployment on different platforms, such as servers, desktops, and mobile devices.</li><li><strong>Ecosystem</strong>: It has a rich ecosystem, featuring tools like TensorBoard (for model visualisation), TensorFlow Lite (for mobile and embedded devices), and TensorFlow Serving (for deploying models in production environments).</li><li><strong>Community Support</strong>: With a large community and an ever-growing repository of resources, TensorFlow remains one of the most supported frameworks in the field of machine learning.</li></ol><h3>Tensors: The Backbone of TensorFlow</h3><p>A <strong>tensor</strong> is essentially a multi-dimensional array that holds data in various forms, making it a central concept in TensorFlow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*RkFE3l-1p-xcQJ1f33ayEw.png" /></figure><ul><li><strong>0-D Tensor</strong>: A scalar (e.g., a single number like 5).</li><li><strong>1-D Tensor</strong>: A vector (e.g., [1, 2, 3]).</li><li><strong>2-D Tensor</strong>: A matrix (e.g., [[1, 2, 3], [4, 5, 6]]).</li><li><strong>N-D Tensor</strong>: A generalised tensor representing higher-dimensional data (e.g., images or video).</li></ul><p>In deep learning, tensors represent the features and data points used in training models.</p><h3>Computational Graphs: TensorFlow’s Core Engine</h3><p>TensorFlow uses <strong>computational graphs</strong> to perform operations. In this graph, the nodes represent mathematical operations (e.g., addition, multiplication), and the edges between them represent the data (tensors) that flow from one node to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*lwsoeT7jM55QBhMHXIlt2w.png" /></figure><h3>Building a Computational Graph</h3><p>A <strong>computational graph</strong> organises operations as nodes in a graph. Each node takes one or more tensors as inputs and produces one or more tensors as outputs.</p><h3>Running a Computational Graph</h3><p>In earlier versions of TensorFlow, a session was required to execute a computational graph. However, in TensorFlow 2.0, eager execution is enabled by default, allowing operations to run immediately as they are defined — no session is needed.</p><h3>TensorFlow: Constants, Variables, and Placeholders</h3><h3>Constants</h3><p><strong>Constants</strong> in TensorFlow are fixed values that don’t change during the execution of your model. For example, in a housing price prediction model, you might use a constant to represent the average price per square foot.</p><pre>import tensorflow as tf<br><br>average_price = tf.constant(200)  # Price per square foot</pre><h3>Variables</h3><p><strong>Variables</strong> are dynamic — they change as the model learns during training. Variables represent model parameters like weights or biases, which TensorFlow adjusts to optimise the model’s performance.</p><pre>num_bedrooms_weight = tf.Variable(0.5)  # Initial weight</pre><h3>Placeholders</h3><p><strong>Placeholders</strong> allow for dynamic data input during training. They define where data will enter the computational graph without specifying its exact shape or size, enabling flexible input handling.</p><pre>x = tf.placeholder(tf.float32, shape=[None, 1])  # Features (e.g., square footage)</pre><h3>Building Your First Model: Linear Regression in TensorFlow 2.0</h3><p>Let’s now build a simple linear regression model using TensorFlow 2.0. In this model, the equation for linear regression is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*0ntCLNR8rCFKBO4w2E1Ebg.png" /></figure><p>Where:</p><ul><li><em>W</em> is the weight (a learnable parameter).</li><li><em>B</em> is the bias (another learnable parameter).</li><li><em>X </em>is the input data.</li></ul><h3>Step-by-Step Guide:</h3><p><strong>Import TensorFlow</strong>:</p><pre>import tensorflow as tf</pre><p><strong>Define Variables</strong>: Initialise your weight <em>W</em> and bias <em>B</em> as TensorFlow variables.</p><pre>W = tf.Variable(tf.random.normal([1]), name=&#39;weight&#39;)<br>B = tf.Variable(tf.random.normal([1]), name=&#39;bias&#39;)</pre><p><strong>Model Definition</strong>: Create a function to represent your linear regression model.</p><pre>def linear_regression(X):<br>    return W * X + B</pre><p><strong>Loss Function</strong>: Define a loss function, such as <strong>mean squared error (MSE)</strong>.</p><pre>def loss_fn(Y_true, Y_pred):<br>    return tf.reduce_mean(tf.square(Y_pred - Y_true))</pre><p><strong>Optimizer</strong>: Select an optimizer to minimise the loss. Here, we’ll use <strong>Stochastic Gradient Descent (SGD)</strong>.</p><pre>optimizer = tf.optimizers.SGD(learning_rate=0.01)</pre><p><strong>Training Loop</strong>: Create a loop to train the model and adjust the values of <em>W</em> and <em>B</em> based on the input data.</p><pre>num_epochs = 1000<br>for epoch in range(num_epochs):<br>    with tf.GradientTape() as tape:<br>        Y_pred = linear_regression(X)<br>        loss = loss_fn(Y_true, Y_pred)<br>    gradients = tape.gradient(loss, [W, B])<br>    optimizer.apply_gradients(zip(gradients, [W, B]))<br><br>    if epoch % 100 == 0:<br>        print(f&#39;Epoch {epoch}: Loss: {loss.numpy()}, W: {W.numpy()}, B: {B.numpy()}&#39;)</pre><p><strong>Using the Model</strong>: After training, you can use the model to make predictions on new data.</p><pre>predictions = linear_regression(new_X)</pre><p>With TensorFlow 2.0’s eager execution, building and training models feels more intuitive. The code runs immediately, and there’s no need for creating and running sessions.</p><h3>Conclusion</h3><p>TensorFlow is a powerful tool for both beginners and experts in machine learning. Its flexibility, robust ecosystem, and ease of use make it ideal for a wide range of machine learning tasks. By mastering core concepts such as tensors, computational graphs, and TensorFlow’s handling of constants, variables, and placeholders, you can efficiently build and train models. The linear regression example demonstrated TensorFlow’s simplicity in handling mathematical models, highlighting its ability to scale from simple operations to more complex tasks.</p><p>Whether you’re just getting started or looking to explore advanced features, TensorFlow’s capabilities will support your journey through the vast landscape of machine learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4212e0a1a8f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DCGANs: Deep Convolutional Generative Adversarial Network]]></title>
            <link>https://medium.com/@halfdeb/dcgans-deep-convolutional-generative-adversarial-network-69bb63601fc8?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/69bb63601fc8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 21:46:32 GMT</pubDate>
            <atom:updated>2024-09-16T21:46:32.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkJXDD6Mk2rKzn5eNYdMXw.png" /></figure><h3>Introduction: What are GANs?</h3><p>Generative Adversarial Networks (GANs) are a subset of generative AI, capable of creating new, unique content across various domains like music, speech, and writing. At their core, GANs consist of two neural networks: the Generator and the Discriminator, which are set up in opposition to one another.</p><h4>How GANs Work</h4><ul><li><strong>Generator</strong>: Responsible for producing new instances of data by generating images from random inputs (noise).</li><li><strong>Discriminator</strong>: Evaluates the authenticity of the generated data by comparing it with real images, learning to distinguish between real and fake data in a feedback loop.</li></ul><p>To better understand this process, think of the Generator as an artist trying to create a convincing painting, while the Discriminator acts as an art critic. The critic has seen plenty of real paintings and tries to determine whether the artist’s work is genuine or not. Over time, as the artist receives feedback from the critic, they improve their technique and produce more convincing artwork. Similarly, the Generator improves its ability to create realistic images, while the Discriminator sharpens its skill in identifying fake ones.</p><h4>Steps of GANs</h4><ol><li>The Generator starts by taking a random input (noise) to create an image.</li><li>This generated image, along with real images from a dataset, is sent to the Discriminator.</li><li>The Discriminator then returns a probability score, indicating how likely the generated image is to be real, where 0 means “fake” and 1 means “authentic.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMwHWKKH19meb6x8aQsiRA.png" /></figure><p>The Discriminator is a standard convolutional neural network (a binary classifier) that labels images as real or fake. In contrast, the Generator works in the opposite way: instead of downsampling an image to return a probability, it takes random noise and upsamples it to create an image, which is then analysed by the Discriminator.</p><p><strong>The Competitive Process</strong><br>Both the Generator and Discriminator aim to optimise different, opposing loss functions. During training, the Generator becomes better at creating realistic images, while the Discriminator improves its ability to detect fakes. This dynamic process is often referred to as a “competition” between the two networks.</p><h4>Two Probability distribution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*itn60WlFUChL-XnrgjGLxQ.png" /></figure><ul><li><strong>Pg:</strong> The distribution generated by the Generator (implicit distribution).</li><li><strong>Pr:</strong> The distribution of real images.</li></ul><p>The ultimate goal is for these two distributions to become very similar, allowing the Generator to create highly realistic images.</p><h3>DCGANs</h3><p>Similar to the original GAN, DCGANs use Deep Convolutional Networks instead of fully connected networks. Convolutional networks are particularly effective at identifying areas of spatial correlation within an image. This makes DCGANs more suitable for working with images and videos, whereas traditional GANs are better suited for more general tasks.</p><p><strong>DCGAN Structure</strong><br>Just like other GANs, DCGANs consist of two neural networks: the Generator and the Discriminator.</p><ul><li><strong>Generator</strong>: Receives random noise as input and generates a fake image as output.</li><li><strong>Discriminator</strong>: Takes both real and fake images as input and analyses them. It returns a value between 0 and 1, indicating how real or fake the image appears.</li></ul><p>DCGANs use binary cross-entropy as their loss function. The key point to understand is that the Generator never directly “sees” real images. Instead, it learns to improve only through the feedback it receives from the Discriminator. The Generator’s goal is to produce images that can fool the Discriminator, making them appear as real as possible. On the other hand, the Discriminator aims to become increasingly accurate in distinguishing between real and fake images.</p><h3>Building a DCGAN Step by Step</h3><h4>Importing Libraries</h4><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import tensorflow as tf<br>from tensorflow.keras import layersp</pre><p>In this step, we begin by importing the necessary libraries. Matplotlib is used for plotting and visualising the generated images, while Numpy is used for array manipulation and data processing. TensorFlow is the core library used to build and train the DCGAN model.</p><h4>Loading and Preprocessing the Dataset</h4><pre>(X_train, y_train), (_, _) = tf.keras.datasets.fashion_mnist.load_data()</pre><p>We load the MNIST dataset here. This dataset consists of 60,000 training images of handwritten digits, each sized 28x28 pixels. Only the training data is needed for generating images, so we discard the test data.</p><h4>Reshaping the Dataset</h4><pre>X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype(&#39;float32&#39;)</pre><p>Here, we reshape the dataset to add an extra dimension, changing the shape from (60000, 28, 28) to (60000, 28, 28, 1). This extra dimension is necessary because the DCGAN expects input images with a channel dimension, even if they are grayscale (1 channel).</p><h4>Normalising the Dataset</h4><pre>X_train = (X_train - 127.5) / 127.5</pre><p>The pixel values in the dataset range from 0 to 255. To make the training process more stable, we normalise these values to a range between -1 and 1. This helps the neural networks learn more efficiently.</p><h3>Defining the Buffer Size and Batch Size</h3><pre>buffer_size = 60000<br>batch_size = 256</pre><p>We define the buffer_size as 60,000 (the total number of images) and the batch_size as 256. The batch size determines how many images are processed at a time during training.</p><h3>Shuffling and Batching the Dataset</h3><pre>X_train = tf.data.Dataset.from_tensor_slices(X_train).shuffle(buffer_size).batch(batch_size)</pre><p>Here, we convert the dataset into a tf.data.Dataset object. The dataset is shuffled with a buffer size of 60,000 to ensure the model doesn’t learn any order-specific patterns. It is then divided into batches of 256 images for more efficient processing during training.</p><h3>Building the Generator</h3><pre>def build_generator():<br>    network = tf.keras.Sequential()<br>    network.add(layers.Dense(units=7*7*256, use_bias=False, input_shape=(100,)))<br>    network.add(layers.BatchNormalization())<br>    network.add(layers.LeakyReLU())<br>    network.add(layers.Reshape((7, 7, 256)))<br>    network.add(layers.Conv2DTranspose(filters=128, kernel_size=(5, 5), padding=&#39;same&#39;, use_bias=False))<br>    network.add(layers.BatchNormalization())<br>    network.add(layers.LeakyReLU())<br>    network.add(layers.Conv2DTranspose(filters=64, kernel_size=(5, 5), padding=&#39;same&#39;, strides=(2, 2), use_bias=False))<br>    network.add(layers.BatchNormalization())<br>    network.add(layers.LeakyReLU())<br>    network.add(layers.Conv2DTranspose(filters=1, kernel_size=(5, 5), padding=&#39;same&#39;, strides=(2, 2), use_bias=True, activation=&#39;tanh&#39;))<br>    network.summary()<br>    return network</pre><p>The generator is responsible for creating fake images. It starts with a dense layer that transforms the random noise (a 100-dimensional vector) into a 7x7x256 feature map. Then, a series of transposed convolution layers upsample this feature map to eventually produce a 28x28x1 image (grayscale). The LeakyReLU activation is used to avoid vanishing gradients, and BatchNormalization helps stabilize the training by normalising each batch.</p><h3>Building the Discriminator</h3><pre>def build_discriminator():<br>    network = tf.keras.Sequential()<br>    network.add(layers.Conv2D(filters=64, strides=(2, 2), kernel_size=(5, 5), padding=&#39;same&#39;, input_shape=[28, 28, 1]))<br>    network.add(layers.LeakyReLU())<br>    network.add(layers.Dropout(0.3))<br>    network.add(layers.Conv2D(filters=128, strides=(2, 2), kernel_size=(5, 5), padding=&#39;same&#39;))<br>    network.add(layers.LeakyReLU())<br>    network.add(layers.Dropout(0.3))<br>    network.add(layers.Flatten())<br>    network.add(layers.Dense(1))<br>    network.summary()<br>    return network</pre><p>The discriminator evaluates whether an image is real or fake. It takes a 28x28x1 image as input and passes it through two convolutional layers that downsample the image, followed by dropout layers to prevent overfitting. Finally, the output is flattened and passed through a dense layer that outputs a single value (the probability of the image being real).</p><h3>Defining the Loss Function</h3><pre>cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)</pre><p>We use binary cross-entropy as the loss function for both the generator and the discriminator. The discriminator tries to classify images as either real or fake, and the generator tries to fool the discriminator into classifying fake images as real.</p><h3>Discriminator Loss</h3><pre>def discriminator_loss(expected_output, fake_output):<br>    real_loss = cross_entropy(tf.ones_like(expected_output), expected_output)<br>    fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)<br>    total_loss = real_loss + fake_loss<br>    return total_loss</pre><p>The discriminator’s loss function compares the discriminator’s output for both real images and fake images. The real images are labeled as 1, while the fake ones are labeled as 0. The total loss is the sum of the real and fake losses.</p><h3>Generator Loss</h3><pre>def generator_loss(fake_output):<br>    return cross_entropy(tf.ones_like(fake_output), fake_output)</pre><p>The generator’s loss function compares the discriminator’s output for fake images, which should be as close to 1 (real) as possible. The generator aims to minimize this loss and create images that the discriminator cannot distinguish from real ones.</p><h3>Optimisers</h3><pre>generator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.00001)<br>discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.00001)</pre><p>We use the Adam optimiser for both the generator and the discriminator. The learning rate is set to a low value (0.00001) to ensure stable training without drastic updates to the model weights.</p><h3>Training the GAN</h3><pre>@tf.function<br>def train(images):<br>    noise = tf.random.normal([batch_size, noise_dimension])<br>    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:<br>        generated_images = generator(noise, training=True)<br>        expected_output = discriminator(images, training=True)<br>        fake_output = discriminator(generated_images, training=True)<br>        gen_loss = generator_loss(fake_output)<br>        disc_loss = discriminator_loss(expected_output, fake_output)<br>    generator_gradients = gen_tape.gradient(gen_loss, generator.trainable_variables)<br>    discriminator_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables)<br>    generator_optimizer.apply_gradients(zip(generator_gradients, generator.trainable_variables))<br>    discriminator_optimizer.apply_gradients(zip(discriminator_gradients, discriminator.trainable_variables))</pre><p>The training function handles the training for both the generator and the discriminator. It starts by generating random noise to feed into the generator, which then produces fake images. These images are passed to the discriminator along with real images. The losses for both networks are calculated, and the gradients are used to update the model weights.</p><h3>Running the GAN Training and Visualizing Results</h3><pre>def train_gan(dataset, epochs, test_images):<br>    for epoch in range(epochs):<br>        for image_batch in dataset:<br>            train(image_batch)<br>        print(&#39;Epoch: &#39;, epoch + 1)<br>        generated_images = generator(test_images, training=False)<br>        fig = plt.figure(figsize=(10, 10))<br>        for i in range(generated_images.shape[0]):<br>            plt.subplot(4, 4, i + 1)<br>            plt.imshow(generated_images[i, :, :, 0] * 127.5 + 127.5, cmap=&#39;gray&#39;)<br>            plt.axis(&#39;off&#39;)<br>        plt.show()</pre><p>This function manages the overall training process across multiple epochs. It uses a batch of real images from the dataset and passes them through the training function. After each epoch, it generates and displays a grid of fake images created by the generator to visualise the progress.</p><h3>Results and Analysis After Training</h3><h4>Results after Epoch 1:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*801a6Di6qNxtN4ATWKKgwg.png" /></figure><p>At the very first epoch, the generator produces images that look more like random noise. This is because the generator hasn’t yet learned how to map the noise to meaningful image representations. The discriminator is easily able to distinguish between real and fake images at this stage.</p><h4>Results after Epoch 100:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*JwIeosA42kWSZvjjZZ4rNg.png" /></figure><p>After 100 epochs, the generator begins to create images that resemble clothing items from the Fashion MNIST dataset. While not perfect, the generated images show clear progress and demonstrate that the model is learning to generate more realistic images.</p><h3>Conclusion:</h3><p>This DCGAN implementation is a basic example, and while it shows promising results, there is still plenty of room for improvement. With more training epochs and advanced GAN architectures, the generated images can become significantly better. However, training for too many epochs can lead to mode collapse, where the generator produces a limited variety of images, losing the ability to generate diverse samples.</p><p>For more advanced image generation tasks, newer GAN architectures like <strong>StyleGAN</strong> or <strong>Progressive GANs</strong> may be used, which are designed to overcome some of the limitations of basic GANs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69bb63601fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polynomial Regression and Gradient Descent: A Comprehensive Guide]]></title>
            <link>https://medium.com/@halfdeb/polynomial-regression-and-gradient-descent-a-comprehensive-guide-745bb5baabcf?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/745bb5baabcf</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 13:13:39 GMT</pubDate>
            <atom:updated>2024-01-15T13:13:39.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkzZFiH0vq5M0W5BormYTw.png" /></figure><h3>Introduction</h3><p>Linear regression, a formidable algorithm, does have its limitations. Its assumption of a linear relationship between the dependent and independent variables often falls short in the real world. Data is rarely linearly separable, and relying on a straight-line relationship can lead to inaccuracies. Linear regression is also prone to noise, overfitting, and sensitivity to outliers, making it less versatile in handling complex datasets.</p><h4>The Need for Polynomial Regression</h4><p>So, what if our data defies the simplicity of a straight line? Surprisingly, a linear model can still be employed to fit non-linear data. One approach involves adding powers of each feature as new features, creating an extended set of features. This technique, known as polynomial regression, becomes a powerful tool in capturing the complexity of relationships within data.</p><h3>Exploring Polynomial Regression Through an Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*qjRofi5KjKTCAfqmP8GhMw.png" /></figure><p>Consider the figure above, where a straight line struggles to encapsulate the dataset adequately. In such cases, a linear model proves insufficient, and a more complex boundary is essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*9C1bu_3va0nEmOih64SECg.png" /></figure><p>Polynomial regression steps in to find relationships between features, allowing for the plotting of intricate boundaries that elude plain linear regression models.</p><h3>Plotting Complex Boundaries</h3><p>To depict complex boundaries, polynomial regression considers all combinations of features up to a specified degree. For instance, with two features, ‘a’ and ‘b’, a second-degree polynomial would introduce new features such as ‘a²’, ‘b²’, and ‘ab’. As we increase the degree, the model incorporates higher-order features, offering a more nuanced understanding of the dataset.</p><h3>Drawback of Polynomial Regression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*mlO8cb5bmr6iwQtsm_04wg.png" /></figure><p>While increasing the degree enhances the model’s performance, the trade-off comes in the form of an increased risk of overfitting. The higher the degree, the more closely the model tailors itself to the training data, potentially sacrificing its ability to generalise well to new, unseen data.</p><h3>Striking a Balance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*zdfludLhXFJdVe4elWbxDA.png" /></figure><p>The objective lies in determining the optimal degree, striking a balance between capturing complexity and preventing overfitting. Achieving a balanced boundary, as illustrated in the example, becomes crucial for the model’s effectiveness.</p><h3>Implementation of Polynomial Regression</h3><p>For the implementation of multivariable regression, a dataset with four features is employed. In the self-implementation, the dataset is converted into a dataframe, and features are created by multiplying pairs of existing features. This process, exemplified for degree 2, can be extended to higher degrees for more complex boundaries.</p><p><strong>Self-Implemented Linear Regression Model in Python</strong></p><pre>for i in range(4):<br>    for j in range(i, 4):<br>        ele = li[i] + &quot;_&quot; + li[j]<br>        df[ele] = df[li[i]]*df[li[j]]</pre><p>While the current implementation caters to degree 2, it’s worth noting that this approach is easily extensible to higher degrees. By iterating through the features and creating new combinations.</p><p><strong>Linear Regression Model using Sckit-Learn</strong></p><p>The Scikit-Learn library’s PolynomialFeatures is employed to transform the features, creating polynomial features for enhanced model training.</p><pre>from sklearn.preprocessing import PolynomialFeatures<br>poly_features = PolynomialFeatures()<br>x_poly = poly_features.fit_transform(X)</pre><p>In conclusion, polynomial regression emerges as a valuable tool in handling complex, non-linear relationships within datasets. Balancing the degree of the model is crucial to prevent overfitting and achieve a more generalised and effective predictive model.</p><h3>Gradient Descent</h3><p>Gradient Descent stands as a versatile optimization algorithm, proficient in uncovering optimal solutions across a spectrum of challenges. At its core, the algorithm iteratively refines parameters to minimize a given cost function. For the purpose of illustration, let’s consider a scenario with a single feature and target.</p><p><em>Model Representation:</em></p><p>So, for the time being let us assume that we have one feature and one target. In our pursuit of the best-fit line, the equation takes the form <em>y(predicted) ​=mx+c</em>, and the associated cost is expressed as the sum of squared differences: <em>∑(yi​−(mxi​+c))²</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*yQDMVYvvZ0yNUOrCTDwmrQ.png" /></figure><p>Visualising the relationship between the cost and the hypothesis (<em>m</em>), we observe a graph where the point <em>m</em> corresponds to the minimum cost. The objective is to navigate towards this optimal point.</p><h3><em>Steps to Minimise Cost using Gradient Descent:</em></h3><h4>1. Choosing the Starting Point:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*-ahXK160R-E2VCoTvjRGkQ.png" /></figure><ul><li>Begin with a choosing a random starting point(known as random initialisation)</li><li>Incrementally refine parameters to approach a better cost.</li></ul><h4>2. Determining the Direction:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*ZfaNt8YBy9cIatlShsGCcA.png" /></figure><ul><li>Compute the slope at the current point.</li><li>If the slope is negative, shift left (e.g., P1 in the graph); if positive, shift right (e.g., P2 in the graph).</li><li>Iterate this process, adjusting the direction based on the slope, until the desired state is reached.</li></ul><h4>3. Setting the Learning Rate:</h4><ul><li>The learning rate governs the size of the step taken during each iteration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*nvJTpgTPxHnRbts0oiXXZw.png" /></figure><ul><li>A balance is crucial; a too-large step may cause bouncing, while a too-small step may prolong convergence.</li><li>Consider adaptive learning rates: start with a high rate and decrease as proximity to the local minimum is achieved.</li></ul><h3>Math behind Gradient Descent</h3><p><em>Updating Parameters:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZmHsZUI2W4AaKwR1xswoQ.png" /></figure><p>The refined values for <em>m</em> and <em>c</em> in the optimisation process are computed using the following above formula</p><p>Where <em>α</em> stands for the learning rate, and slope(<em>m</em>​) and slope(<em>c)</em>​ represent the partial derivatives of the cost function with respect to <em>m</em> and <em>c</em> respectively which will help use to decide in which direction we should move.</p><p><em>Partial Derivatives Calculation:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyEFjV19egcKZZYBgknOsQ.png" /></figure><p>These derivatives provide the rate of change of the cost function concerning <em>m</em> and <em>c</em>, influencing the adjustments made during each iteration.</p><p><em>Optimisation Iterations:</em></p><p>The question arises: how many iterations are needed to optimize <em>m</em> and <em>c</em>? The optimisation process involves iteratively updating <em>m</em> and <em>c</em> and recalculating the cost. With each iteration, the optimized cost should exhibit a consistent decrease.</p><p><em>Convergence Criteria:</em></p><p>The optimisation process continues until the change in the cost function becomes minimal. This signifies that further iterations yield marginal improvements in the cost, indicating the algorithm has approached an optimal solution.</p><p>Understanding the mathematical foundations of gradient descent, including parameter updates and derivatives, unveils the iterative nature of the optimisation process. The convergence criteria, tied to diminishing changes in the cost, guide the algorithm towards an optimal configuration of <em>m</em> and <em>c</em>, ensuring a finely-tuned model.</p><h3>Types of Gradient Descent</h3><p><strong><em>Batch Gradient Descent:</em></strong> Batch Gradient Descent, often referred to as vanilla gradient descent, meticulously evaluates the error for each example in the entire training dataset. However, the model updates only after processing all training examples, constituting a training epoch. This approach offers computational efficiency, a stable error gradient, and reliable convergence. Yet, it may settle into a suboptimal convergence state, and the algorithm necessitates the entire training dataset to be in memory.</p><p><strong><em>Stochastic Gradient Descent (SGD):</em></strong> In contrast, Stochastic Gradient Descent (SGD) updates parameters for each training example individually. This means that the model undergoes frequent updates, potentially making it faster than batch gradient descent. While the detailed rate of improvement is an advantage, the computational expense and the introduction of noisy gradients are notable drawbacks. Noisy gradients can cause the error rate to fluctuate instead of steadily decreasing.</p><p><strong><em>Mini-Batch Gradient Descent:</em></strong> Mini-Batch Gradient Descent emerges as a harmonious blend of SGD and batch gradient descent. Here, the training dataset is partitioned into small batches, and an update is performed for each batch. This strategy strikes a balance between the stability of SGD and the efficiency of batch gradient descent. Common mini-batch sizes typically range between 50 and 256, but optimal sizes vary based on the application.</p><h3>Implementation of Gradient Descent</h3><p><strong>Self-Implemented Gradient Descent in Python</strong></p><pre># This function finds the new gradient at each step<br>def step_gradient(points, learning_rate, m , c):<br>    m_slope = 0<br>    c_slope = 0<br>    M = len(points)<br>    for i in range(M):<br>        x = points[i, 0]<br>        y = points[i, 1]<br>        m_slope += (-2/M)* (y - m * x - c)*x<br>        c_slope += (-2/M)* (y - m * x - c)<br>    new_m = m - learning_rate * m_slope<br>    new_c = c - learning_rate * c_slope<br>    return new_m, new_c<br><br># The Gradient Descent Function<br>def gd(points, learning_rate, num_iterations):<br>    m = 0       # Intial random value taken as 0<br>    c = 0       # Intial random value taken as 0<br>    for i in range(num_iterations):<br>        m, c = step_gradient(points, learning_rate, m , c)<br>        print(i, &quot; Cost: &quot;, cost(points, m, c))<br>    return m, c<br><br># This function finds the new cost after each optimisation.<br>def cost(points, m, c):<br>    total_cost = 0<br>    M = len(points)<br>    for i in range(M):<br>        x = points[i, 0]<br>        y = points[i, 1]<br>        total_cost += (1/M)*((y - m*x - c)**2)<br>    return total_cost<br><br>def run():<br>    learning_rate = 0.0001 # can change according to the situation<br>    num_iterations = 100   # can change according to the situation<br>    m, c = gd(training_data, learning_rate, num_iterations)<br>    print(&quot;Final m :&quot;, m)<br>    print(&quot;Final c :&quot;, c)<br>    return m,c</pre><p>This Python implementation of gradient descent involves three essential functions. The <em>step_gradient </em>function computes the new gradient using dataset points, the learning rate, and current <em>m</em> and <em>c</em> values. The main <em>gd</em> function iteratively updates <em>m</em> and <em>c</em> through the <em>step_gradient </em>function, displaying the cost at each iteration. The <em>cost</em> function calculates the new cost after each optimisation. The <em>run</em> function sets the learning rate and iterations, executes gradient descent, and prints the final <em>m</em> and <em>c</em>.</p><p><strong>Gradient Descent using Sckit-Learn</strong></p><pre>from sklearn.ensemble import GradientBoostingRegressor<br>model = GradientBoostingRegressor()<br>model.fit(x_train,y_train)</pre><p>Scikit-Learn simplifies gradient descent with the GradientBoostingRegressor. This concise code creates a regressor instance, fits it to training data (x_train and y_train), and trains the model with default settings. It&#39;s a swift and efficient approach for leveraging gradient descent without delving into manual optimisation, making it a valuable tool for those seeking a quick, high-level implementation.</p><h3>Conclusion</h3><p>In the realm of regression analysis, where linear models may fall short in capturing the complexity of real-world data, polynomial regression emerges as a powerful alternative. By introducing higher-order features through polynomial terms, this technique accommodates non-linear relationships, offering a more nuanced understanding of datasets.</p><p>However, the flexibility of polynomial regression comes with a caveat: the risk of overfitting increases with the degree of the polynomial. Striking a balance between complexity and overfitting becomes crucial for a well-generalised predictive model.</p><p>On the optimisation front, Gradient Descent proves to be a versatile algorithm, capable of refining parameters iteratively to minimise a given cost function. Whether implementing it from scratch in Python or utilizing Scikit-Learn’s convenient tools, Gradient Descent facilitates the optimization process, guiding models towards optimal solutions.</p><p>Understanding the interplay between Polynomial Regression and Gradient Descent provides a comprehensive toolkit for tackling diverse data challenges. The ability to navigate non-linear relationships while optimising model parameters ensures adaptability and robust performance across various applications. Ultimately, this combination of techniques contributes to the versatility and effectiveness of regression models in the ever-evolving landscape of data science.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745bb5baabcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Simple Linear Regression: Theory and Python Implementation Guide]]></title>
            <link>https://medium.com/@halfdeb/mastering-simple-linear-regression-theory-and-python-implementation-guide-7141239b1412?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7141239b1412</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 11:24:03 GMT</pubDate>
            <atom:updated>2024-01-11T11:24:03.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgNuD5eolkbtlEO16W8nFA.png" /></figure><h3>Introduction</h3><p>Linear Regression stands as the cornerstone of Machine Learning, representing the fundamental algorithm for regression tasks. This algorithm proves particularly valuable when predicting continuous values, where the output variable ‘Y’ exhibits a continuous nature.</p><p>Terms Used:</p><ul><li>Features: Independent variables denoted as X1, X2, … Xn.</li><li>Target/Output: Dependent variable ‘Y,’ influenced by the independent variables.</li></ul><p>Linear Regression assumes a linear relationship between ‘X’ and ‘Y,’ excelling at predicting future values while being less adept at classification.</p><p>The algorithm seeks to establish a function using training data, forming a hypothesis to predict outputs based on this function.</p><p>So, Linear Regression hypothesis function is represented by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILvkYOsTsFf_C3ThCmYGBw.png" /></figure><p>Here:</p><ul><li><em>Y</em> is the dependent variable (target/output),</li><li><em>X</em>1​,<em>X</em>2​,…,<em>Xn</em>​ are the independent variables (features),</li><li><em>m</em>1​,<em>m</em>2​,…,<em>mn</em>​ are the coefficients associated with the respective independent variables,</li><li><em>b</em> is the intercept.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA8mbpWmbfsXbNrKk8Dh-A.png" /></figure><p>In the figure above, which serves as an illustration of linear regression, it is evident that the algorithm endeavors to identify the optimal fit line within the training data. By leveraging the hypothesis generated from this line, the algorithm aims to make precise numerical predictions.</p><h4>Types of Linear Regression:</h4><ul><li><strong>Simple Linear Regression: </strong>When a single independent variable is used to predict the value of a numerical dependent variable.</li><li><strong>Multiple Linear Regression:</strong> If more than one independent variable is used to predict the value of a numerical dependent variable.</li></ul><h3>Simple Linear Regression</h3><p>This model, focused on a single independent variable ‘x,’ adopts the equation <em>Y</em>=<em>mX</em>+<em>b</em>. Linear Regression endeavours to identify values for ‘m’ and ‘b’ that minimise the error between each data point (x, y_actual) and its predicted counterpart (x, predicted).</p><h3>Evaluation of Our Model</h3><p>When making predictions, data points may fall perfectly on the line, have minor deviations, or exhibit major errors. Evaluating the model’s accuracy involves various metrics:</p><h4><strong>Mean Squared Error(MSE):</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSTW4RQM1J_6QAaV_wNuwA.png" /></figure><ul><li>∑ denotes the summation across all data points.</li><li><em>yi</em>​−(<em>m</em>⋅<em>xi</em>​+<em>b</em>) represents the difference between actual and predicted values for each data point.</li><li>Squaring each difference emphasises the magnitude of errors.</li><li>umming up these squared differences yields the overall cost.</li></ul><h4><strong>Root Mean Squared Error(RMSE):</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkQFkFFXTLyzqjGxmx5ovA.png" /></figure><h4><strong>Coefficient of Determination(R²):</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*IHxU_3Xw7cRqwUBBgy1pCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgTEuc2GKFCaCJO5dKh7uA.png" /></figure><p>In the context of <em>u</em>, we calculate the sum of squared differences by subtracting the predicted values from the actual values. This involves squaring each of these differences for every data point and subsequently summing up these squared values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuLB7cWw9kgLL0QEaCDnIA.png" /></figure><p>In the context of <em>v</em>, we compute the sum of squared differences by subtracting the mean value (<em>y</em>ˉ​) from each actual value. This process involves squaring each of these differences for every data point and subsequently summing up these squared values.</p><p>So combining all of these we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCdeDz6msclDhyOkhGpEMw.png" /></figure><p>The value of Coefficient of Determination will lie between 1 and 0, it can be negative but that means you are doing extremely bad.</p><p>The usefulness of R² is its ability to find the likelihood of future events falling within the predicted outcomes. The idea is that if more samples are added, the coefficient would show the probability of a new point falling on the line.</p><p>Even if there is a strong connection between the two variables, determination does not prove causality. For example, a study on birthdays may show a large number of birthdays happen within a time frame of one or two months. This does not mean that the passage of time or the change of seasons causes extra births.</p><h3>Cost Function</h3><p>A cost function, in the context of linear regression, is defined as a function that maps events or values of one or more variables onto a real number. This number intuitively represents the “cost” associated with the event. In the realm of linear regression, the primary objective is to identify the line of best fit for given inputs (X values) and corresponding outputs (Y values).</p><p>Objective: Optimize Regression Coefficients</p><ul><li>Different values for the coefficients result in various regression lines. The cost function comes into play to determine the coefficients that yield the best fit line. It essentially optimizes the regression coefficients, providing a measure of how well the linear regression model is performing.</li><li>The error in linear regression is calculated using the formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nk5vQ0fc8wli_NZQfOyTHA.png" /></figure><ul><li>However, a drawback of this method is that negative and positive errors cancel each other out. One approach to address this issue is by taking the modulus. Nevertheless, this introduces a linear addition of errors, potentially leading to inaccurate analysis.</li></ul><p>So, we will use mean squared error(MSE) as our cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zTUQuab8NuFNbDCHSXFcA.png" /></figure><p>It serves as a remedy to the cancellation problem, providing a more accurate measure of the overall error in the linear regression model.</p><p>In summary, the cost function plays a pivotal role in fine-tuning the linear regression model by optimizing the coefficients and employing MSE to gauge the accuracy of predictions.</p><p><strong>Optimizing m and b with the Cost Function</strong></p><p>Let’s find the value of m and b corresponding to which the cost function will be minimum.We will take the partial derivative of the cost function with respect to m and b separately to find their minimum values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*9KdiW-0P0N1DXBod1hxagg.png" /></figure><h3>Implementation of Linear Regression in Python</h3><h4>Self-Implemented Linear Regression Model in Python</h4><p>In this self-implemented linear regression model, the Python code efficiently determines the best-fit line using training data. The functions employed include:</p><pre># This function is used to find the best fit line using the training data<br>def fit(x_train, y_train):<br>    num = (x_train * y_train).mean() - x_train.mean() * y_train.mean()<br>    den = (x_train ** 2).mean() - x_train.mean() ** 2<br>    m = num / den<br>    c = y_train.mean() - m * x_train.mean()<br>    return m, c</pre><pre># This function predicts the value of &#39;y&#39; corresponding to each &#39;x&#39;<br>def predict(x, m, c):<br>    return m * x + c</pre><pre># This function returns the score using the Y(actual) and Y(predited), coefficient of determination.<br>def score(y_truth, y_pred): <br>    u = ((y_truth - y_pred)**2).sum()<br>    v = ((y_truth - y_truth.mean())**2).sum()<br>    return 1 - u/v</pre><pre>m, c = fit(X_train, Y_train)<br># Test data<br>y_test_pred = predict(X_test, m, c)<br>print(&quot;Test Score: &quot;,score(Y_test, y_test_pred))<br><br># Train data<br>y_train_pred = predict(X_train, m, c)<br>print(&quot;Train Score:&quot;, score(Y_train, y_train_pred))<br>print(&quot;M:&quot;, m)<br>print(&quot;C:&quot;, c)<br>print(&quot;Cost on training data:&quot;, cost(X_train,Y_train, m, c ))</pre><p>The obtained coefficients (‘m’ and ‘c’) are then used to predict values for both test and training data. The resulting scores are printed to assess the model’s accuracy. Additionally, the values of ‘m’ and ‘c’ are displayed, offering insights into the linear relationship. The code concludes with the calculation of the cost on the training data, providing a comprehensive understanding of the model’s efficacy.</p><h4>Linear Regression Model using Sckit-Learn</h4><p>This implementation of a linear regression model leverages the Scikit-Learn library, a powerful tool for machine learning in Python.</p><pre>from sklearn import linear_model<br> <br>reg = linear_model.LinearRegression()<br>reg.fit(X_train, Y_train)<br> <br>y_predict = reg.predict(X_test)</pre><p>The code utilizes the Linear Regression class from Scikit-Learn to effortlessly build and train a linear regression model on the provided training data (X_train and Y_train). The predict method is then used to obtain predictions for the test data (X_test).</p><pre>from sklearn.metrics import mean_squared_error<br>mse_self_implement = mean_squared_error(Y_test, y_predict)<br> <br>print(&quot;MSE&quot;, mse_self_implement)<br> <br>weights = reg.coef_           # An array of weights corresponding to each feature <br>intercept = reg.intercept_<br>print(&quot;Coeffecient for x is:&quot;, weights[0])<br>print(&quot;Intercept value is:&quot;, intercept)</pre><p>To assess the model’s performance, the mean squared error (MSE) is calculated using the mean_squared_error function from Scikit-Learn. This metric provides a measure of the average squared difference between predicted and actual values, offering insights into the accuracy of the model.</p><p>Moreover, the coefficients and intercept of the linear regression model are extracted using reg.coef_ and ref.intercept_ respectively. These values reveal the weights assigned to each feature and the intercept term in the linear equation, contributing to a comprehensive understanding of the model&#39;s learned parameters.</p><h3>Conclusion</h3><p>This comprehensive exploration of Simple Linear Regression, from theory to implementation in Python, equips readers with a profound understanding of the algorithm. Whether self-implementing or leveraging powerful libraries like Scikit-Learn, mastering linear regression becomes an attainable goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7141239b1412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling PCA: Illuminating the Geometric and Mathematical Foundations]]></title>
            <link>https://medium.com/@halfdeb/unveiling-pca-illuminating-the-geometric-and-mathematical-foundations-9d0325eeb3b1?source=rss-89149fdf64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d0325eeb3b1</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Debaditya Samanta]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 17:23:23 GMT</pubDate>
            <atom:updated>2024-01-04T17:29:49.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWxC-aI1mDRE5LfPeZzJRA.png" /></figure><h3>Introduction</h3><p>Principal Component Analysis (PCA) stands as a crucial technique in the realm of unsupervised learning, designed to address the Curse of Dimensionality — a phenomenon that plagues datasets with numerous, potentially irrelevant, or highly correlated features. The Curse of Dimensionality refers to the challenges that arise when dealing with datasets in high-dimensional spaces.</p><p>This article delves into the core principles of PCA, shedding light on its geometric and mathematical foundations. Specifically, we explore how PCA overcomes challenges like algorithmic efficiency, mitigates the Curse of Dimensionality, and provides visual insights for clearer data interpretation.</p><h4>Why PCA is used in Machine learning</h4><ul><li><strong>Algorithmic Efficiency:</strong></li></ul><p>PCA optimizes algorithm execution, resulting in faster speeds and reduced memory consumption. This is particularly valuable in large-scale machine learning applications.</p><ul><li><strong>Curse of Dimensionality Mitigation:</strong></li></ul><p>By extracting critical features, PCA effectively combats the Curse of Dimensionality, enhancing model accuracy and preventing overfitting.</p><ul><li><strong>Visual Insight:</strong></li></ul><p>PCA facilitates clearer data interpretation by reducing it to 2D or 3D, providing a visually comprehensible representation. This aids in understanding complex relationships within the data.</p><h4>Feature Selection</h4><p>Consider a scenario where the target variable is price (Y), with features including the number of rooms (f1) and the number of grocery stores (f2).</p><p>Let’s visualise this decision-making process through a graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*jVgarKpijfeTF1i4HfdgGg.png" /></figure><p>Consider a graph plotting the variance of rooms (d1) against the variance of number of grocery store (d2). The objective is to discern which feature holds more significance in influencing the target variable.</p><p>From the graph, it becomes apparent that the variance of number of rooms(d1) markedly exceeds that of number of grocery store(d2). In this scenario, the strategy is clear — retain the feature with higher variance. In our example, with d1 &gt; d2, we opt to retain number of rooms(f1) and discard number of grocery stores(f2).</p><h4><strong>Feature Extraction</strong></h4><p>Expanding on our illustration, let’s consider a scenario where we replace the number of grocery stores with the number of washrooms. Faced with a dilemma where both features seem equally vital, conventional methods might falter.</p><p><em>Stalemate in Feature Importance</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*aKCzqMDErCFhTedG5XbgyA.png" /></figure><p>When confronted with the decision between the number of rooms (f1) and the number of washrooms (f2), and finding both equally crucial, the traditional reliance on variance/spread becomes inconclusive. The graph reveals equal variances (d1 = d2). In such cases, we turn to Principal Component Analysis (PCA).</p><p><em>PCA as the Resolving Force</em></p><p>In these situations, Principal Component Analysis (PCA) emerges as the hero, solving the problem. PCA has the distinctive capability to merge features into a new dimension, forming a composite feature that captures the essence of the original variables.</p><p><em>Constructing a Unified Feature: SIZE</em></p><p>In our specific case, PCA suggests combining both the number of rooms (f1) and the number of washrooms (f2) into a singular, all-encompassing feature named SIZE. This newly formed feature captures the fundamental characteristics of both f1 and f2, providing a holistic representation while significantly reducing the complexity of the data.</p><p><em>The Essence of PCA</em></p><p>The essence of PCA lies in its capacity to navigate through feature ambiguity, seamlessly creating a new set of dimensions that encapsulate the core information of the original features. By doing so, PCA not only resolves dilemmas but also streamlines the data into a more manageable and meaningful form, paving the way for enhanced interpretability and efficiency in machine learning applications.</p><h3>Geometric Intuition</h3><p>Let’s imagine the same graph for the same set of features(rooms and washrooms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Zy7Rp1Z4CEfEAQI40w8ucw.png" /></figure><p>So, earlier we had two axes in the graph room and washroom. So, what PCA does is it tries to find a new set of axes/co-ordinates room’ and washroom’ axes.</p><p>In the given example of a room and a washroom, when applying Principal Component Analysis (PCA), the algorithm seeks to identify a new set of coordinates represented by axes denoted as room’ and washroom’. Subsequently, by focusing on these newly defined axes, PCA aims to maximise the variance or spread along these directions. Upon analysis, if the variance along the room’ axis (PC1) surpasses that along the washroom’ axis (PC2), the latter is deemed less significant, leading to its removal.</p><p>The resulting axes, PC1 and PC2, represent the Principal Components (PCs) of the dataset. In this context, PC1 (room’) is chosen as the primary component due to its higher variance, signifying its importance in capturing the key information within the data.</p><h3>Mathematical Intuition</h3><p>Let’s delve into key statistical techniques utilized in Principal Component Analysis (PCA), starting with the pivotal concept of covariance.</p><h4><strong>The Need for Covariance:</strong></h4><p>In the initial stages of statistical analysis, reliance on the mean as a measure of central tendency proved insufficient in addressing the complexity of certain problems. While the mean provides a central anchor, it falls short in capturing the spread or variability within a dataset. Recognising this limitation, variance was introduced to quantify individual data point deviations. However, variance alone fails to capture potential relationships between variables. Hence, the necessity for covariance arose, offering a more comprehensive understanding of not only how individual variables deviate but also how they co-vary.</p><h4>Understanding Covariance Matrix:</h4><p>The covariance matrix emerges as a powerful summary sheet for diverse measurements. It elucidates how each variable varies independently (diagonal elements) and explores their collective variations (off-diagonal elements). A positive covariance indicates variables that tend to increase or decrease together, while a negative covariance signifies variables that move in opposite directions. In practical terms, the covariance matrix simplifies complex data, revealing relationships and patterns.</p><p>Now, let’s construct our covariance matrix Σ using using 3 features X, Y, and Z:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*PaQlQhKwWe8lz023dSxQaQ.png" /></figure><ul><li><strong><em>Var(X), Var(Y), Var(Z): </em></strong>These diagonal elements represent the variances of X, Y, and Z respectively. Imagine them as the measure of how much each variable dances around its own average value. The larger the variance, the more unpredictable the variable’s behaviour.</li><li><strong><em>Cov(X, Y), Cov(X, Z), Cov(Y, Z):</em></strong><em> </em>Moving off the diagonal, these elements capture the joint variability between pairs of variables. Cov(X, Y), for example, tells us if X and Y tend to move together or in opposite directions.</li></ul><p>In simpler terms, the covariance matrix acts as a statistical compass, guiding us through the interconnectedness of our variables. The diagonal elements pinpoint the variability of each variable in isolation, while the off-diagonal elements reveal the extent to which variables influence each other.</p><h4>Eigen Vectors and Eigen Values:</h4><p>Eigen vectors, a special type of vectors, exhibit a remarkable property — they maintain their direction even after the application of a linear transformation. On the other hand, eigen values represent the magnitude change of the corresponding eigen vector.</p><p>In the context of PCA, eigen vectors play a pivotal role in identifying the principal dimensions of the dataset. They indicate the directions in which the data varies the most. Meanwhile, eigen values provide insights into the amount of information carried by these specific directions. If the eigen value associated with a particular dimension is significantly small, it implies that this dimension contributes less information and can be safely disregarded in the interest of dimensionality reduction.</p><h4>Steps of PCA Implementation:</h4><ol><li>Find the Co-variance Matrix of the dataset.</li><li>Perform eigen decomposition to obtain eigen vectors and eigen values.</li><li>Identify eigen vectors corresponding to the maximum eigen values.</li><li>Discard dimensions with minimal eigen values, as they contribute less information.</li></ol><p>The process of Principal Component Analysis (PCA) relies on mathematical concepts like covariance, covariance matrix, eigenvalues, and eigenvectors, allowing PCA to systematically reduce dimensionality for a more efficient representation of data.</p><h3>Conclusion</h3><p>In conclusion, Principal Component Analysis (PCA) emerges as a powerful ally in the field of machine learning, offering a strategic solution to the challenges posed by high-dimensional datasets. As we navigated through the geometric and mathematical foundations of PCA, it became evident that this technique is not just a dimensionality reduction tool but a beacon that illuminates the intricacies of data interpretation and model optimisation.</p><p>By addressing the Curse of Dimensionality, PCA optimizes algorithmic efficiency, enhances model accuracy, and provides a visual language for clearer data understanding. The journey from feature selection to feature extraction demonstrated PCA’s unique ability to resolve dilemmas in situations where traditional methods fall short.</p><p><em>Special thanks to CampusX for their enlightening videos that have been instrumental in my comprehension of this entire concept. The attached video links below serve as valuable resources, providing a clearer and more in-depth understanding of the topic for readers seeking further clarification and insights.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiRbsBi5W0-c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiRbsBi5W0-c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiRbsBi5W0-c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea7d1ac8dbc4d1d0cc6202b068b17a8c/href">https://medium.com/media/ea7d1ac8dbc4d1d0cc6202b068b17a8c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtXXnxjj2wM4%3Fstart%3D2909%26feature%3Doembed%26start%3D2909&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtXXnxjj2wM4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtXXnxjj2wM4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b46e51b60ec41b710f0135964a53e637/href">https://medium.com/media/b46e51b60ec41b710f0135964a53e637/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d0325eeb3b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>