<?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 Diego O’Hurtado on Medium]]></title>
        <description><![CDATA[Stories by Diego O’Hurtado on Medium]]></description>
        <link>https://medium.com/@diegohurtadoo?source=rss-3b572bafb88a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u0OOzVTv2BWtCyYh-c4oFQ.jpeg</url>
            <title>Stories by Diego O’Hurtado on Medium</title>
            <link>https://medium.com/@diegohurtadoo?source=rss-3b572bafb88a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:43:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diegohurtadoo/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[Google ADK vs LangChain vs LangGraph vs LangFlow vs LangSmith]]></title>
            <link>https://diegohurtadoo.medium.com/google-adk-vs-langchain-vs-langgraph-vs-langflow-vs-langsmith-60ed7b8e2d14?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60ed7b8e2d14</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 14:01:01 GMT</pubDate>
            <atom:updated>2026-03-17T14:01:01.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo2IGl2IFRGggMtzNh66cw.png" /></figure><h3>The Real Differences in the Modern AI Agent Stack</h3><p>Most “X vs Y” posts compare these tools as if they were interchangeable.</p><p>They aren’t.</p><p>I watched a team spend three weeks evaluating Google ADK against LangChain, as if they were competing solutions to the same problem. They weren’t. One is an orchestration framework for multi-agent systems. The other is a component library for LLM integrations. Comparing them is like asking whether a restaurant needs a head chef or a pantry. The answer is obvious: <strong>you need both, and they do completely different jobs.</strong></p><p>Some of these tools are frameworks, some are orchestrators, some are visual builders, and others are observability platforms. Comparing them head-to-head is like comparing a chef’s knife to an oven to a thermometer , they’re all in the kitchen, but they solve fundamentally different problems.</p><p>If you’re building production AI agents, understanding <strong>where each tool fits in the stack</strong> is far more important than choosing a single “winner.”</p><p>The biggest mistake teams make with AI agents is <strong>confusing orchestration with infrastructure.</strong></p><p>This guide breaks down the actual roles of:</p><ul><li><strong>Google ADK</strong></li><li><strong>LangChain</strong></li><li><strong>LangGraph</strong></li><li><strong>LangFlow</strong></li><li><strong>LangSmith</strong></li></ul><p>…and explains when you should use each one and when you shouldn’t in real systems.</p><ul><li><strong>Google ADK</strong> → Production multi-agent orchestration (the kitchen brigade)</li><li><strong>LangChain</strong> → LLM components, tools &amp; integrations (the ingredient pantry)</li><li><strong>LangGraph</strong> → Stateful workflow graphs with loops &amp; branching (the recipe execution engine)</li><li><strong>LangFlow</strong> → Visual drag-and-drop prototyping (the cooking show demo)</li><li><strong>LangSmith</strong> → Observability, tracing &amp; evaluation (the health inspector)</li></ul><p>They’re not competitors. They’re different layers of the same stack. Many production teams use 3–4 of them together.</p><h3>The Modern AI Agent Stack</h3><p>AI agents are not just prompts.</p><p>A production agent system typically requires seven distinct capabilities: orchestration, tool execution, retrieval, memory, monitoring, evaluation, and deployment infrastructure. No single framework covers all seven. This is the root cause of the confusion — people evaluate individual tools against the full list and conclude they’re all “incomplete.” They’re not incomplete. They’re specialized.</p><p>Think of it like a professional kitchen. No single piece of equipment makes a restaurant work. You need the stove (compute), the pantry (components), the expeditor (orchestration), the recipe system (workflows), and the health inspector (observability). Each tool in the AI agent stack maps to one of these roles.</p><p>Different frameworks solve different layers of this stack. Here’s where each one fits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw8L7ARHojTKQUVx9Qnl_g.png" /></figure><p><strong>Figure 1 — The modern AI agent stack and where each framework fits.</strong></p><p>Understanding this layering is the key insight. Once you see these tools as complementary layers rather than competing products, the “which one should I use?” question answers itself: <strong>it depends on which layer you’re solving for.</strong></p><p>Let’s break down each one.</p><h3>1. Google ADK — The Kitchen Brigade</h3><p>Google’s <strong>Agent Development Kit (ADK)</strong> is a code-first framework designed for building production multi-agent systems.</p><p>Unlike many agent frameworks optimized for demos and tutorials, ADK is built around <strong>explicit workflow orchestration and production reliability</strong>. You define exactly how agents coordinate — sequentially, in parallel, or in loops , using Python code that reads like an architecture diagram.</p><p>Key capabilities include:</p><ul><li><strong>Sequential and Parallel agents</strong> — Define multi-agent topologies in code</li><li><strong>Loop orchestration</strong> — Agents that iterate until a condition is met</li><li><strong>Structured outputs</strong> — Enforce deterministic response schemas</li><li><strong>Session state management</strong> — Persistent context across agent interactions</li><li><strong>Artifacts and memory</strong> — Store and retrieve data across sessions</li><li><strong>Grounding with external tools</strong> — Connect agents to APIs, databases, and search</li><li><strong>Evaluation pipelines</strong> — Built-in testing for agent quality</li><li><strong>Deployment to Vertex AI Agent Engine</strong> — One-click production deployment on Google Cloud</li></ul><p>Instead of hiding orchestration behind prompts, ADK makes workflows <strong>explicit and inspectable.</strong></p><p>Here’s what a multi-agent orchestration looks like in ADK:</p><pre>root_agent = SequentialAgent(<br>    name=&quot;MultiAgentWorkflow&quot;,<br>    sub_agents=[<br>        router_agent,<br>        ParallelAgent(sub_agents=[<br>            analysis_agent,<br>            retrieval_agent,<br>            computation_agent,<br>            execution_agent<br>        ]),<br>        synthesis_agent<br>    ]<br>)</pre><p>This structure makes the control flow <strong>visible and deterministic</strong> — you can read the orchestration logic without tracing through prompts or hidden state. For production systems, this explicitness is not a nice-to-have; it’s a requirement.</p><p>There’s a critical architectural decision embedded in this code that’s easy to miss: the ParallelAgent executes all four sub-agents <strong>concurrently</strong>, not sequentially. In a travel planning scenario, this means weather data, hotel searches, attraction lookups, and transport options are all fetched simultaneously. What would take 12 seconds sequentially completes in ~3 seconds. At scale, this parallelism is the difference between a usable product and a timeout.</p><p>ADK also introduces a factory pattern for agent instantiation — build_travel_workflow() creates fresh agent instances for every execution. This prevents a subtle but devastating production bug: <strong>state contamination between requests.</strong> If Agent A&#39;s memory from Request 1 leaks into Request 2, you get hallucinated context — and in an agentic system with tool execution capabilities, hallucinated context can trigger real-world actions.</p><p>ADK treats agents as <strong>orchestrated workflows — not chat loops.</strong></p><p><strong>Best use cases:</strong> Enterprise multi-agent systems, structured pipelines with parallel execution, production deployments on Google Cloud / Vertex AI.</p><p><strong>The hard truth:</strong> ADK’s strength — deep Vertex AI integration — is also its primary tradeoff. Teams not running on Google Cloud will face friction. The framework is opinionated about its deployment target, which is a deliberate design choice for production reliability but limits portability. If your infrastructure is AWS or Azure-first, evaluate the integration cost carefully before committing.</p><h3>2. LangChain</h3><h3>2. LangChain — The Ingredient Pantry</h3><p><strong>LangChain</strong> is one of the most widely adopted AI application frameworks in the ecosystem, and for good reason: its strength lies in the sheer breadth of <strong>integrations and modular components</strong> it provides.</p><p>Think of LangChain as a massively well-stocked pantry. It gives you every ingredient you could possibly need — LLM abstractions, tool calling, retrieval pipelines, memory modules, prompt templates, and integrations with hundreds of APIs — but it doesn’t tell you how to cook the meal.</p><p>Core capabilities:</p><ul><li><strong>LLM abstractions</strong> — Unified interface across OpenAI, Anthropic, Google, and dozens more</li><li><strong>Tool calling</strong> — Standardized function-calling patterns</li><li><strong>Retrieval pipelines</strong> — Document loaders, text splitters, vector stores</li><li><strong>Memory modules</strong> — Conversation history, summary memory, entity memory</li><li><strong>Prompt templates</strong> — Reusable, parameterized prompt engineering</li><li><strong>500+ integrations</strong> — From Pinecone to PostgreSQL to Slack</li></ul><p>Here’s a basic tool-calling chain in LangChain:</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br><br>@tool<br>def get_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch current weather for a city.&quot;&quot;&quot;<br>    return f&quot;72°F and sunny in {city}&quot;<br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;).bind_tools([get_weather])<br>result = llm.invoke(&quot;What&#39;s the weather in Tokyo?&quot;)</pre><p>This flexibility makes LangChain ideal for <strong>prototyping AI applications quickly</strong>, building RAG systems, and integrating LLMs into existing software where you need to connect many different services.</p><p>The ecosystem advantage is real. Need to load PDFs? There’s a document loader. Need to query Pinecone, Weaviate, or Chroma? There’s a vector store integration. Need to switch from OpenAI to Anthropic? Change one import. This modularity lets teams move fast in the exploration phase , and in AI development, speed of experimentation often determines who ships first.</p><p><strong>The hard truth:</strong> LangChain’s abstraction layers , the very thing that makes it flexible — can become a debugging challenge at scale. When a chain of 6 components fails in production, tracing which abstraction swallowed the error requires patience. Stack traces can be deep, and the gap between “what the abstraction exposes” and “what actually happened in the HTTP call” can be frustrating. This is not a flaw; it’s an inherent tradeoff of generalized abstractions. It’s also precisely why LangGraph and LangSmith exist — they solve the orchestration and observability gaps that emerge when LangChain applications grow beyond prototypes.</p><p><strong>Best use cases:</strong> Rapid prototyping, RAG pipelines, LLM integration into existing codebases, projects that need broad third-party API connectivity.</p><p><strong>Myth vs. Reality</strong></p><p><em>Myth:</em> “LangChain does everything , it’s the only framework you need.”</p><p><em>Reality:</em> LangChain provides <strong>components</strong>, not <strong>orchestration</strong>. For simple chains, that’s enough. For multi-step agent workflows with branching, retries, and state — you’ll need LangGraph. For monitoring and evaluation , you’ll need LangSmith. LangChain is the foundation layer, not the entire building.</p><h3>3. LangGraph — The Recipe Execution Engine</h3><p><strong>LangGraph</strong> is the orchestration layer that sits on top of LangChain.</p><p>Where LangChain gives you components, LangGraph gives you <strong>execution structure</strong>. Instead of linear chains, LangGraph models workflows as <strong>stateful directed graphs</strong> — with branching, loops, retries, and persistence built in.</p><p>Conceptually, it’s closer to a <strong>state machine for AI agents</strong> than a prompt chaining library.</p><p>Core capabilities:</p><ul><li><strong>Branching workflows</strong> — Route execution based on conditions or LLM decisions</li><li><strong>Loops and cycles</strong> — Agents that iterate, refine, and self-correct</li><li><strong>Retries with error context</strong> — Automatic recovery from failures</li><li><strong>State persistence</strong> — Checkpoint and resume long-running workflows</li><li><strong>Human-in-the-loop</strong> — Pause execution for human approval at critical nodes</li></ul><p>Here’s a stateful agent graph in LangGraph:</p><pre>from langgraph.graph import StateGraph, END<br><br>workflow = StateGraph(AgentState)<br><br>workflow.add_node(&quot;research&quot;, research_agent)<br>workflow.add_node(&quot;analyze&quot;, analysis_agent)<br>workflow.add_node(&quot;decide&quot;, decision_node)<br><br>workflow.add_edge(&quot;research&quot;, &quot;analyze&quot;)<br>workflow.add_conditional_edges(&quot;analyze&quot;, route_decision, {<br>    &quot;needs_more_research&quot;: &quot;research&quot;,   # Loop back<br>    &quot;ready&quot;: &quot;decide&quot;                    # Move forward<br>})<br>workflow.add_edge(&quot;decide&quot;, END)<br><br>app = workflow.compile()</pre><p>Notice the key difference from the ADK example: LangGraph defines workflows as <strong>graphs with explicit edges and conditions</strong>, making cycles and branching first-class primitives. The &quot;needs_more_research&quot; → &quot;research&quot; loop is trivial to express here, and the state is automatically persisted between nodes.</p><p>This cycling capability is what makes LangGraph fundamentally different from simple chain-based orchestration. In a linear chain, if step 3 produces a bad result, you either accept it or restart from step 1. In a LangGraph workflow, step 3 can loop back to step 2 with error context, refine the result, and try again — without re-executing the expensive steps that already succeeded. For agent systems that make API calls at each step, this saves both time and cost.</p><p>State persistence is the other key feature. LangGraph can <strong>checkpoint the entire execution state</strong> at any node, persist it to a database, and resume later. This enables long-running workflows that span hours or days — think: “start a research task, pause for human review, resume with feedback, continue to completion.” Most other orchestration approaches lose state when the process restarts.</p><p>This is particularly powerful for:</p><ul><li><strong>Multi-step reasoning</strong> — Agent refines its answer through iterative loops</li><li><strong>Planning agents</strong> — Break complex tasks into sub-plans, execute, evaluate, re-plan</li><li><strong>Conversational workflows</strong> — Long-running interactions with checkpoint/resume</li><li><strong>Self-correcting pipelines</strong> — Validate output, loop back on failure</li></ul><p><strong>The relationship to LangChain:</strong> If LangChain is the pantry (ingredients), LangGraph is the recipe execution system (when to add each ingredient, in what order, with what conditions). Most production LangChain applications eventually adopt LangGraph for orchestration — it’s the natural evolution, not a replacement.</p><p><strong>Best use cases:</strong> Complex agent control flow, iterative planning and reasoning, workflows that require loops, branching, or long-running state.</p><h3>4. LangFlow — The Cooking Show Demo</h3><p><strong>LangFlow</strong> is a visual development interface for LangChain.</p><p>Instead of writing code, developers build AI pipelines using <strong>drag-and-drop nodes</strong> in a browser-based canvas. Each node represents a LangChain component — an LLM call, a retrieval step, a tool, a prompt template — and you wire them together visually.</p><p>Features include:</p><ul><li><strong>Visual prompt flow builder</strong> — See your entire pipeline as a graph</li><li><strong>Rapid prototyping</strong> — Go from idea to working demo in minutes</li><li><strong>Visual debugging</strong> — Inspect intermediate outputs at each node</li><li><strong>Python export</strong> — Convert visual flows to Python code for production</li></ul><p>This makes LangFlow genuinely useful for <strong>beginners learning the LangChain ecosystem</strong>, teams prototyping pipeline architectures before committing to code, and demos or experimentation where speed matters more than production-readiness.</p><p><strong>When NOT to use LangFlow:</strong> Most production systems eventually migrate to code-based frameworks — and for good reason. Visual builders hit limits when you need custom error handling, complex state management, version control with Git, CI/CD integration, or performance optimization. If you’re past the prototyping stage, you should be writing code.</p><p>The honest framing: LangFlow is a <strong>discovery and prototyping tool</strong>, not a production deployment target. It’s excellent at its job — just be clear about what that job is.</p><p><strong>Best use cases:</strong> Learning LangChain, prototyping pipeline architectures, demos, and non-technical stakeholder presentations.</p><h3>5. LangSmith — The Health Inspector</h3><p>Your agent just hallucinated a hotel that doesn’t exist. A customer saw a price that was wrong by 40%. Your RAG pipeline returned a chunk from the wrong document.</p><p>Your logs show… nothing.</p><p><strong>This is the problem LangSmith solves.</strong></p><p>LangSmith focuses on <strong>observability, testing, and evaluation</strong> for LLM applications. It’s a completely different category from the other four tools — it doesn’t build agents, it <strong>monitors them</strong>.</p><p>Core capabilities:</p><ul><li><strong>Prompt tracing</strong> — Full visibility into every LLM call, input, output, latency, and cost</li><li><strong>Agent execution logs</strong> — Step-by-step replay of multi-agent workflows</li><li><strong>Dataset-based evaluation</strong> — Test agent outputs against golden datasets</li><li><strong>Regression testing</strong> — Detect when prompt changes degrade performance</li><li><strong>Performance monitoring</strong> — Track latency, token usage, error rates in production</li></ul><p>If you can’t observe an AI system, you can’t reliably improve it. LangSmith makes the invisible visible.</p><p>Here’s a concrete scenario: your customer support agent suddenly starts giving incorrect refund amounts. Without tracing, you’re guessing — is it the prompt? The retrieval? The model? A changed API response? With LangSmith, you pull up the trace for any specific request and see <strong>exactly</strong> which component produced the wrong value, what inputs it received, and what the model’s reasoning was. Debugging time drops from hours to minutes.</p><p>The evaluation capability is equally critical. LangSmith lets you define golden datasets — input/expected-output pairs — and automatically test your agent against them whenever you change a prompt, swap a model, or modify a tool. This is the LLM equivalent of unit testing, and it catches regressions before they reach production.</p><p><strong>The critical insight:</strong> LangSmith is not tied to LangChain. It works alongside LangChain, LangGraph, and even <strong>custom agent frameworks</strong> that don’t use LangChain at all. Any system that makes LLM calls can benefit from structured observability. If you’re building agents with Google ADK, CrewAI, AutoGen, or raw API calls — LangSmith still works.</p><p><strong>Best use cases:</strong> Production monitoring, prompt regression testing, debugging agent failures, evaluating output quality at scale.</p><p><strong>The hard truth:</strong> Observability is the most underinvested layer in most AI agent stacks. Teams spend 90% of their time building agents and 10% on monitoring — then spend 90% of their debugging time wishing they had better logs. If you’re deploying agents to production without tracing, you’re flying blind.</p><h3>The Real Comparison</h3><p>These tools are often positioned as competitors. In reality, many production teams use three or four of them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t62livI88ak2oUgEAIUt9w.png" /></figure><p><strong>Figure 2 : Comparison of major AI agent frameworks.</strong></p><p><strong>How to read the Production Readiness scores:</strong> These ratings reflect each tool’s <strong>out-of-the-box</strong> production capabilities — native deployment support, built-in error handling, state management, and observability integration. LangChain scores lower not because it can’t be used in production, but because it typically requires LangGraph + LangSmith to reach production-grade reliability. ADK scores highest because production deployment (via Vertex AI) is its primary design goal. LangGraph and LangSmith both score high because they were specifically created to address production gaps.</p><h3>The Full Stack in Practice</h3><p>Enough theory. Here’s how these tools work <strong>together</strong> in a real production architecture.</p><p>Consider a customer support agent system that handles complex, multi-step queries — refunds, account changes, technical troubleshooting — across multiple backend systems. No single framework handles this end-to-end. But the combination is powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXZSFWt6lkijOxkNnw6Zuw.png" /></figure><p>In this architecture:</p><ul><li><strong>Google ADK</strong> defines the top-level orchestration , sequential steps, parallel fan-out, and the overall agent topology. It’s the executive chef deciding the order of operations and which stations fire simultaneously.</li><li><strong>LangChain</strong> powers the individual tool calls — RAG retrieval from the policy knowledge base, API integrations for account lookups, and LLM abstractions for the component agents. It’s the pantry every station pulls from.</li><li><strong>LangGraph</strong> handles the resolution workflow — a stateful graph where the agent proposes a solution, validates it against business rules, and loops back if validation fails. For high-risk actions (refunds over $500), it pauses for human approval. It’s the recipe execution system that handles “what if the soufflé falls.”</li><li><strong>LangSmith</strong> wraps the entire system in observability — tracing every LLM call, every tool invocation, every routing decision. When something goes wrong at 3 AM, the on-call engineer can replay the exact execution path and identify the failure in minutes instead of hours.</li><li><strong>LangFlow</strong> doesn’t appear in production — but the team used it during the design phase to prototype three different pipeline architectures before committing to code. It earned its keep in week 1 and retired gracefully.</li></ul><p><strong>This is the point:</strong> these tools aren’t competing. They’re solving different problems at different layers. The question isn’t “ADK or LangChain?” — it’s “which combination covers my stack?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s72d9KyG3WQZGIYzgR2Q4g.png" /></figure><h3>When to Use Each</h3><p><strong>Use Google ADK if you want:</strong></p><ul><li>Production-grade multi-agent systems with explicit orchestration</li><li>Parallel agent execution with structured coordination</li><li>Deployment to Google Cloud / Vertex AI</li></ul><p><strong>Use LangChain if you want:</strong></p><ul><li>Rapid LLM integrations with broad API connectivity</li><li>Flexible RAG pipelines and retrieval systems</li><li>A component library to build custom agent tools</li></ul><p><strong>Use LangGraph if you need:</strong></p><ul><li>Complex agent control flow with loops, branching, and cycles</li><li>State persistence and human-in-the-loop workflows</li><li>Production orchestration on top of LangChain components</li></ul><p><strong>Use LangFlow if you want:</strong></p><ul><li>Visual prototyping without writing code</li><li>Quick demos and experimentation</li><li>A learning tool for the LangChain ecosystem</li></ul><p><strong>Use LangSmith if you need:</strong></p><ul><li>Production monitoring and prompt tracing</li><li>Regression testing for prompt and model changes</li><li>Debugging agent failures with full execution replay</li></ul><h3>The Bigger Trend</h3><p>Agent systems are evolving fast, and the direction is unmistakable.</p><p>Early frameworks focused on <strong>prompt orchestration</strong> — string together a few LLM calls, maybe add retrieval, ship it. That era is ending. Not because prompt engineering doesn’t matter, but because prompt engineering alone doesn’t produce systems that are <strong>reliable, observable, and maintainable at scale.</strong></p><p>The teams I see succeeding in production share a common pattern: they treat AI agents like distributed systems, not like chatbots. They adopt the same engineering principles that made microservices reliable — explicit interfaces, independent scaling, structured error handling, comprehensive monitoring — and apply them to agentic workflows.</p><p>Modern production systems demand:</p><ul><li><strong>Reliability</strong> — Agents that recover from failures instead of crashing silently</li><li><strong>Observability</strong> — Full visibility into every decision an agent makes</li><li><strong>Deterministic workflows</strong> — Explicit control flow, not “let the LLM figure it out”</li><li><strong>Structured outputs</strong> — Typed, validated responses that downstream systems can trust</li><li><strong>Scalable infrastructure</strong> — Deployment patterns that survive real traffic</li><li><strong>Auditability</strong> — The ability to trace any output back to the exact configuration that produced it</li></ul><p>This is why the industry is converging on <strong>explicit orchestration frameworks</strong> like ADK and LangGraph, paired with <strong>observability platforms</strong> like LangSmith. The stack is maturing. The tools are specializing. And the teams that understand the layers are shipping faster than the teams still searching for the one framework that does everything.</p><p>The future of AI agents isn’t smarter prompts.</p><p><strong>It’s better engineering.</strong></p><h3>References</h3><p>Google ADK Documentation</p><p><a href="https://cloud.google.com/vertex-ai/docs/agent-builder">https://cloud.google.com/vertex-ai/docs/agent-builder</a></p><p>Google ADK GitHub</p><p><a href="https://github.com/google/adk">https://github.com/google/adk</a></p><p>LangChain Documentation</p><p><a href="https://python.langchain.com/">https://python.langchain.com</a></p><p>LangGraph Documentation</p><p><a href="https://langchain-ai.github.io/langgraph">https://langchain-ai.github.io/langgraph</a></p><p>LangFlow Documentation</p><p><a href="https://docs.langflow.org/">https://docs.langflow.org</a></p><p>LangSmith Documentation</p><p><a href="https://docs.smith.langchain.com/">https://docs.smith.langchain.com</a></p><p>Google AI Agents Whitepaper</p><p><a href="https://ai.google.dev/">https://ai.google.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60ed7b8e2d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Building AI Agents. Start Designing AI Systems]]></title>
            <link>https://diegohurtadoo.medium.com/stop-building-ai-agents-start-designing-ai-systems-d5a6cb4911a5?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a6cb4911a5</guid>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-03-04T14:01:02.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Production-Ready Multi-Agent System with Google ADK</h3><h4>Most agent demos fail at the exact moment they become useful.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVBJim3C9dAXOkT6LpbSdw.png" /></figure><p>The first request works.</p><p>The second requirement exposes the architecture.</p><p><strong>That is when the real questions show up:</strong></p><ul><li>How do you keep latency under control as capabilities grow?</li><li>How do you prevent malformed outputs from breaking downstream systems?</li><li>How do you ground answers without overengineering retrieval?</li><li>How do you debug a bad run after the fact?</li><li>How do you stop an agent from crossing a business boundary it should never cross?</li></ul><p>Those are not prompt questions.</p><p>They are systems questions.</p><p>So instead of building one big do-everything agent, I built a <strong>production-minded multi-agent system</strong> with <strong>Google ADK</strong>.</p><p>The project I started from happened to be a travel planner. But the architecture is much broader than that. The same pattern applies to internal copilots, document workflows, analytics assistants, research systems, support automation, and agentic back-office tools.</p><p>This post is really about one reusable pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECzSJ_j-fXxlb545eINj5g.png" /></figure><p><em>Figure 1: Hero architecture</em></p><p>The One-Sentence Architecture</p><h3>Route → Research in parallel → Synthesize → Validate → Repair → Persist artifacts</h3><p>That is the system.</p><blockquote><strong><em>The jump from demo to product is not a better prompt. It is better control flow.</em></strong></blockquote><p>I use one mental model to explain the design:</p><ul><li>the user request is the <strong>order ticket</strong></li><li>the router is the <strong>expeditor</strong></li><li>specialist agents are <strong>kitchen stations</strong></li><li>grounding is the <strong>walk-in pantry</strong></li><li>the schema validator is the <strong>plating standard</strong></li><li>the event log is the <strong>kitchen camera</strong></li></ul><p>Production AI systems are much closer to a kitchen than a magic trick.</p><h3>Stop building one big agent</h3><p>A single agent looks simple on a whiteboard.</p><p>In practice, it becomes a pile of mixed responsibilities:</p><ul><li>intent classification</li><li>retrieval</li><li>tool calling</li><li>formatting</li><li>safety</li><li>business constraints</li><li>error recovery</li></ul><p>That usually works for a prototype.</p><p>It falls apart the moment you add reliability requirements.</p><p>The first staff-level shift is this:</p><h3>Separate control flow from task execution.</h3><p>The router should decide.</p><p>Specialists should specialize.</p><p>The synthesizer should assemble.</p><p>The validator should judge.</p><p>The repair loop should fix structure, not redo work.</p><blockquote><strong><em>When one agent owns everything, no part of the system is truly designed.</em></strong></blockquote><h3>Pattern 1: Route first, specialize second</h3><p>Every production multi-agent system needs a control plane.</p><p>That starts with a router.</p><p>The router’s job is not to solve the entire problem. Its job is to classify the request, extract structure, and determine what kind of downstream work should happen.</p><p>Once that intent is clear, the workflow fans out into specialist agents.</p><p>Here’s what that topology looks like in practice:</p><pre>root_agent = SequentialAgent(<br>    name=&quot;MultiAgentWorkflow&quot;,<br>    sub_agents=[<br>        router_agent,<br>        ParallelAgent(sub_agents=[<br>            analysis_agent,<br>            retrieval_agent,<br>            computation_agent,<br>            execution_agent<br>        ]),<br>        synthesis_agent<br>    ]<br>)</pre><p>This small structure encodes the entire control flow:</p><p>a router stage, parallel execution layer, and a final synthesis step.</p><p>The important part is not the syntax.</p><p>The important part is that control flow is explicit.</p><p>In one system, those specialists might be domain-specific. In another, they might be more general:</p><ul><li>Analysis Agent</li><li>Retrieval Agent</li><li>Computation Agent</li><li>Execution Agent</li></ul><p>The important part is not the names.</p><p>The important part is that each specialist has a bounded responsibility and a clean output.</p><p>This matters even more once you introduce parallel execution. If multiple branches run at once, each branch needs its own output channel. Shared-state parallelism without strict boundaries is how you get collisions and debugging sessions that never end.</p><p>One nuance is worth stating clearly:</p><p>In many first versions, the router is used to structure intent before it is used to skip work. That is a reasonable maturity step. It keeps the graph explicit and makes conditional execution an obvious next hardening step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0TfliL5ogZz3aykxDR-Iw.png" /></figure><p><em>Figure 2: Current vs Future routing</em></p><blockquote><strong><em>A router is not there to sound smart. It is there to make the rest of the system cheaper, faster, and easier to reason about.</em></strong></blockquote><h3>Pattern 2: Parallelism is really an I/O problem</h3><p>Parallel architecture looks great in diagrams.</p><p>It only matters if the work can actually overlap.</p><p>That is why one of the most important design choices in a multi-agent system is the tool boundary.</p><p>If specialist agents are blocked on sequential I/O, parallelism is mostly decorative.</p><p>The fix is straightforward:</p><ul><li>use async tool calls</li><li>wrap retries around unstable boundaries</li><li>make development-time dependencies deterministic</li></ul><p>This is where production design starts to feel different from demo design.</p><p>You stop asking, “Can the model call a tool?”</p><p>You start asking:</p><ul><li>Can multiple agents call tools without blocking each other?</li><li>What happens when a dependency fails on the first attempt?</li><li>Can I reproduce tool behavior locally without waiting on external systems?</li><li>Can I test the workflow without a network dependency?</li></ul><p>Async execution makes the branches overlap.</p><p>Retries make boundaries resilient.</p><p>Mock services make the system testable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwjQGMgjN-w74H3O0u8qiw.png" /></figure><p><em>Figure 3: Tooling + async execution</em></p><blockquote><strong><em>Parallel agents do not save you if the tool layer is still sequential.</em></strong></blockquote><h3>Pattern 3: Grounding should be boring</h3><p>One of the easiest ways to build a brittle agent is to let it improvise from the model prior.</p><p>That looks intelligent until you inspect the details.</p><p>So production systems need grounding.</p><p>The good news is grounding does not have to begin with a heavyweight vector stack. A lot of teams overcomplicate this too early.</p><p>A practical first version is simple:</p><ul><li>ingest a trusted knowledge source</li><li>chunk it with overlap</li><li>index it with a straightforward retrieval method</li><li>return results with provenance</li></ul><p>The overlap matters more than people think. It prevents meaning from being cut at chunk boundaries.</p><p>The strategic point is bigger:</p><h3>Put retrieval behind a stable tool boundary.</h3><p>Start simple, evolve later. Swap backends without rewriting the agent layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FBQT4_A-golQOBDh_wWAQ.png" /></figure><p><em>Figure 4: Grounding / retrieval pipeline</em></p><blockquote><strong><em>Grounding is not about making the model smarter. It is about making the system less guessy.</em></strong></blockquote><h3>Pattern 4: Contracts before creativity</h3><p>The moment an LLM output becomes an artifact, it needs a contract.</p><p>Not a vibe.</p><p>Not “mostly JSON.”</p><p>A contract.</p><p>This is where agent systems quietly fail. Outputs look structured enough at first glance, then downstream code spends the rest of its life compensating for missing fields and shape drift.</p><p>A schema boundary forces discipline:</p><ul><li>define the output shape explicitly</li><li>validate it before treating it as real</li><li>attach operational metadata for traceability</li></ul><p>Then comes the staff-level lesson:</p><h3>Valid does not always mean complete</h3><p>A schema can validate successfully and still lose useful information.</p><p>That happens when extra keys are tolerated and critical fields fall back to defaults. The structure passes. The substance leaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5b4DttSwuwPBNdqSF22w2Q.png" /></figure><p><em>Figure 5: Valid ≠ complete</em></p><blockquote><strong><em>A passing validator is not the same thing as a complete result.</em></strong></blockquote><h3>Pattern 5: Repair the structure, not the work</h3><p>The workflow should not assume the first synthesized output will always validate.</p><p>Instead, follow a validate-and-repair loop:</p><ol><li>run the expensive research and tool steps once</li><li>extract the structured candidate</li><li>validate it against the schema</li><li>on failure, repair using the validation error context</li><li>re-validate</li></ol><p>Structure failures are cheaper than research failures.</p><p>Repair the plate.</p><p>Do not recook the meal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zk5Fvj5PP3yeyRxq6d3UvA.png" /></figure><p><em>Figure 6: Repair loop</em></p><blockquote><strong><em>The fastest retry is the one that does not repeat the expensive step.</em></strong></blockquote><h3>Pattern 6: If you can’t replay it, you can’t operate it</h3><p>A lot of agent demos stop at: “The model answered.”</p><p>That is not enough.</p><p>A real system needs to tell you:</p><ul><li>what happened</li><li>why it happened</li><li>which configuration produced it</li><li>how to reproduce it later</li></ul><p>So treat artifacts as first-class outputs:</p><ul><li>config-driven behavior</li><li>a stable run identifier</li><li>raw outputs</li><li>final validated outputs</li><li>repair artifacts when needed</li><li>event logs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcvoDcy_CpYx9MuYz9Bhmw.png" /></figure><p><em>Figure 7: Reproducibility + artifacts</em></p><blockquote><strong><em>Observability is not extra credit for agent systems. It is the product.</em></strong></blockquote><h3>Final takeaway</h3><p>Stop treating agents like prompts. Start treating them like systems.</p><p>The reusable pattern is architectural:</p><h3>Route → Research in parallel → Synthesize → Validate → Repair → Persist artifacts</h3><p>Not as magic.</p><p>As kitchens.</p><h3>References &amp; Further Reading</h3><ol><li>Google Developers Blog — <em>A Developer’s Guide to Multi-Agent Patterns in ADK</em></li><li>Google ADK Documentation — Workflow Agents</li><li>Lewis et al. (2020) — <em>Retrieval-Augmented Generation</em></li><li>Pydantic Documentation</li><li>Tenacity Documentation</li><li>Google SRE Book — Monitoring Distributed Systems</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a6cb4911a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction Using Machine Learning Models]]></title>
            <link>https://diegohurtadoo.medium.com/customer-churn-prediction-using-machine-learning-models-b088390ce0f0?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b088390ce0f0</guid>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[churn-rate]]></category>
            <category><![CDATA[churn]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 15:15:22 GMT</pubDate>
            <atom:updated>2023-05-07T19:51:37.296Z</atom:updated>
            <content:encoded><![CDATA[<p>Predict whether a customer will churn using machine learning models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko7vODMIPuIwRIvdD1KT5g.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><p>The problem of churn prediction in machine learning involves predicting which customers are likely to stop using a product or service. Churn prediction is an important problem for businesses, as losing customers can have a significant impact on revenue and profitability.</p><p>The problem of churn prediction can be approached as a binary classification problem, where the goal is to predict whether a customer will churn or not based on various features such as demographics, usage behavior, transaction history, and customer feedback. The challenge in churn prediction is to identify the most important features that contribute to customer churn and to build a predictive model that can accurately predict churn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2Uxb69W7VmSIhr3_skrZUA.png" /><figcaption>Customer Churn Map — Diego Hurtado</figcaption></figure><p>Customer churn is a critical problem for telco providers as it can significantly impact their revenue and profitability. Losing customers to competitors can decrease revenue and market share, as well as increase costs associated with acquiring new customers.</p><p>To address this problem, telco providers need to identify the factors contributing to customer churn and take proactive measures to retain customers at risk of churning. This requires the analysis of various data sources, such as customer demographic information, usage patterns, billing history, and customer service interactions.</p><p>The approach to solving the Customer Churn Prediction problem can be divided into several steps:</p><h3>Data Collection</h3><p>Collect the relevant data required to make predictions. In this case, the data could include information such as customer demographics, usage patterns, billing history, and customer service interactions.</p><p>In this case, the dataset that I am using is Customer Churn Prediction 2020 from the Kaggle competition</p><p>The dataset has the following features:</p><ol><li>“state”, <em>string</em>. 2-letter code of the US state of customer residence</li><li>“account_length”, <em>numerical</em>. For a number of months, the customer has been with the current telco provider</li><li>“area_code”, <em>string</em>=”area_code_AAA” where AAA = 3 digit area code.</li><li>“international_plan”, <em>(yes/no)</em>. The customer has an international plan.</li><li>“voice_mail_plan”, <em>(yes/no)</em>. The customer has a voicemail plan.</li><li>“number_vmail_messages”, <em>numerical</em>. A number of voice-mail messages.</li><li>“total_day_minutes”, <em>numerical</em>. Total minutes of day calls.</li><li>“total_day_calls”, <em>numerical</em>. Total minutes of day calls.</li><li>“total_day_charge”, <em>numerical</em>. The total charge of day calls.</li><li>“total_eve_minutes”, <em>numerical</em>. Total minutes of evening calls.</li><li>“total_eve_calls”, <em>numerical</em>. A total number of evening calls.</li><li>“total_eve_charge”, <em>numerical</em>. The total charge for evening calls.</li><li>“total_night_minutes”, <em>numerical</em>. Total minutes of night calls.</li><li>“total_night_calls”, <em>numerical</em>. A total number of night calls.</li><li>“total_night_charge”, <em>numerical</em>. The total charge of night calls.</li><li>“total_intl_minutes”, <em>numerical</em>. Total minutes of international calls.</li><li>“total_intl_calls”, <em>numerical</em>. A total number of international calls.</li><li>“total_intl_charge”, <em>numerical</em>. The total charge of international calls</li><li>“number_customer_service_calls”, is <em>numerical</em>. A number of calls to customer service</li><li>“churn”, <em>(yes/no)</em>. Customer churn — target variable.</li></ol><p>One of the main challenges in customer churn prediction is identifying the right features or variables that can accurately predict churn. For example, customer demographics such as age, gender, and income may not be the best predictors of churn. Instead, variables such as the length of the customer’s relationship with the telco provider, the frequency of customer service interactions, and the types of services used may be more informative.</p><h3>Data Cleaning and Preparation:</h3><p>This step involves cleaning the data and preparing it for analysis. The data should be checked for missing values, outliers, and inconsistencies. The data should also be transformed into a format that can be used for analysis, such as a structured table or matrix.</p><h3>Feature Engineering:</h3><p>Feature engineering is the process of creating new variables that can improve the accuracy of the model. For example, variables such as the length of the customer’s relationship with the telco provider or the frequency of customer service interactions may be useful in predicting churn.</p><h3>Model Selection:</h3><p>Another challenge is selecting the appropriate machine learning algorithm to make accurate predictions. There are many different algorithms to choose from, each with its own strengths and weaknesses. The choice of algorithm will depend on the nature of the data, the amount of data available, and the desired level of accuracy.</p><p>There are many different machine learning algorithms that can be used to predict churn. Some popular options include logistic regression, decision trees, random forests, and neural networks. The choice of model will depend on the nature of the data, the amount of data available, and the desired level of accuracy.</p><h4>LSTM Classifier for Churn Prediction | %96 Accuracy</h4><p>An LSTMClassifier can be used to predict churn in a telco provider by processing the sequential data of customer interactions and behaviors over time. The LSTMClassifier architecture can capture and learn from the long-term dependencies in the customer data and has proven effective in solving time-series problems, such as churn prediction.</p><p>I have a Kaggle notebook <a href="https://www.kaggle.com/code/diegohurtadoo/telco-churn-prediction-using-lstm-96-accuracy">here</a>:</p><p><a href="https://www.kaggle.com/code/diegohurtadoo/telco-churn-prediction-using-lstm-96-accuracy">https://www.kaggle.com/code/diegohurtadoo/telco-churn-prediction-using-lstm-96-accuracy</a></p><pre># Define the function to create the LSTM model outside the class<br>def create_lstm_model(input_shape):<br>    model = Sequential()<br>    model.add(LSTM(64, input_shape=input_shape, return_sequences=True))<br>    model.add(Dropout(0.2))<br>    model.add(LSTM(32))<br>    model.add(Dropout(0.2))<br>    model.add(Dense(1, activation=&#39;sigmoid&#39;))<br>    model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>    return model<br><br># Define the LSTMClassifier class<br>class LSTMClassifier:<br>    <br>    &quot;&quot;&quot;<br>    <br>    Class Created by: Diego Gustavo Hurtado Olivares<br>    <br>    LSTMClassifier is a class that provides an easy-to-use interface for training, evaluating, <br>    and tuning Long Short-Term Memory (LSTM) models for binary classification tasks.<br>    <br>    This class includes methods for preprocessing data, building and training the LSTM model,<br>    evaluating the model using various metrics, plotting the training history and ROC curve,<br>    predicting new instances, saving and loading the model, and obtaining feature importances <br>    using permutation importance. It also provides support for hyperparameter tuning, K-fold<br>    cross-validation, and early stopping.<br>    <br>    Example usage:<br>    --------------<br>    <br>    # Initialize the LSTMClassifier with your data<br>    lstm_classifier = LSTMClassifier(data)<br>    <br>    # Preprocess the data<br>    lstm_classifier.preprocess_data()<br>    <br>    # Build the LSTM model<br>    lstm_classifier.build_model()<br>    <br>    # Train the model<br>    history = lstm_classifier.train_model(epochs=50, batch_size=32)<br>    <br>    # Evaluate the model<br>    lstm_classifier.evaluate_model()<br>    <br>    # Plot the training history and ROC curve<br>    lstm_classifier.plot_training_history(history)<br>    lstm_classifier.plot_roc_curve()<br>    <br>    # Predict new instances<br>    y_pred = lstm_classifier.predict(X_new)<br>    <br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, data):<br>        # Initialize the data path and variables to store the data, train and test sets, and model<br>        # self.data_path = data_path<br>        self.data = data<br>        self.X_train = None<br>        self.X_test = None<br>        self.y_train = None<br>        self.y_test = None<br>        self.scaler = None<br>        self.model = None<br>        <br>    def load_data(self):<br>        # Load the data from the specified path<br>        self.data = pd.read_csv(self.data_path)<br>        <br>    def preprocess_data(self):<br>        # Split the data into features (X) and target (y)<br>        X = self.data.drop([&quot;churn&quot;], axis=1)<br>        y = self.data[&quot;churn&quot;]<br>        <br>        # Split the data into train and test sets<br>        self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>        <br>        # Standardize the features<br>        self.scaler = StandardScaler()<br>        self.X_train = self.scaler.fit_transform(self.X_train)<br>        self.X_test = self.scaler.transform(self.X_test)<br>        <br>        # Reshape the features to be 3D arrays suitable for input into an LSTM model<br>        self.X_train = np.reshape(self.X_train, (self.X_train.shape[0], 1, self.X_train.shape[1]))<br>        self.X_test = np.reshape(self.X_test, (self.X_test.shape[0], 1, self.X_test.shape[1]))<br>        <br>    def build_model(self):<br>        # Create a sequential model with two LSTM layers, two dropout layers, and a dense output layer<br>        self.model = Sequential()<br>        self.model.add(LSTM(64, input_shape=(1, self.X_train.shape[2]), return_sequences=True))<br>        self.model.add(Dropout(0.2))<br>        self.model.add(LSTM(32))<br>        self.model.add(Dropout(0.2))<br>        self.model.add(Dense(1, activation=&#39;sigmoid&#39;))<br>        # Compile the model with the binary crossentropy loss function, the Adam optimizer, and accuracy metrics<br>        self.model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br>        <br>    def early_stopping(self, patience=10, restore_best_weights=True):<br>        return EarlyStopping(monitor=&#39;val_loss&#39;, patience=patience, restore_best_weights=restore_best_weights)<br>    <br>    def custom_metric(self, y_true, y_pred):<br>        # Example: Implement the balanced accuracy metric<br>        balanced_accuracy = balanced_accuracy_score(y_true, y_pred)<br>        return balanced_accuracy<br>    <br>        <br>    def evaluate_model(self, use_custom_metric=True):<br>        y_pred_prob = self.model.predict(self.X_test)<br>        y_pred_rounded = np.round(y_pred_prob)<br>        y_pred = y_pred_rounded.astype(int).ravel()<br><br>        # Evaluation metrics<br>        confusion_mat = confusion_matrix(self.y_test, y_pred)<br>        classification_re = classification_report(self.y_test, y_pred)<br>        accuracy = accuracy_score(self.y_test, y_pred)<br>        f1 = f1_score(self.y_test, y_pred)<br>        recall = recall_score(self.y_test, y_pred)<br><br>        # Print the evaluation metrics<br>        print(&quot;Confusion Matrix:&quot;)<br>        print(confusion_mat)<br>        print(&quot;Classification Report:&quot;)<br>        print(classification_re)<br>        print(&quot;Accuracy:&quot;, accuracy)<br>        print(&quot;F1 Score:&quot;, f1)<br>        print(&quot;Recall:&quot;, recall)<br><br>        if use_custom_metric:<br>            custom_metric_value = self.custom_metric(self.y_test, y_pred)<br>            print(&quot;Custom Metric Value (Balanced Accuracy):&quot;, custom_metric_value)<br>        <br>    def plot_training_history(self, history):<br>        # Plot training &amp; validation accuracy values<br>        plt.figure(figsize=(12, 5))<br>        plt.plot(history.history[&#39;accuracy&#39;])<br>        plt.plot(history.history[&#39;val_accuracy&#39;])<br>        plt.title(&#39;Model accuracy&#39;)<br>        plt.ylabel(&#39;Accuracy&#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>        # Plot training &amp; validation loss values<br>        plt.figure(figsize=(12, 5))<br>        plt.plot(history.history[&#39;loss&#39;])<br>        plt.plot(history.history[&#39;val_loss&#39;])<br>        plt.title(&#39;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>    def plot_roc_curve(self):<br>        y_pred_prob = self.model.predict(self.X_test).ravel()<br>        fpr, tpr, thresholds = roc_curve(self.y_test, y_pred_prob)<br>        auc_score = auc(fpr, tpr)<br><br>        plt.figure(figsize=(10, 6))<br>        plt.plot(fpr, tpr, label=&#39;ROC curve (area = %0.2f)&#39; % auc_score)<br>        plt.plot([0, 1], [0, 1], &#39;k--&#39;)<br>        plt.xlim([0.0, 1.0])<br>        plt.ylim([0.0, 1.05])<br>        plt.xlabel(&#39;False Positive Rate&#39;)<br>        plt.ylabel(&#39;True Positive Rate&#39;)<br>        plt.title(&#39;Receiver Operating Characteristic (ROC)&#39;)<br>        plt.legend(loc=&quot;lower right&quot;)<br>        plt.show()<br>        <br>    def predict(self, X):<br>        # Preprocess input<br>        X_scaled = self.scaler.transform(X)<br>        X_reshaped = np.reshape(X_scaled, (X_scaled.shape[0], 1, X_scaled.shape[1]))<br>        <br>        # Make predictions<br>        y_pred_prob = self.model.predict(X_reshaped)<br>        y_pred_rounded = np.round(y_pred_prob)<br>        y_pred = y_pred_rounded.astype(int).ravel()<br>        return y_pred<br><br>    def save_model(self, model_path):<br>        self.model.save(model_path)<br><br>    def load_model(self, model_path):<br>        self.model = load_model(model_path)<br><br>    def get_model_summary(self):<br>        self.model.summary()<br>        <br>    def tune_hyperparameters(self, param_grid, cv=5, search_type=&#39;grid&#39;, n_iter=None, random_state=42):<br>        input_shape = (1, self.X_train.shape[2])<br><br>        # Wrap the model for use with scikit-learn<br>        model = KerasClassifier(build_fn=lambda: create_lstm_model(input_shape), verbose=0)<br><br>        if search_type == &#39;grid&#39;:<br>            search = GridSearchCV(estimator=model, param_grid=param_grid, cv=cv)<br>        elif search_type == &#39;random&#39;:<br>            if n_iter is None:<br>                raise ValueError(&quot;n_iter must be specified for random search.&quot;)<br>            search = RandomizedSearchCV(estimator=model, param_distributions=param_grid, cv=cv,<br>                                        n_iter=n_iter, random_state=random_state)<br><br>        search_result = search.fit(self.X_train, self.y_train)<br><br>        # Print the best score and best parameters<br>        print(&quot;Best score: %f using %s&quot; % (search_result.best_score_, search_result.best_params_))<br>        return search_result<br><br>    def k_fold_cross_validation(self, n_splits=5, epochs=50, batch_size=32):<br>        input_shape = (1, self.X_train.shape[2])<br><br>        # Define a function to create the model with the proper input shape<br>        def create_model():<br>            return create_lstm_model(input_shape)<br><br>        # Wrap the model for use with scikit-learn<br>        model = KerasClassifier(build_fn=create_model, epochs=epochs, batch_size=batch_size, verbose=0)<br><br>        # Perform k-fold cross-validation<br>        kfold = KFold(n_splits=n_splits, shuffle=True, random_state=42)<br>        results = cross_val_score(model, self.X_train, self.y_train, cv=kfold)<br><br>        # Print the mean and standard deviation of the cross-validation scores<br>        print(&quot;Cross-Validation Accuracy: %.2f%% (%.2f%%)&quot; % (results.mean() * 100, results.std() * 100))<br><br>    def model_to_json(self):<br>        model_json = self.model.to_json()<br>        return model_json<br><br>    def json_to_model(self, model_json):<br>        self.model = model_from_json(model_json)<br>        <br>    def predict_proba(self, X):<br>        X_scaled = self.scaler.transform(X)<br>        X_reshaped = np.reshape(X_scaled, (X_scaled.shape[0], 1, X_scaled.shape[1]))<br>        y_pred_prob = self.model.predict(X_reshaped)<br>        return y_pred_prob<br><br>    def train_val_split(self, val_size=0.1, random_state=42):<br>        self.X_train, self.X_val, self.y_train, self.y_val = train_test_split(<br>            self.X_train, self.y_train, test_size=val_size, random_state=random_state)<br><br>        # Reshape X_val using the same number of features as in X_train and X_test<br>        self.X_val = np.reshape(self.X_val, (self.X_val.shape[0], 1, self.X_train.shape[2]))<br><br><br>    def learning_rate_reduction(self, factor=0.1, patience=10, min_lr=1e-5):<br>        return ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=factor, patience=patience, min_lr=min_lr)<br><br>    def train_model(self, epochs, batch_size, use_early_stopping=True, use_lr_reduction=True):<br>        callbacks = []<br>        if use_early_stopping:<br>            callbacks.append(self.early_stopping())<br>        if use_lr_reduction:<br>            callbacks.append(self.learning_rate_reduction())<br><br>        history = self.model.fit(self.X_train, self.y_train, epochs=epochs, batch_size=batch_size,<br>                                 validation_data=(self.X_test, self.y_test), callbacks=callbacks)<br>        return history<br>    <br>    def get_feature_importance(self, X, y, n_repeats=10, random_state=42):<br>        # Wrap the predict_proba method for use with sklearn&#39;s permutation_importance function<br>        def predict_proba_wrapped(X):<br>            return self.predict_proba(X)<br><br>        # Compute the permutation importance<br>        result = permutation_importance(predict_proba_wrapped, X, y, n_repeats=n_repeats,<br>                                        random_state=random_state, n_jobs=-1)<br><br>        # Combine the feature importances and their names into a dataframe and sort by importance<br>        feature_importance = pd.DataFrame({&#39;feature&#39;: self.data.drop([&quot;churn&quot;], axis=1).columns,<br>                                           &#39;importance&#39;: result.importances_mean,<br>                                           &#39;std&#39;: result.importances_std})<br><br>        feature_importance = feature_importance.sort_values(by=&#39;importance&#39;, ascending=False)<br><br>        return feature_importance</pre><p>LSTMClassifier is an effective approach for predicting customer churn in a telco provider by learning from the sequential data of customer interactions and behaviors over time. The LSTMClassifier architecture can capture and learn from the long-term dependencies in customer data and can be used to build accurate and reliable churn prediction models.</p><h4>Model evaluation</h4><p>The model will be evaluated using the test Accuracy criterion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*neGnH7iFpfmiuAQ3ZjSy5Q.png" /></figure><p>Model evaluation is an important step in the process of building a churn prediction model as it helps to determine the accuracy and reliability of the model. There are several methods for evaluating the performance of a churn prediction model, including:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WOD21EaVWtXZq7Bc5C1-Q.png" /><figcaption><em>Plot the training history — </em>Diego Gustavo Hurtado Olivares</figcaption></figure><p>Confusion Matrix: A confusion matrix is a table that summarizes the performance of a binary classification model. It shows the number of true positives (TP), false positives (FP), true negatives (TN), and false negatives (FN) predicted by the model. From this matrix, several evaluation metrics can be calculated, such as accuracy, precision, recall, and F1 score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_yG_LNNJVGCwPM7X48JRtA.png" /></figure><p>Receiver Operating Characteristic (ROC) Curve: The ROC curve is a plot of the true positive rate (TPR) against the false positive rate (FPR) at various classification thresholds. It provides a visual representation of the performance of the model and can be used to compare the performance of different models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*-9xlb5ywcgxUY4YPqT7tKg.png" /><figcaption>Diego Gustavo Hurtado Olivares</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Ol5Imouy1aYQwU08ZrUgsA.png" /></figure><p>Area Under the Curve (AUC): The AUC is the area under the ROC curve and provides a single number that summarizes the performance of the model. A higher AUC indicates better model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8oCUzffW7d0aqYqDwV6rVQ.png" /></figure><h4>Decision Tree Classifier</h4><p>In a Decision Tree Classifier for churn prediction, the input data consists of customer features. The model learns from this data and creates a decision tree that can predict whether a customer is likely to churn or not.</p><p>The decision tree consists of nodes and branches. The nodes represent decisions based on features in the input data, while the branches represent the possible outcomes of those decisions. At each node, the model selects the feature that provides the most information gain or reduction in impurity in the target variable, which in this case is the churn status.</p><p>A Decision Tree Classifier is an effective approach for predicting customer churn in a telco provider. It is easy to understand and interpret and can provide valuable insights into the factors that contribute to churn. By using feature selection techniques, we can identify the most relevant features for predicting churn and improve the accuracy and reliability of the model.</p><h4>Visual representations of decision trees</h4><p>Graphviz is an open-source graph visualization software that can be used to create visual representations of decision trees and other graphs.</p><p>The export_graphviz the method takes in a trained decision tree classifier, the output file path for the generated Graphviz file, and several other optional arguments that control the appearance of the generated graph, such as node colors and font styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko7vODMIPuIwRIvdD1KT5g.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joAlPv313q_89UrEkLIBXw.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zjsRpwemfxfYnbxsApAZng.png" /></figure><h4>Model Evaluation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*H_bqQaDJggbrjGeOLNXG3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-rmeKxWSmH2i-RFwrLbYXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OYQRdZXRUumdbpOLuXHZ9g.png" /></figure><h4>Random Forest Classifier</h4><p>Random Forest Classifier is a type of ensemble learning algorithm that can be used for churn prediction in a telco provider. It is a popular and powerful algorithm that combines the predictions of multiple decision trees to improve the accuracy and reliability of the model.</p><p>In a Random Forest Classifier for churn prediction, the input data consists of customer features. The model learns from this data and creates multiple decision trees, each using a random subset of the features and data. The final prediction is then made by aggregating the predictions of all the individual trees.</p><p>Random Forest Classifier is an effective approach for predicting customer churn in a telco provider. It is able to handle a large number of features and can capture complex interactions between features. By using feature selection techniques, we can identify the most relevant features for predicting churn and improve the accuracy and reliability of the model.</p><p>I am building a Random Forest classifier with 1 tree to generate a chart of the three to predict churn</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZBWWoqX44036bqW4VuO3A.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><h4>Feature Importances</h4><p>Feature importance in machine learning can help in churn prediction by identifying the factors that have the most influence on customer churn. By understanding which features are most important, businesses can focus their retention efforts on addressing the specific issues that are driving customer behavior.</p><p>For example, if a machine learning model identifies that the length of time a customer has been with a company is the most important feature in predicting churn, a business might focus on creating loyalty programs or other incentives that encourage long-term customer relationships.</p><p>Alternatively, if the model identifies that customer service calls are the most important feature, a business might focus on improving their customer service response times and quality to reduce customer dissatisfaction and prevent churn.</p><p>By prioritizing efforts based on feature importance, businesses can be more efficient and effective in retaining their customers. This approach can lead to better customer satisfaction, increased loyalty, and ultimately, higher revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zmwnfkd7rDqvqmXlwWp8wA.png" /></figure><p>feature_importances_ is an attribute of the Random Forest Classifier in scikit-learn that provides information about the relative importance of each feature in the model for predicting the target variable. The attribute returns an array of importance scores, with each score representing the relative importance of the corresponding feature in the input data.</p><p>The feature importance score is calculated by the Random Forest Classifier based on the reduction in impurity achieved by splitting on a particular feature. Features that result in higher impurity reduction are assigned higher importance scores, as they are more informative for predicting the target variable.</p><h4>Permutation Importance</h4><p>permutation_importance is a method from the sklearn.inspection a module that can be used to calculate the feature importances of a Random Forest Classifier using a permutation-based method. This method is an alternative to the traditional impurity-based method used by feature_importances_, which may not capture the full range of interactions between features.</p><p>The permutation_importance the method works by randomly permuting the values of each feature in the input data and measuring the resulting decrease in model performance. Features that result in a larger decrease in performance after permutation are considered more important, as they contribute more to the model&#39;s predictive power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-aG17Y9dzNSdqGuPM32a5w.png" /></figure><h4>Visual representations of decision trees in Random Forest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iX7VFtO1XmKuNhzk4ddg7A.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><h4>Model Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6zIAY_X9aUHFkEi4eUC_xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SbKBoHhlvJAKfgRROQrhqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Q9v6m_4A3LEU3gtGOh6L-g.png" /></figure><h4>AdaBoost Classifier</h4><p>AdaBoost (short for Adaptive Boosting) is a machine learning algorithm that is commonly used in binary classification problems, including churn prediction. The algorithm works by combining multiple weak classifiers to create a strong classifier that can accurately predict whether a customer is likely to churn or not.</p><p>AdaBoost algorithm can be used to identify the most important features that contribute to customer churn and to create a highly accurate prediction model that can be used to reduce customer churn and improve customer retention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fk2oKJxzLdqi2gJyRHP_GQ.png" /><figcaption>Visual representations of decision trees for Churn Prediction — Diego Hurtado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*a_350MfJu_S_yPAP2cK09A.png" /></figure><h4>Model Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jnCNTPcp9nim5D4IZ1warw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wYjAbryCWz7wGdg_EjbyQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NOCFVbDJs5W3PYvDY4RJ-g.png" /></figure><h4>XGBoost (Extreme Gradient Boosting) Classifier</h4><p>Like other boosting algorithms, XGBoost trains multiple weak models (decision trees) sequentially and iteratively. In each iteration, the algorithm tries to correct the errors made by the previous models by fitting a new model to the residual errors. The final prediction is then obtained by summing the predictions of all the weak models.</p><p>In churn prediction, XGBoost can be used to predict whether a customer is likely to churn based on various customer features such as age, gender, usage behavior, and transaction history. The algorithm can handle both categorical and numerical features, and can also handle missing data. The feature importance can also be easily calculated using XGBoost, which can help identify the most important features that contribute to customer churn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*J75Vu-5yjyLpPl8MCFbUTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlyTQoB-7iZmlm8wV6vS-Q.png" /><figcaption>Feature Importance Plot using XGBoost — Diego Hurtado</figcaption></figure><p>XGBoost Classifier doesn’t generate a single decision tree, but instead, it combines multiple decision trees to form a powerful ensemble model.</p><h4>Model Evaluation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7HWsxHJWde46uOJqr6R2Uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vEAJIrjyhKIW1rT5VpQwYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bEwOUtFfUqRc4oBgX0QBrQ.png" /></figure><h4>Churn Probability</h4><p>Churn probability is a measure of the likelihood that a customer will stop using a product or service, or “churn,” within a given time period. It is typically expressed as a percentage, with higher values indicating a higher likelihood of churn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVZlhVlHroRp25KD-C86jg.png" /><figcaption>Diego Hurtado</figcaption></figure><p>Churn probability is calculated using a predictive model, which takes into account various factors such as customer behavior, demographics, and historical data to determine the probability of churn. This model may be trained using machine learning algorithms, which can identify patterns and relationships within the data to make more accurate predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxKkLswUZ5N3LZAtGNOyAg.png" /><figcaption>Diego Hurtado</figcaption></figure><p>Churn probability is an important metric for businesses because it allows them to identify which customers are at high risk of leaving and take proactive steps to retain them. For example, a business might offer a special promotion or discount to a customer who has a high churn probability, or they might assign a customer service representative to follow up with them to address any issues they may be having.</p><p>By identifying high-risk customers and taking targeted retention actions, businesses can reduce their overall churn rates, increase customer loyalty, and ultimately improve their bottom line.</p><p><strong>It is important to give a churn probability for several reasons:</strong></p><p>Early identification of at-risk customers: By providing a churn probability, businesses can identify customers who are at high risk of leaving before they actually churn. This allows the business to intervene early and take proactive steps to retain the customer.</p><ol><li><strong>Targeted retention strategies:</strong> By knowing the probability of churn for each customer, businesses can tailor their retention strategies to be more effective. For example, if a customer has a high probability of churn, a business might offer them a special discount or another incentive to encourage them to stay.</li><li><strong>Resource allocation</strong>: By prioritizing efforts based on churn probability, businesses can allocate their resources more efficiently. For example, they can focus their retention efforts on high-value customers who are at high risk of leaving, rather than spreading their efforts evenly across all customers.</li><li><strong>Business planning: </strong>Churn probability can also inform long-term business planning. By understanding which factors contribute most to churn, businesses can adjust their product or service offerings, pricing, or other aspects of their business model to reduce customer churn and improve overall retention rates.</li></ol><p>Overall, providing a churn probability allows businesses to be more proactive in their customer retention efforts, which can lead to higher customer satisfaction, loyalty, and revenue.</p><h4>Geographic of Churn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*RYdVa6KRaPGurnooYRuPeg.png" /><figcaption>Customer Churn — Diego Hurtado</figcaption></figure><p>Geographic data can provide valuable insight into customer behavior and preferences, as well as the competitive landscape in a given market. By incorporating geographic data into churn prediction models, businesses can gain a more complete picture of their customers and make more accurate predictions about their behavior. This, in turn, can help them take targeted retention actions to reduce churn and improve overall customer satisfaction and loyalty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*7-XUyk6R6XwU6D_n1KG71g.png" /><figcaption>Number of Customer Service Calls by State — Diego Hurtado</figcaption></figure><p>Geographic data can also be used to identify potential new markets for a business or to tailor marketing and advertising campaigns to specific regions. For example, a business might use geographic data to identify areas with a high concentration of potential customers and create targeted campaigns to acquire new customers in those areas.</p><h3>Conclusion</h3><p>In conclusion, machine learning models can be used for churn prediction because they are capable of analyzing large volumes of data, identifying patterns and relationships within the data, and making accurate predictions about future behavior.</p><p>By using historical data on customer behavior and demographics, machine learning models can identify which customers are most likely to churn and what factors are driving their behavior. This information can then be used to create targeted retention strategies and prevent customer churn.</p><p>Additionally, machine learning models can be trained on new data as it becomes available, allowing them to adapt and improve their predictions over time. This can help businesses stay ahead of changing customer behavior and improve their overall customer retention rates.</p><p>Overall, machine learning models provide a powerful tool for businesses to predict and prevent customer churn, ultimately leading to increased customer loyalty, retention, and revenue.</p><h3>Contact Me:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QVgAQWwbqMiHURq6.jpg" /><figcaption>Bailey the Golden Retriever Sitting at a Desk (knowyourmeme, 2022)</figcaption></figure><p><a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a>Diego Gustavo Hurtado olivares</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74etRUtIB1ljvMfSKVCciQ.png" /><figcaption>Diego Hurtado <a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b088390ce0f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Taxi Fare in New York City]]></title>
            <link>https://diegohurtadoo.medium.com/predicting-taxi-fare-in-new-york-city-c5dd4aef55f4?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5dd4aef55f4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prédiction]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[new-york]]></category>
            <category><![CDATA[geospatial]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 05:39:05 GMT</pubDate>
            <atom:updated>2023-02-01T21:23:23.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Predict Taxi Fare in NY using Machine Learning Techniques</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6xnHYe__u8xiJWm_KsWgMw.png" /><figcaption>Visualization of 55,423,856 million records of trips in New York (Diego Hurtado)</figcaption></figure><h3>Introduction</h3><p>The general problem approach to predicting taxi fares in New York using machine learning techniques would involve using historical data on past taxi rides, such as pickup and drop-off locations, time of day, and weather conditions, to train a model.</p><p>The model would then be used to make predictions on future taxi fares based on input data, such as a requested pickup and drop-off location and time. Techniques such as regression analysis, decision trees, and neural networks could be used to train the model. Additionally, feature engineering and feature selection techniques may be used to identify the most relevant factors in determining taxi fares.</p><p>The goal of this approach is to create a model that can accurately predict taxi fares, which can be useful for both taxi companies and customers. That way, both taxi companies, and customers can benefit from knowing the price beforehand.</p><h3>Data</h3><p>The dataset is from Google Cloud Competition, hosted in partnership with Google Cloud and Coursera, the goal is to predict the fare amount (inclusive of tolls) for a taxi ride in New York City given the pickup and dropoff locations.</p><p>The dataset size is <strong>55,423,856 million records</strong> of trips with the fare cost, from <strong>2009–01–01</strong> to <strong>2015–06–30</strong>, with <strong>8 features</strong>: <strong>key, fare_amount, pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, and passenger_count.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*wMzcd5vi8inrYFsr75Tw6A.png" /><figcaption>Visualization of 55,423,856 million records of trips in New York (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*-EgK4ZxUwFwRqGH_5Gc9TA.png" /><figcaption>Visualization of 55,423,856 million records of trips in New York (Diego Hurtado)</figcaption></figure><h4>Data Cleaning</h4><p>Clean and preprocess the data to ensure that it is in a format that can be used to train the model.</p><p><strong>Removing outliers</strong></p><p>The process of removing outliers of coordinates that are in the water can be performed using a combination of data analysis and spatial analysis techniques. Here are the steps to perform this process:</p><ol><li>Identify the water bodies: First, you need to identify the water bodies that you want to remove the outliers from. This can be done by using a water body shapefile or by using a satellite imagery layer.</li><li>Extract the coordinates: Next, extract the coordinates of the data points that you want to remove the outliers from.</li><li>Perform spatial analysis: Use a spatial analysis tool, such as the “point in polygon” analysis, to determine if each coordinate is inside, outside, or on the boundary of the water bodies.</li><li>Identify the outliers: Outliers are coordinates that are located inside the water bodies. These coordinates can be identified by using the results of the spatial analysis.</li><li>Remove the outliers: Finally, you can remove the outliers from your dataset by deleting or excluding the coordinates that are located inside the water bodies.</li></ol><p>This process can be useful for applications where you want to remove incorrect or erroneous data points from your dataset, or to ensure that your data is spatially accurate. By removing outliers in the water, you can improve the quality and accuracy of your data and avoid potential errors in your analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*6xnHYe__u8xiJWm_KsWgMw.png" /><figcaption>Visualization of trips in New York (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*BFART1CVvC-oUDJgZOedZA.png" /><figcaption>Visualization of trips in New York (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNIeCU27WApkwhDt3yxP9Q.png" /><figcaption>Density Map of trips in New York (Diego Hurtado)</figcaption></figure><h3>Test Dataset:</h3><p>A test dataset is a set of data that is used to evaluate the performance of a machine-learning model. It is typically used to verify the accuracy and robustness of the model by comparing its predictions to known outcomes. The test dataset is only used to evaluate the final model and it should be representative of the real-world data that the model will encounter in production.</p><p>Input features for the test set (about 10K rows). Your goal is to predict fare_amount for each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*GyuJRxCrDwVT-qo6O1DsnA.png" /><figcaption>Visualization of trips of the test Dataset (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*1I2r0jakKXo22vDIbgi1cA.png" /><figcaption>Travel between the places with more travel distance — Diego Hurtado</figcaption></figure><h3>Feature engineering</h3><p>Identify the most relevant factors that determine taxi fares and create new features based on these factors. For example, you can calculate the distance between pickup and drop-off, or create a new feature to indicate whether it is a weekend or not.</p><h4>Create new features</h4><p>Creating new features that represent the interaction between two other features, such as the product of the distance and time of a taxi ride.</p><h4>Time</h4><ul><li>Year</li><li>Month</li><li>Day</li><li>Hour</li><li>Weekend</li><li>Rush Hour</li></ul><h4>Distance</h4><p>To calculate the distance we can use the travel distance from google API but since the dataset has millions of records the number of queries will be a lot, that&#39;s why I am using haversine distance:</p><h4>Haversine Distance</h4><p>The haversine distance is a measure of the great-circle distance between two points on a sphere, such as the Earth. It is often used to calculate the distance between two GPS coordinates (latitude and longitude).</p><p>The formula for the haversine distance is as follows:</p><p>d = 2 * R * asin(sqrt(sin²((lat2-lat1)/2) + cos(lat1) * cos(lat2) * sin²((lon2-lon1)/2)))</p><p><strong>Where:</strong></p><p>d is the distance between the two points R is the radius of the sphere (e.g., the Earth’s radius of approximately 6,371 km) lat1 and lat2 are the latitudes of the two points lon1 and lon2 are the longitudes of the two points</p><p>The haversine distance can be used to calculate the travel distance between two points on the surface of the Earth, taking into account the curvature of the Earth. This can be useful for applications such as determining the closest airport to a city, or the travel distance between two cities by air.</p><h4>Labeling the coordinates of cities of New York</h4><p>Labeling coordinates based on their location relative to a polygon involves determining if a given point (represented by its coordinates) is inside, outside, or on the boundary of the polygon. This process is commonly referred to as “point in polygon” analysis.</p><p>Check if the point is inside the polygon: This can be done using the “ray casting” method. A ray is drawn from the point to a point outside of the polygon. If the number of times the ray intersects with an edge of the polygon is odd, the point is inside the polygon. If the number of intersections is even, the point is outside of the polygon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h913mczjB5LvYQkOzrRnxw.png" /><figcaption>Labeling coordinates based on their location City</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*1xY2m69oOoZ2XVtkUUMAAg.png" /><figcaption>Taxi Trips in Manhattan — Diego Hurtado</figcaption></figure><p>This process can be useful for various applications, such as mapping and spatial analysis, where it is important to determine the relationship between points and polygons. The labeling can be used to group points into different regions or to determine if a point is located inside a particular area of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L55B-Cpovccm0Wbb1KfXw.png" /><figcaption>Trips by the hour in Manhattan — Diego Hurtado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cyx9PkSZlxruKkj5Tdulvg.png" /><figcaption>Trips by the hour in Manhattan — Diego Hurtado</figcaption></figure><h4><strong>Clustering the coordinates</strong></h4><p>Clustering the coordinates based on their locations is a process of grouping similar coordinates into clusters. This can be useful for various applications, such as spatial analysis, market segmentation, and pattern recognition.</p><p>This process can help you uncover patterns and relationships in the data that may not be immediately apparent. By grouping similar coordinates together, you can better understand the spatial distribution of your data and make informed decisions based on this information.</p><h3>EDA</h3><p>Exploratory Data Analysis (EDA) is an approach to analyzing and understanding data, primarily through visualizations and statistical summaries. It helps to identify patterns, anomalies, relationships, and other features in the data that may not be immediately obvious.</p><p>The goal of EDA is to gain an understanding of the data and to form hypotheses about it that can be tested in later stages of analysis. EDA is an iterative process, as insights gained from one stage can lead to additional questions and new ways of looking at the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAwPf-razyZ_zVY3gp_NMA.png" /><figcaption>Taxi Fare by the hour in Manhattan — Diego Hurtado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*D5sZAqw0GGvOZ0w0J960fg.png" /></figure><p>I created 4 categories of distances for the trips</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*A5EKuAng5Kx2IW_5EVNpUA.png" /></figure><p>Fare based on the number of Passengers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*8QTrKnsHPjgR4Uk7aTyDzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pl-cDTSAfOrdUsj7vVRYcg.png" /><figcaption>Trips Distribution by Hour</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*w5qdqmW6eUKE1-XUK61gMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Gpn-cfR1A7IdNAUgkWA2Ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*lh88Uca4f42ykCVJT_SQ_A.png" /></figure><h3>Machine Learning Model to predict Fare Cost</h3><p>There are several machine learning models that can be used to approach the problem of predicting taxi fares in New York, including linear regression, decision trees, random forests, and neural networks.</p><p><strong>Linear regression</strong> is a simple model that tries to find a linear relationship between the input features and the target variable (taxi fare). This model can work well for basic prediction problems, but may not capture more complex relationships in the data.</p><p>I wrote a blog about how to implement linear regression from the <a href="https://medium.com/@diego.hurtado.olivares/linear-regression-from-scratch-15bfd15dc2e"><strong>model Representation &amp; Implementation From Scratch in Python</strong></a></p><p><a href="https://medium.com/@diego.hurtado.olivares/linear-regression-from-scratch-15bfd15dc2e">Here you can find the link.</a></p><p><strong>Decision trees and random forests</strong> are more sophisticated models that can handle non-linear relationships in the data. They work by recursively dividing the data into smaller and smaller subsets based on the values of the input features until a prediction can be made for each subset.</p><p>Ultimately, the choice of model will depend on the complexity of the problem and the available data, and different models may need to be tried and compared to determine which one provides the best results.</p><h3>Random Forest Regressor</h3><p>I am using Random Forest Regressor because is a powerful machine learning algorithm that can be used to predict taxi fares for several reasons.</p><p>Random Forest Regressor is a suitable algorithm for predicting taxi fares because of its ability to handle non-linear relationships, missing values, high dimensional data, improved accuracy, and reduced overfitting.</p><h3>Evaluate the model</h3><p>Evaluating a model is the process of measuring its performance and accuracy in making predictions on new data. The goal is to determine whether the model is a good fit for the problem it was designed to solve.</p><h4>Evaluation Metrics</h4><p>Various metrics such as Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE), R-squared, and others can be used to evaluate the model’s performance and accuracy in making predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*KlA8cAXdot58ohs_zuuxhA.png" /></figure><h4>Visualizations</h4><p>Plotting the predicted values against the actual values helps to visually assess the model’s performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvGyX0soGjUNgUPZfoU6eQ.png" /></figure><h4>Evaluation Metrics by subcategory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAOo5U_by30otFIj26qazQ.png" /></figure><h3>Feature Importance</h3><p>Feature importance in Random Forest Regressor refers to the relative contribution of each feature to the prediction of the target variable. It provides insight into which features are most important in explaining the target variable, and how they are related to each other.</p><p>Random Forest Regressor calculates feature importance by aggregating the results of many decision trees. Each tree splits the data based on the most important feature and the process is repeated for each split. The feature importance is calculated by summing up the number of times each feature is selected for splitting across all the trees in the forest.</p><h4>Gini Importance</h4><p>This method calculates feature importance based on the decrease in impurity (measured by the Gini index) in the target variable after each split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpSw_ESyIVVRiotIkTNaLA.png" /></figure><h4>Permutation Importance</h4><p>This method calculates feature importance by randomly permuting the values of a feature and measuring the change in the model’s performance.</p><p>Feature importance provides valuable information that can be used to identify and remove redundant or irrelevant features, reduce overfitting, and improve the interpretability of the model. It is an important tool for understanding the relationships between the features and the target variable and can help to guide the direction of further analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srjZyUuKerp7rkaVbbNXcg.png" /></figure><h3>Contact Me:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QVgAQWwbqMiHURq6.jpg" /><figcaption>Bailey the Golden Retriever Sitting at a Desk (knowyourmeme, 2022)</figcaption></figure><p><a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a>Diego Gustavo Hurtado olivares</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74etRUtIB1ljvMfSKVCciQ.png" /><figcaption>Diego Hurtado <a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5dd4aef55f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression From Scratch]]></title>
            <link>https://diegohurtadoo.medium.com/linear-regression-from-scratch-15bfd15dc2e?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bfd15dc2e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-models]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 21:46:45 GMT</pubDate>
            <atom:updated>2023-01-15T21:46:45.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear Regression Model Representation &amp; Implementation From Scratch in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*GtEzGClEwN6JTMjVJB8PUA.png" /></figure><h3><strong>Introduction</strong></h3><p>The goal of this notebook is to implement linear regression from scratch using the mathematical Model Representation with Python. first, solving a simple linear regression with one variable, then solving a multiple linear regression model for housing prediction and comparing the results with the pre-build classes of <strong>sklearn</strong>, and finally using a more complex dataset: the House Prices — Advanced Regression Techniques to Predict sales prices.</p><p>All the process will be documented in a Jupiter Nootebook</p><h4>Linear Regression</h4><p>Linear regression is a statistical method used to model the linear relationship between a dependent variable, denoted as <strong>Y</strong>, and one or more independent variables, denoted as <strong>X</strong>. [1]</p><p>The goal of linear regression is to find the line of best fit that minimizes the distance between the points and the line.</p><p>The equation for a simple linear regression model with one predictor variable is:</p><p>Y = b0 + b1 * X</p><p>Where b0 is the intercept term and b1 is the coefficient for the predictor variable X.</p><p>In a multiple linear regression model with multiple predictor variables, the equation can be written as:</p><p>Y = b0 + b1 * X1 + b2 * X2 + … + bn * Xn</p><p>where X1, X2, …, Xn are the predictor variables and b1, b2, …, bn are the corresponding coefficients.</p><p>Linear regression can be used to make predictions about the value of the dependent variable given a set of predictor variables. The coefficients of the model can be estimated using a variety of techniques, such as the ordinary least squares method.</p><p>Linear regression is a widely used and well-understood technique that is simple to implement and easy to interpret. It is a powerful tool for understanding the relationships between different variables and can be used to make informed decisions.</p><p><strong>Inspirations:</strong></p><p>The model formulation , content, implementation are based on the <a href="https://www.coursera.org/specializations/machine-learning-introduction">Machine Learning Specialization</a> program created in collaboration between <strong>DeepLearning.AI</strong> and <strong>Stanford Online</strong>, that teaches teach you the fundamentals of machine learning and how to Build machine learning models in Python using popular machine learning libraries with NumPy</p><p>Also I am using <strong>ChatGPT</strong> to describe some concepts: E.g Explain simple linear regression with one variable</p><h3>Simple Linear Regression with One Variable</h3><p>Linear regression with one variable is a statistical method used to model the relationship between a single independent variable (x) and a dependent variable (y). It assumes that the relationship between the two variables is linear, meaning that y is a linear function of x. The goal of linear regression is to find the best-fitting line through the data points, which can be used to make predictions about the value of y for any given value of x. The best-fitting line is determined by finding the values of the slope and y-intercept that minimize the sum of the squared differences between the predicted and actual values of y. This method is also known as simple linear regression [1]</p><h4>Dataset</h4><p>The file dataset1.txt contains the dataset for our linear regression problem. The first column is the population of a city and the second column is the profit of a food truck in that city. [3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*zLf3bSptYvtrJDRez0zp2Q.png" /></figure><blockquote><strong>Note: The Dataset Does not need any preprocesing</strong></blockquote><h4><strong>Notation:</strong></h4><p><strong>m</strong> = Number of training examples</p><p><strong>X</strong> = ‘Input’ variables / Features</p><p><strong>y</strong> = ‘Output’ variable / ‘target’ variable</p><p>The dataset is loaded from the data file into the variables X and y:</p><pre>#Read the text file (csv)<br>df = pd.read_csv(&#39;https://raw.githubusercontent.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python/main/data/dataset1.txt&#39;, skiprows = 0, header = None, names = [&#39;population&#39;, &#39;profit&#39;])<br>#Form the usual &quot;X&quot; matrix and &quot;y&quot; vector<br>X = df[[&#39;population&#39;]][&#39;population&#39;].values<br>y = df[[&#39;profit&#39;]].values<br><br>m = y.size #number of training examples<br><br>#Reshape y to a mx1 matrix<br>y = y.reshape((m, 1))<br><br>df.head(3)</pre><h4>Plotting the Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*HobT5wwsQndecD33tpWTxQ.png" /></figure><h3>Gradient Descent</h3><p>Gradient descent is an optimization algorithm used to minimize a function. It works by iteratively moving in the direction of steepest descent as defined by the negative of the gradient. [4]</p><p>In mathematical terms, suppose we have a function f(x) that we want to minimize, where x is a vector of parameters. The gradient of the function with respect to the parameters is a vector of partial derivatives of the function with respect to each parameter</p><p>The gradient points in the direction of greatest increase of the function, so to minimize the function, we can move in the opposite direction, which is the direction of steepest descent. This is done by updating the parameters in the opposite direction of the gradient:</p><p>where η is the learning rate, which determines the step size at each iteration.</p><p>The process of updating the parameters in this way is repeated until the cost function converges to a minimum or until a pre-determined number of iterations is reached.</p><p>We use Gradient Decent to fit the linear regression parameters θ to our dataset</p><h4>Update Equations</h4><p>The objective of linear regression is to minimize the cost function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*xpJE9y8GCfPINkRL42nq0Q.png" /></figure><p>where the hypothesis hθ(x) is given by the linear model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*eCpJAOdaR-JBNRxmdNZZPA.png" /></figure><p>Recall that the parameters of your model are the θj values. These are the values you will adjust to minimize cost J(θ). One way to do this is to use the batch gradient descent algorithm. In batch gradient descent, each iteration performs the update</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49Kh-cE5MB4B1JW_7R8loA.png" /></figure><p>With each step of gradient descent, your parameters θj come closer to the optimal values that will achieve the lowest cost J(θ).</p><h4>Implementation</h4><p>We have already set up the data for linear regression. In the following cell, we add another dimension to our data to accommodate the θ0 intercept term.</p><pre># Add a column of ones to X. The numpy function stack joins arrays along a given axis. <br># The first axis (axis=0) refers to rows (training examples) <br># and second axis (axis=1) refers to columns (features).<br>X = np.stack([np.ones(m), X], axis=1)</pre><h4>Computing the cost 𝐽(𝜃)</h4><p>As you perform gradient descent to learn to minimize the cost function 𝐽(𝜃)J(θ), it is helpful to monitor the convergence by computing the cost.</p><p>In this section, you will implement a function to calculate 𝐽(𝜃) so you can check the convergence of your gradient descent implementation.</p><p>The function computeCost which computes 𝐽(𝜃). As you are doing this, remember that the variables 𝑋 and 𝑦 are not scalar values, but matrices whose rows represent the examples from the training set.</p><p>Computes the cost of using theta as the parameter for linear regression to fit the data points in X and y</p><p>Compute the cost of a particular choice of theta. You should set J to the cost.</p><pre>def computeCost(X, y, theta):<br>    m = y.size  # number of training examples<br>    # You need to return the following variables correctly<br>    J = 0.0<br>    J = 1./(2. * m) * np.sum((np.dot(X, theta) - y)**2)<br>    return J</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*Q5uBsYLjFiO0RESdL42ulg.png" /></figure><h4>Gradient descent method</h4><p>Next, you will implement gradient descent in a function. The loop structure has been written for you, and you only need to supply the updates to 𝜃θ within each iteration.</p><p>As you program, make sure you understand what you are trying to optimize and what is being updated. Keep in mind that the cost 𝐽(𝜃) is parameterized by the vector 𝜃, not 𝑋 and 𝑦y. That is, we minimize the value of 𝐽(𝜃) by changing the values of the vector 𝜃, not by changing 𝑋 or 𝑦. Refer to the equations in this notebook and to the lecture slides if you are uncertain. A good way to verify that gradient descent is working correctly is to look at the value of 𝐽(𝜃) and check that it is decreasing with each step.</p><p>The starter code for the function gradientDescent calls computeCost on every iteration and saves the cost to a python list. Assuming you have implemented gradient descent and computeCost correctly, your value of 𝐽(𝜃)J(θ) should never increase and should converge to a steady value by the end of the algorithm.</p><pre>def gradientDescent(X, y, theta, alpha, num_iters):<br>    # Initialize some useful values<br>    m = y.shape[0]  # number of training examples<br>    # are passed by reference to functions<br>    theta = theta.copy()<br>    J_history = [] # Use a python list to save cost in every iteration<br>    <br>    for i in range(num_iters):<br>        theta = theta - (alpha/m) * np.dot(X.T, (np.dot(X, theta) - y))<br>        # save the cost J in every iteration<br>        J_history.append(computeCost(X, y, theta))<br>    <br>    return theta, J_history</pre><p>After you are finished call the implemented gradientDescent function and print the computed 𝜃θ. We initialize the θ parameters to 0 and the learning rate 𝛼α to 0.01. Execute the following cell to check your code.</p><pre># initialize fitting parameters<br>theta = np.zeros((2, 1))<br># some gradient descent settings<br>iterations = 1500<br>alpha = 0.01<br><br># run gradient descent<br>theta, J_hist = gradientDescent(X, y, theta, alpha, iterations)<br><br>print(&#39;Theta found by gradient descent:&#39;)<br>print(&#39;𝜃 = &#39; + str(theta[0][0])  + &#39; , &#39; + str(theta[1][0]) )</pre><p>Theta found by gradient descent:<br>𝜃 = -3.6302914394043593, 1.1663623503355818</p><h3>Visualizing Linear Fit</h3><p>We will use your final parameters to plot the linear fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nnZqiyAPfrEYFNxDSOpxiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*GtEzGClEwN6JTMjVJB8PUA.png" /></figure><h3>Prediction of Profits for a Food Truck</h3><p>Now that we build our linear regression model we can test some predictions</p><p><strong>prediction_Value</strong> = 7 (Population in 10,000s)</p><h4>Predictions from Linear Regression Algorithm from scratch</h4><pre>predict = np.dot([[1, prediction_Value]], theta)<br>print(&#39;The 𝜃 value: &#39; + str(theta[0][0])  + &#39; , &#39; + str(theta[1][0]) )<br>print(&#39;For population = 70,000, we predict a profit of $&#39;, round(predict[0][0]*10000, 2))</pre><p>The 𝜃 value: -3.6302914394043593, 1.1663623503355818<br>For population = 70,000, we predict a profit of<strong> $ 45342.45</strong></p><h4>Predictions of LinearRegression Model from sklearn</h4><p>We can compare the results using the class of the sklearn LinearRegression module that contains different functions for performing machine learning with linear models</p><pre>from sklearn.linear_model import LinearRegression<br><br>X = df[[&#39;population&#39;]]<br>y = df[[&#39;profit&#39;]]<br><br>reg = LinearRegression().fit(X, y)<br>print(&#39;Score:&#39;)<br>print(reg.score(X, y))<br><br>print(&#39;The 𝜃 value: &#39; + str(reg.intercept_[0]) + &#39; , &#39; + str(reg.coef_[0][0]))<br>print(&#39;For population = 70,000, we predict a profit of $&#39;, round(reg.predict(np.array([[7]]))[0][0] * 10000, 2))</pre><p><strong>Score:</strong><br>0.7020315537841397<br>The <strong>𝜃</strong> value: -3.89578087831185, 1.1930336441895935<br>For population = 70,000, we predict a profit of <strong>$ 44554.55</strong></p><h3>Visualizing 𝐽(𝜃)</h3><p>To understand the cost function 𝐽(𝜃) better, you will now plot the cost over a 2-dimensional grid of 𝜃0 and 𝜃1 values. You will not need to code anything new for this part, but you should understand how the code you have written already is creating these images.</p><p>In the next cell, the code is set up to calculate 𝐽(𝜃) over a grid of values using the computeCost function that you wrote. After executing the following cell, you will have a 2-D array of 𝐽(𝜃) values. Then, those values are used to produce surface and contour plots of 𝐽(𝜃) using the matplotlib plot_surface and contourf functions. The plots should look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ySYR9kLEirCVksg3Z8cftQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XsH3U_RWDBtt-GHd-BmeXA.png" /></figure><p>The purpose of these graphs is to show you how 𝐽(𝜃) varies with changes in 𝜃0and 𝜃1. The cost function 𝐽(𝜃) is bowl-shaped and has a global minimum. (This is easier to see in the contour plot than in the 3D surface plot). This minimum is the optimal point for 𝜃 and 𝜃1, and each step of gradient descent moves closer to this point.</p><h3>Linear regression with multiple variables</h3><p>In this part, you will implement linear regression with multiple variables to predict the prices of houses. Suppose you are selling your house and you want to know what a good market price would be. One way to do this is to first collect information on recent houses sold and make a model of housing prices.</p><p>Linear regression in the context of house prediction, linear regression can be used to predict the value of a house based on a set of predictor variables such as size, location, age, and number of bedrooms.</p><p>The goal of linear regression is to find the line of best fit that minimizes the distance between the points and the line. The equation of this line can be used to make predictions about the value of a house given a set of predictor variables.</p><h4>Dataset</h4><p>The file dataset2.txt contains a training set of housing prices in Portland, Oregon. The first column is the size of the house (in square feet), the second column is the number of bedrooms, and the third column is the price of the house. [3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*6GAbYNh2t-CGOKL2xrdmhA.png" /></figure><blockquote><strong>Note: The Dataset Does not need any preprocesing</strong></blockquote><h4>Notation:</h4><p><strong>m</strong> = Number of training examples</p><p><strong>X</strong> = ‘Input’ variables / Features</p><p><strong>y</strong> = ‘Output’ variable / ‘target’ variable</p><pre>#Load Data<br>df = pd.read_csv(&#39;https://raw.githubusercontent.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python/main/data/dataset2.txt&#39;, skiprows = 0, header = None, names = [&#39;size sq-ft&#39;, &#39;bedrooms&#39;, &#39;price&#39;])<br>X = df[[&#39;size sq-ft&#39;, &#39;bedrooms&#39;]].values<br>y = df[[&#39;price&#39;]].values<br>m = y.size<br>#Reshape y to a mx1 matrix<br>y = y.reshape((m, 1))<br><br>df.head(5)</pre><h3>Feature Normalization</h3><p>Feature normalization is a technique used to transform the values of numeric columns in a dataset to a common scale, without distorting differences in the range or distribution of the data. This can be useful for machine learning models that use optimization algorithms that require features to be on a similar scale in order to work effectively. [5]</p><p>There are several methods for normalizing features, but one common method is to subtract the mean of the feature from each value, and then divide the result by the standard deviation of the feature. This scales the feature values to have zero mean and unit variance.</p><p>For example, suppose we have a dataset with a numeric column x. To normalize this feature, we can apply the following transformation to each value xi in the column:</p><p>xi_normalized = (xi — mean(x)) / std(x)</p><p>where mean(x) and std(x) are the mean and standard deviation of the feature x, respectively.</p><p>Another method for normalizing features is to scale the values to a fixed range, such as [0, 1] or [-1, 1]. This can be done by subtracting the minimum value of the feature from each value, and then dividing the result by the range (max — min) of the feature.</p><p>Normalizing features can help machine learning algorithms to converge faster and perform better, but it is important to remember to apply the same normalization transformation to the test set when evaluating the model.</p><p>This technique is used in many machine learning libraries such as scikit-learn, TensorFlow, and Keras.</p><p><strong>Source:</strong> scikit-learn documentation (<a href="https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler">https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler</a>)</p><h3>Feature Normalization from scratch</h3><pre>def  featureNormalize(X):<br>    X_norm = X.copy()<br>    mu = np.zeros(X.shape[1])<br>    sigma = np.zeros(X.shape[1])<br>    mu = np.mean(X, axis = 0)<br>    sigma = np.std(X, axis = 0)<br>    <br>    X_norm = X_norm - mu<br>    X_norm = X_norm / sigma<br>    return X_norm, mu, sigma</pre><pre># call featureNormalize on the loaded data<br>X_norm, mu, sigma = featureNormalize(X)</pre><p>Computed mean: [2000.68085106 3.17021277]<br>Computed standard deviation: [7.86202619e+02 7.52842809e-01]</p><h4>Feature Normalization from StandardScaler class</h4><p>Source: scikit-learn documentation (<a href="https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler">https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler</a>)</p><pre>from sklearn import preprocessing<br>scaler = preprocessing.StandardScaler().fit(X)</pre><pre># call featureNormalize on the loaded data<br>X_scaled = scaler.transform(X)</pre><p>Computed mean: [2000.68085106 3.17021277]<br>Computed standard deviation: [7.86202619e+02 7.52842809e-01]</p><h3>Gradient Descent Multi</h3><p>Previously, you implemented gradient descent on a univariate regression problem. The only difference now is that there is one more feature in the matrix 𝑋. The hypothesis function and the batch gradient descent update rule remain unchanged. [3]</p><p>You should complete the code for the functions computeCostMulti and gradientDescentMulti to implement the cost function and gradient descent for linear regression with multiple variables. If your code in the previous part (single variable) already supports multiple variables, you can use it here too. Make sure your code supports any number of features and is well-vectorized. You can use the shape property of numpy arrays to find out how many features are present in the dataset.</p><p><strong>Implementation Note:</strong> In the multivariate case, the cost function can also be written in the following vectorized form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*sa3m6bJ_VXi98zHAAoP6fw.png" /></figure><pre>def computeCostMulti(X, y, theta):<br>    m = y.shape[0] # number of training examples<br>    J = 0.0<br>    J = 1./(2. * m) * np.sum((np.dot(X, theta) - y)**2)<br>    return J</pre><p>Where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*367b-ruScYfd2BRdRGSJjg.png" /></figure><pre>def gradientDescentMulti(X, y, theta, alpha, num_iters):<br>    m = y.shape[0] # number of training examples<br>    <br>    # make a copy of theta, which will be updated by gradient descent<br>    theta = theta.copy()<br>    <br>    J_history = []<br>    <br>    for i in range(num_iters):<br>        theta = theta - (alpha/m) * np.dot(X.T, (np.dot(X, theta) - y))<br>        # save the cost J in every iteration<br>        J_history.append(computeCostMulti(X, y, theta))<br>    <br>    return theta, J_history</pre><h4>Selecting learning rates</h4><p>In this part of the exercise, you will get to try out different learning rates for the dataset and find a learning rate that converges quickly. You can change the learning rate by modifying the following code and changing the part of the code that sets the learning rate.</p><p>Use your implementation of gradientDescentMulti function and run gradient descent for about 50 iterations at the chosen learning rate. The function should also return the history of 𝐽(𝜃)J(θ) values in a vector 𝐽J.</p><p>After the last iteration, plot the J values against the number of iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*w2uLyRsrfjEM6lm8bhVCug.png" /></figure><h3>Predict House Price</h3><p>Now that we implement the model we can start doing some predictions</p><h3>Regression Evaluation Metrics</h3><p>Regression evaluation metrics are used to evaluate the performance of a regression model. These metrics provide a quantitative measure of the accuracy of the model’s predictions and allow us to compare the performance of different models.</p><p>There are several common regression evaluation metrics, including:</p><p><strong>Mean absolute error (MAE): </strong>This metric measures the average absolute difference between the predicted values and the true values. It is calculated as the sum of the absolute differences between the predicted and true values, divided by the number of samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*LAIZG3jqlwtGikM2-HLaDQ.png" /></figure><p><strong>Mean squared error (MSE):</strong> This metric measures the average squared difference between the predicted values and the true values. It is calculated as the sum of the squared differences between the predicted and true values, divided by the number of samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*BPWk9Fv31iKjPMohW1eAbg.png" /></figure><p><strong>Root mean squared error (RMSE):</strong> This metric is the square root of the mean squared error. It is often used because it is in the same units as the original data, which makes it easier to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*KWN5vs4QYMB361lXZXl7nA.png" /></figure><p><strong>R-squared (R2):</strong> This metric is a measure of the goodness of fit of the model. It ranges from 0 to 1, with higher values indicating a better fit.</p><p>There are other regression evaluation metrics that can be used, depending on the specific needs of the problem. It is important to choose an appropriate metric that reflects the goals of the model and the characteristics of the data.</p><p><strong>Values:</strong></p><p>size_ft = 1650 # sq-ft<br>bathrooms = 3</p><h4>Predict House Price using our model</h4><p><strong>theta computed from gradient descent: </strong>[[340412.56301439 [109370.05670466] [ -6500.61509507]]</p><p><strong>The predicted price of a 1650 sqft, 3 beedrooms house: 293098.5</strong></p><h4>Predict House Price using LinearRegression Model From sklearn.linear_model</h4><pre>X = X_scaled<br>y = df[[&#39;price&#39;]]<br><br>reg = LinearRegression().fit(X, y)<br>print(&#39;The accuracy of the Linear Regression model:&#39;)<br>print(reg.score(X, y))<br><br>print(&#39;The 𝜃 value: &#39; + str(reg.intercept_[0]) + &#39; , &#39; + str(reg.coef_[0][0]))<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (sklearn.linear_model):&#39;, round(reg.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0][0], 1) )</pre><p><strong>The accuracy of the Linear Regression model:</strong><br>0.7329450180289143<br><strong>The 𝜃 value: </strong>340412.6595744681 , 109447.7964696418<br>Predicted price of a 1650 sq-ft, 3 br house (sklearn.linear_model): 293081.5</p><p>We can observed that prediction is not that ‘Good’: 0.73</p><h4>Underfitting</h4><p>Underfitting in linear regression occurs when the model is not complex enough to capture the underlying relationship between the independent and dependent variables in the data. This can happen for a few reasons:</p><ol><li><strong>The model is too simple:</strong> If the model only has a few parameters, it may not be able to capture the complexity of the data. In such cases, a more complex model with more parameters may be required.</li><li><strong>The data is not linear:</strong> If the data has a non-linear relationship between the independent and dependent variables, a linear model will not be able to fit the data well.</li><li><strong>Insufficient data:</strong> With limited data, the model may not be able to learn the underlying relationship between the independent and dependent variables.</li></ol><p>Underfitting can be identified by low training accuracy and high validation error, which implies that the model is not generalizing well to new unseen data.</p><h4>How to solve Underfitting in linear regression model</h4><p>There are several ways to solve underfitting in linear regression:</p><ol><li><strong>Adding more features:</strong> By adding more features, the model can become more complex, allowing it to capture the underlying relationship between the independent and dependent variables more accurately.</li><li><strong>Using non-linear features:</strong> Adding non-linear features or interactions between features can help the model capture non-linear relationships in the data.</li><li><strong>Using a more complex model: </strong>Instead of using a linear model, using a more complex model like polynomial regression, decision tree regression or random forest regression may be able to better fit the data.</li><li><strong>Increasing the amount of data:</strong> With more data, the model can learn the underlying relationship between the independent and dependent variables more accurately.</li><li><strong>Regularization:</strong> Regularization is a technique that helps to prevent overfitting by adding a penalty term to the loss function to discourage large coefficients. L1 and L2 regularization are the most popular ways of regularizing linear regression.</li><li><strong>Cross-validation: </strong>Using cross-validation techniques (such as k-fold cross-validation) can help to identify and avoid overfitting by evaluating the performance of the model on unseen data.</li></ol><p>It’s important to note that there’s no one-size-fits-all solution to underfitting and it may require trying different approaches and experimenting with different parameters to find the best solution.</p><p>In this case we can observe that we only have 2 features and the size of the sample data is low (47)</p><h3>Setting up train and test split</h3><p>Setting up a train and test split is a common technique used in machine learning to evaluate the performance of a model. The goal of the train and test split is to evaluate the model’s ability to generalize to new, unseen data.</p><p>In the train and test split, the original dataset is randomly divided into a training set and a testing set. The model is trained on the training set, and then its performance is evaluated on the testing set. This allows the model to be trained and tested on different data, which gives a more realistic evaluation of its performance.</p><p>The train and test split is useful because it allows the model to be trained and evaluated in a controlled way. It is important to evaluate the model on unseen data, as this allows us to gauge its performance on data that it has not seen before and determine whether it is overfitting or underfitting.</p><p>In summary, setting up a train and test split is an important step in the machine learning process as it helps to evaluate the model’s ability to generalize to new, unseen data and ensure that it is not overfitting or underfitting.</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)</pre><h3>Linear Regression with split dataset</h3><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score<br><br>#Create linear regression <br>reg = LinearRegression()<br><br>#Train the model using the training sets<br>reg.fit(X_train, y_train)<br><br># Make predictions using the testing set<br>y_pred = reg.predict(X_test)<br>print(&#39;The accuracy of the Linear Regression&#39;,r2_score(y_test,y_pred))<br>print(&#39;The 𝜃 value: &#39; + str(reg.intercept_[0]) + &#39; , &#39; + str(reg.coef_[0][0]))<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (linear_model.LinearRegression):&#39;, round(reg.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0][0], 1) )<br>print (&#39;RMSE: &#39;, mean_squared_error(y_test, y_pred))</pre><p>The accuracy of the Linear Regression 0.8268330726601523<br>The 𝜃 value: 341272.94128357305 , 108050.93183004484<br>Predicted price of a 1650 sq-ft, 3 br house (linear_model.LinearRegression): 292732.0<br>RMSE: 2226159168.988815</p><h4>Regularization</h4><p>L1 and L2 regularization are techniques used to prevent overfitting in machine learning models. Overfitting occurs when a model is too complex and has too many parameters, which can lead to poor performance on new, unseen data. Regularization is a way of limiting the complexity of a model by adding a penalty term to the loss function. This penalty term discourages the model from learning too many parameters, which can help improve its generalization ability.</p><p>In summary, L1 and L2 regularization are similar in that they both add a penalty term to the loss function to prevent overfitting. The main difference is that L1 regularization encourages sparsity in the model by setting some weights to zero, while L2 regularization encourages weight values to be small but non-zero.</p><h3>Lasso Regression (L1 Regularization)</h3><p>L1 regularization, also known as Lasso regularization, adds a penalty term to the objective function that is proportional to the absolute value of the coefficients. This results in some coefficients being exactly equal to zero, effectively eliminating them from the model. L1 regularization is useful for feature selection, as it can automatically select the most important features.</p><pre>from sklearn.linear_model import Lasso<br><br>lasso=Lasso(alpha=0.8)<br>lasso.fit(X_train, y_train)<br>y_pred3=lasso.predict(X_test)<br><br>print(&#39;The accuracy of the Lasso Regression&#39;,lasso.score(X_test, y_test))<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso):&#39;, round(lasso.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0], 2) )</pre><h3>Ridge Regression (L2 Regularization)</h3><p>L2 regularization, also known as Ridge regularization, adds a penalty term to the objective function that is proportional to the square of the coefficients. This results in the coefficients being small, but non-zero. L2 regularization is useful for preventing overfitting and improving the generalization of the model.</p><pre>from sklearn.linear_model import Ridge<br><br>#Create Ridge regression <br>ridge = Ridge()<br><br>#Train the model using the training sets<br>ridge.fit(X_train, y_train)<br>b = float(ridge.intercept_)<br><br># Make predictions using the testing set - Ridge Regression<br>test_ridge = ridge.predict(X_test)<br>print(&#39;The accuracy of the Ridge Regression is&#39;, r2_score(y_test, test_ridge))<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso):&#39;, round( ridge.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0][0] , 2) )</pre><h3>Hyperparameter tunning</h3><p>Hyperparameter tuning is the process of adjusting the hyperparameters of a machine learning model to optimize its performance. Hyperparameters are parameters that are set prior to training the model and are not learned from the training data.</p><p>Hyperparameter tuning is an important step in the machine learning process because the performance of the model can be significantly affected by the choice of hyperparameters. Different hyperparameter values can result in drastically different model performance, and finding the optimal values can be a challenging task.</p><p>There are several methods for hyperparameter tuning, including manual tuning, grid search, and random search. In manual tuning, the hyperparameters are manually adjusted by the user. In grid search, a predefined set of hyperparameter values is specified, and the model is trained and evaluated using all possible combinations of these values. In random search, the hyperparameter values are chosen randomly from a predefined range.</p><p>Hyperparameter tuning can be a time-consuming process, but it is an important step in the machine learning workflow as it can significantly improve the performance of the model.</p><h3>Hyperparameter tunning Ridge Regression (L2 Regularization)</h3><pre>#find best alpha for Ridge Regression<br>from sklearn.model_selection import GridSearchCV<br><br>param_grid={&#39;alpha&#39;:np.arange(1,10,500)} #range from 1-500 with equal interval of 10 <br>ridge=Ridge() <br>ridge_best_alpha=GridSearchCV(ridge, param_grid)<br>ridge_best_alpha.fit(X_train,y_train)<br><br>print(&quot;Best alpha for Ridge Regression:&quot;,ridge_best_alpha.best_params_)<br>print(&quot;Best score for Ridge Regression with best alpha:&quot;,ridge_best_alpha.best_score_)</pre><h3>Hyperparameter tunning Lasso Regression (L1 Regularization)</h3><pre>from sklearn.model_selection import GridSearchCV<br><br>param_grid={&#39;alpha&#39;:np.arange(0,0.1,1)} #range from 0-1 with equal interval of 0.1 <br>lasso=Lasso() <br>lasso_best_alpha=GridSearchCV(lasso, param_grid) <br>lasso_best_alpha.fit(X_train,y_train)<br><br>print(&quot;Best alpha for Lasso Regression:&quot;,lasso_best_alpha.best_params_)<br>print(&quot;Best score for Lasso Regression with best alpha:&quot;,lasso_best_alpha.best_score_)</pre><p>Best score for Lasso Regression with best alpha: 0.15732202460557382</p><pre>#seting alpha as 20<br>alpha = lasso_best_alpha.best_score_ <br><br># Initialising Lasso() with above alpha<br>lasso = Lasso(alpha=alpha)<br><br>#fitting model<br>lasso.fit(X_train,y_train)<br><br>print(&#39;The accuracy of the Lasso Regression&#39;,lasso.score(X_test, y_test))<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso):&#39;, round(lasso.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0], 2) )</pre><p>The accuracy of the Lasso Regression 0.826833643868359<br>Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso): 292732.05</p><h3>Hyperparameter tunning ElasticNet Regression</h3><pre>from sklearn.linear_model import ElasticNet<br><br># list of alpha to tune<br>params = {&#39;alpha&#39;: [0.0001, 0.001, 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]}<br><br># defining cross validation folds as 8<br>folds = 8<br><br># Initialising ElasticNet()<br>elasticnet = ElasticNet() <br><br>#using same attributes used for Ridge tuning except estimator here would be ElasticNet<br>grid_cv_model = GridSearchCV(<br>                       estimator=elasticnet,<br>                       param_grid=params,<br>                       scoring=&#39;neg_mean_absolute_error&#39;,<br>                       cv=folds,<br>                       return_train_score=True,<br>                       verbose=1<br>)<br><br>#fitingmodel_cv<br>grid_cv_model.fit(X_train,y_train)<br><br># Checking best  alpha from model_cv<br>print(grid_cv_model.best_params_)<br><br>alpha = grid_cv_model.best_params_[&quot;alpha&quot;]<br><br># Defining ElasticNet with above alpha<br>elasticnet = ElasticNet(alpha=alpha)<br>  <br># fiting elastic net<br>elasticnet.fit(X_train,y_train)<br><br>pred_by_elasticnet = elasticnet.predict(X_test)<br><br>print(&#39;The accuracy of the Ridge Regression is&#39;, round(r2_score(y_test, pred_by_elasticnet), 2))<br>print(f&#39;ElasticNet RMSE: {np.sqrt(mse(y_test,pred_by_elasticnet))}&#39;)<br>print(&#39;Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso):&#39;, round(elasticnet.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0], 2) )</pre><p>Predicted price of a 1650 sq-ft, 3 br house (linear_model.Lasso): 295701.11</p><h3>The next phase is to apply this concepts to a more complex dataset</h3><p>For that I am using the [House Prices — Advanced Regression Techniques](<a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/overview/description">https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/overview/description</a>) competition dataset [6]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*DSD1yX9EiwYcMbgS.png" /><figcaption>Photo by Tom Thain on Unsplash.</figcaption></figure><p>Before start modeling we need to check the dataset</p><h4>EDA</h4><p>Exploratory Data Analysis (EDA) is an approach to analyzing and summarizing datasets to gain insights and understanding about the data. It is a crucial step in the data science process as it helps identify patterns, trends, and relationships in the data that can inform later steps in the process such as building models or making decisions. EDA typically involves visualizing the data using graphs and plots, as well as applying statistical techniques to summarize and understand the data. It is called “exploratory” because the analyst is often unsure about what they are looking for in the data and is using EDA to help them discover what the data can tell them.</p><p>We have 1460 rows and 81 columns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*hOWq55bPN6amybnUntD6Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*D226c-FUI71NkSxXh1NdBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QltBNvdWAChze357rYdDog.png" /></figure><h3>Normalization, remove outliers and Skewness</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wNvHxT_R_Sl68V5rprK7uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuATYWoKcpFcRo4FU3b0Tg.png" /></figure><h4>Filling Missing Values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ACJ9b6EvEezUnD02h_xUhw.png" /></figure><pre>from sklearn.base import TransformerMixin<br>from sklearn.base import BaseEstimator<br><br>class DataImputer(BaseEstimator, TransformerMixin):<br>    def __init__(self, strategy, filler):<br>        self.strategy = strategy<br>        self.fill = filler<br>        &quot;&quot;&quot;<br>        Impute missing values.<br><br>        &quot;&quot;&quot;<br>    def fit(self, X, column, strategy):<br>        if strategy == &#39;mean&#39;:<br>            X[column] = X[column].mean()<br>        elif strategy == &#39;median&#39;:<br>            X[column] = X[column].median()<br>        elif strategy == &#39;mode&#39;:<br>            X[column] = X[column].mode().iloc[0]<br>        elif strategy == &#39;zero&#39;:<br>            X[column] = X[column].fillna(0)<br>        elif strategy == &#39;none&#39;:<br>            X[column] = df[column].fillna(&quot;None&quot;)<br>                <br>        return X[column]</pre><p><strong>Filling missing values</strong></p><pre>imputer = DataImputer(BaseEstimator, TransformerMixin)<br><br>df_clean = pd.read_csv(&#39;https://raw.githubusercontent.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python/main/data/data_cleaning_hp.csv&#39;)<br><br>df[&quot;LotFrontage&quot;] = df.groupby(&quot;Neighborhood&quot;)[&quot;LotFrontage&quot;].transform(<br>    lambda x: x.fillna(x.median()))<br><br>## loop to filling the missing Values using the DataInputer Class<br>for i in df_clean[&#39;fill type&#39;].unique():<br>    strategy = i<br>    for j in df_clean[df_clean[&#39;fill type&#39;] == i][&#39;column name&#39;].tolist():<br>        column = j<br>        print(strategy  + column)<br>        df[column] = imputer.fit(df, column, strategy)</pre><h3>For this version I am using the same variables of the previous exercise</h3><pre>X = df[[&#39;Totalsqr&#39;, &#39;BedroomAbvGr&#39;]].values<br>y = df[[&#39;SalePrice&#39;]].values<br>m = y.size<br>#Reshape y to a mx1 matrix<br>y = y.reshape((m, 1))<br><br>df.head(5)</pre><p><strong>Feature scaling</strong></p><pre>from sklearn import preprocessing<br><br>scaler = preprocessing.StandardScaler().fit(X)<br><br># call featureNormalize on the loaded data<br>X_norm, mu, sigma = featureNormalize(X)<br><br>print(&#39;Computed mean:&#39;, mu)<br>print(&#39;Computed standard deviation:&#39;, sigma)<br><br># call featureNormalize on the loaded data<br>X_scaled = scaler.transform(X)<br>print(&#39;Computed mean:&#39;, scaler.mean_)<br>print(&#39;Computed standard deviation:&#39;, sigma)<br><br>X = X_scaled</pre><p><strong>Train and test datasets</strong></p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)</pre><p><strong>Linear regression</strong></p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)<br><br>size_ft = 2416 # sq-ft<br>bathrooms = 3<br><br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score<br><br>#Create linear regression <br>reg = LinearRegression()<br><br>#Train the model using the training sets<br>reg.fit(X_train, y_train)<br><br># Make predictions using the testing set<br>y_pred = reg.predict(X_test)<br>print(&#39;The accuracy of the Linear Regression&#39;,r2_score(y_test,y_pred))<br>print(&#39;The 𝜃 value: &#39; + str(reg.intercept_[0]) + &#39; , &#39; + str(reg.coef_[0][0]))<br>print(&#39;Predicted price of a &#39; + str(size_ft) + &#39; sq-ft, 3 br house (linear_model.LinearRegression):&#39;, round(reg.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0][0], 1) )<br>print (&#39;RMSE: &#39;, mean_squared_error(y_test, y_pred))</pre><p><strong>Ridge Regression</strong></p><pre>from sklearn.linear_model import Ridge<br><br>#Create Ridge regression <br>ridge = Ridge()<br><br>#Train the model using the training sets<br>ridge.fit(X_train, y_train)<br>b = float(ridge.intercept_)<br><br># Make predictions using the testing set - Ridge Regression<br>test_ridge = ridge.predict(X_test)<br>print(&#39;The accuracy of the Ridge Regression is&#39;, r2_score(y_test, test_ridge))<br>print(&#39;Predicted price of a &#39; + str(size_ft) + &#39; sq-ft, 3 br house (linear_model.Lasso):&#39;, round( ridge.predict(np.array([[(size_ft - mu[0])/sigma[0], (bathrooms - mu[1]) / sigma[1]]]))[0][0] , 2) )</pre><p><strong>Predictions:</strong></p><p>Actual Sale Price: $ 12,247</p><p>Linear Regression: 12,3</p><p>Lasso Regression: 12,28</p><h3><strong>Conclusions:</strong></h3><p>The goal of this post is to explain the Model Representation of linear Regression and the implementation from scratch to understand what is behind the pre-build clases of models and compare the implementation with the pre-build clases of sklearn</p><h3>Future Work:</h3><p>Explain more details of the preprocessing process</p><p>Use all the columns</p><p>Feature engineering, feature selection</p><p>Use more complex methods like:</p><ul><li>XGBoost Regressor</li><li>Explain More deatils of the data processing process</li><li>Light Gradient Boosting Regressor</li><li>Support Vector Regressor</li><li>Gradient Boosting Regressor</li><li>Random Forest Regressor</li></ul><p><a href="https://github.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python"><strong>Jupiter Nootebok:</strong></a></p><p><a href="https://github.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python">https://github.com/DiegoHurtad0/Linear-Regression-Model-Representation-Implementation-From-Scratch-using-Python</a></p><h3>Contact Me:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QVgAQWwbqMiHURq6.jpg" /><figcaption>Bailey the Golden Retriever Sitting at a Desk (knowyourmeme, 2022)</figcaption></figure><p><a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a>Diego Gustavo Hurtado olivares</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74etRUtIB1ljvMfSKVCciQ.png" /><figcaption>Diego Hurtado <a href="https://www.linkedin.com/in/diegohurtadoo/"><strong>Linkedin:</strong></a></figcaption></figure><h3>References</h3><p>[1] “An Introduction to Linear Regression Analysis” by Douglas C. Montgomery, Elizabeth A. Peck, G. Geoffrey Vining. published by John Wiley &amp; Sons, Inc., Hoboken, New Jersey, ISBN 978–0–470–17248–9.</p><p>[1]Brown, Tom B., et al. “Language Models are Few-Shot Learners.” arXiv preprint arXiv:2005.14165 (2020).</p><p>[3] Machine Learning Specialization. Available at: <a href="https://in.coursera.org/specializations/machine-learning-introduction">https://in.coursera.org/specializations/machine-learning-introduction</a> (Accessed: January 13, 2023).</p><p>[4] “A Stochastic Approximation Method” by Robbins and Monro (1951) which introduced the stochastic gradient descent algorithm.</p><p>[5] Preprocessing data <em>Available at: </em><a href="https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler"><em>https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler</em></a><em>) (Accessed: January 13, 2023).</em></p><p>[6] House Prices — Advanced Regression Techniques <em>Available at: </em><a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/overview/description"><em>https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/overview/description</em></a><em> (Accessed: January 13, 2023).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bfd15dc2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An overview of Covid-19 in Mexico]]></title>
            <link>https://medium.com/data-science/covid-19-an-overview-of-mexico-ccf702ec80d9?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf702ec80d9</guid>
            <category><![CDATA[covid-19-mexico]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 22:10:29 GMT</pubDate>
            <atom:updated>2023-04-06T22:32:54.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>Causality Modeling of Covid 19 in Mexico</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf6Y1NlpVZXShYtD6gK8TQ.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>confirmed cases density (Diego Hurtado)</figcaption></figure><h3>Project Overview</h3><p>This project aims to provide an in-depth analysis of the COVID-19 situation in Mexico and develop a machine learning-based model to forecast new cases of the virus. By leveraging historical data on COVID-19 cases, the project seeks to identify trends, patterns, and potential correlations with various factors that may contribute to the spread of the virus. The insights gained from this analysis and the predictive model will help inform public health policies and strategies for better managing and mitigating the impact of the pandemic.</p><h3>Problem Statement</h3><p>COVID-19 has had a significant impact on Mexico, causing considerable strain on healthcare systems and disrupting the economy. Accurate and timely forecasting of new COVID-19 cases is essential for effective planning and resource allocation to control the spread of the virus. However, traditional forecasting methods may not be sufficient to address the complexity and rapidly changing nature of the pandemic. A machine learning-based approach is needed to provide more accurate and adaptable predictions for decision-makers.</p><p>Since late December 2019, an outbreak of a novel coronavirus disease (COVID-19; previously known as 2019-nCoV) was reported in Wuhan, China, which has subsequently affected 210 countries worldwide. As of November 10, 2022, about 7.1 M cases have been confirmed, over 330 k deaths in <strong>Mexico.</strong></p><h3>Objective</h3><p>The primary objective of this project is to develop a machine learning-based forecasting model for predicting new COVID-19 cases in Mexico. The model will be trained on historical data and will consider various factors, such as demographic information, socioeconomic indicators, and public health interventions. The project will also aim to:</p><ol><li>Analyze the COVID-19 situation in Mexico, identifying trends and patterns in the spread of the virus.</li><li>Investigate potential correlations between different factors and the number of new COVID-19 cases.</li><li>Evaluate the performance of the developed forecasting model and compare it with traditional forecasting methods.</li><li>Provide actionable insights and recommendations to inform public health policies and strategies for controlling the spread of COVID-19 in Mexico.</li></ol><h3>Index 📖</h3><p>▪️ Covid 19 — <strong>Data Analyst</strong> Mexico Overview</p><p>▪️ E<strong>xplanation model</strong> of death cases in Mexico</p><p>▪️ Mexico Counties Covid Cases <strong>Correlation</strong></p><p>▪️ Mexico`s Mobility <strong>pattern behaviour</strong></p><p>▪️<strong> </strong>Mexico Counties <strong>Clustering</strong></p><h3>Covid 19 — Mexico Overview 🇲🇽</h3><p>I am using time series of confirmed/death cases with combination of a dataset of description of the person during covid</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QwnC3Xu_FzMSxwZBJloO1w.png" /><figcaption><strong>Confirm cases (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jRSJUl9ZrZEyqbT_65GAiQ.png" /><figcaption><strong>Period with most of the confirm cases . the 3rd wave ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*C5nUKmjxbz-bvByUyaadfw.png" /><figcaption><strong>Death cases Mexico ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kOkZCxhajiwu8wbtA4HaSg.png" /><figcaption><strong>Period with most of the death cases ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*mjZtK7cdUtGt5tahoa2mAA.png" /><figcaption><strong>Dead ranges cases by age (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*tu9o6MCxGwR5B6EOnc5z1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*DO3Os8gELgN3hVDm4nEvtQ.png" /><figcaption><strong>Confirm range cases by age (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXHBMMJZ3DkJRKkXR5lmHQ.png" /><figcaption><strong>Age distribution by confirm cases (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UEBqp-mrMRIUbpJPV-gYmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLqcjeZw9Cavz6VS9xeThw.png" /><figcaption><strong>Proportion of confirm cases by gender (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcwfXdiyDrcjaXO6YTQ2hw.png" /><figcaption><strong>Percentage of people Hospitalized (Diego Hurtado)</strong></figcaption></figure><h3>Mexico Diseases During Covid 19 🇲🇽</h3><p>Severe disease onset might result in death due to massive alveolar damage and progressive respiratory failure. The Covid-19 pandemic is of high risk for patients on chronic hemodialysis due to their immunosuppressed state, advanced age, and the coexistence of significant comorbidities, in particular cardiovascular disease, diabetes mellitus, and others. Also remarkable that cardiovascular risk factors are highly common among the Mexican population and increasing at alarming rates, Cardiovascular diseases represent the first cause of death in Mexico [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcPCMoYruZvQ6-4lkYP4Sw.png" /><figcaption>Percentage of disease by confirm cases ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd0vs8YyDPxoljl97-ajPA.png" /><figcaption>Percentage of disease by confirm cases ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-wsgEZVbSFX3afHHINBOw.png" /><figcaption>Mexico 🇲🇽 COVID Dashboard (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F7tSGgjs4Awx7PYfpp0OA.png" /><figcaption>Mexico Top death causes 🇲🇽 (Diego Hurtado)</figcaption></figure><h3>What is causing death cases of Covid 19? Explanation model 🇲🇽</h3><p>To try to explain the death reasons, I am using dataset of Mexico reported by General Directorate of Epidemiology , first I am using 2022 period then period of the most death cases. [2020-Nov-02 , 2021-Mar-22]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jRSJUl9ZrZEyqbT_65GAiQ.png" /><figcaption>Death cases 2022 ( Diego Hurtado)</figcaption></figure><p>I am using a R<strong>andom Forest</strong> to predict if a person is likely to death base of age and diseases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZkU22Oe6026BIVX47Cxhg.png" /><figcaption>Tree map death cases period of 2022 (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wf8XZ5fOK1AZB0xLgvtXQ.png" /><figcaption>ROC curve for covid death cases classifier</figcaption></figure><p>The accuracy score of the model is 0.9926950565507624</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*RMf-uh0wBjAzp_UHTxTAWg.png" /><figcaption>Top reasons of death cases 2022 ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*hxHj7jvr68gGpFA4LzUTAQ.png" /><figcaption>Shap value impact death cases 2022 ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Z3HgyyCE8Swap5oMxr3LRw.png" /><figcaption>We can see that if the person is older it has more probability of death , period 2022 ( Diego Hurtado)</figcaption></figure><p><strong>Period with the most cases [2020-Nov-02 , 2021-Mar-22]</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kOkZCxhajiwu8wbtA4HaSg.png" /><figcaption>Period with most of death cases [2020-Nov-02 , 2021-Mar-22] (Diego Hurtado)</figcaption></figure><p>I did the same process but using the period with the most death cases in Mexico.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fs-0vVamkINocfks4TBX-Q.png" /><figcaption>Tree map death cases period of 2022 (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1zRGj5rE0DDI9W6MkE7KA.png" /><figcaption>Left part of tree map worst death cases period ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zk1XPMz6l2uLCEaKJI9JEg.png" /><figcaption>right part of tree map worst death cases period ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vq-AbYGKlZ72dlEk9BoSXw.png" /><figcaption>ROC curve for covid death cases classifier</figcaption></figure><p>AUC: 0.980956706138209</p><p>The accuracy score of the model is: 0.9683646910911617</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*SoRVtmStn-2en2MRpiGFcA.png" /><figcaption>Feature importance (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*yhqQOOZrkjJDVdeABTjtuQ.png" /><figcaption>We can see that if the person is older it has more probability of death ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Uo7eqRgZkAm7txGMdecGsQ.png" /><figcaption>Top reasons of death cases in the most death cases period ( Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*lQTc1CJ3vyDrqK-dy0je3Q.png" /><figcaption>Shap value impact death cases in the most death cases period ( Diego Hurtado)</figcaption></figure><h3>Mexico Counties Covid Cases Correlation 🇲🇽</h3><p>I am transforming the user information to county level to see if any correlation between the counties information to prove causation on hight number of deaths, the ability to uncover the causes and effects of different phenomena in complex systems would help to see the areas of improvement of health system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ZCL5ZYwUbtlXOnMtl_Fn9g.png" /></figure><p>First I am using the number of death case by <strong>disease</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*gqYrEN09KRKlrcbohWSGRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bax1_nnuIJkRDt9Vk2GxgA.png" /></figure><p>Later I am using <strong>socio demographic</strong> information of counties like population, poverty level, health access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*78uPQXS59K93mZcl7vbvPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXnbKhuLHZAGrLxDwWBjIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*u-PRqDG6IoIdGJQ-z0PqXA.png" /></figure><p><strong>Observation:</strong></p><p>Something to remark is that health coverage access of counties of Mexico is low</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*KBnWdMnVfausHdYAEaiVYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*8nfnEDnTA-xS59g439sfHQ.png" /></figure><p>In addition high percentage of people that were intubated on hospital died</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*4cDXocviVIDSAgQFDibi1A.png" /></figure><p>Number of death by health sector in Mexico</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*cVquuL9XD-k3Hx90FxRwkQ.png" /></figure><p><strong>Observation:</strong></p><p>Another import aspect is that the poverty levels of Mexico are hight, so people can not stay at home , Mexican people did not received any help from the President to stay in quarantine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Du2SMAs2mYMcXsM_z44sJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*SYS20yJWrINgwNQADO8cLA.png" /></figure><p><strong>Observation:</strong></p><p>We can observe that the top 10 counties with more deaths are the ones with more population in situation of poverty</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*1jKLiTzh6mcsuvxRmpY5qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7zpU1YJh0UhLKn_R86JhYg.png" /></figure><h3>Mexico`s Mobility 🚗 🇲🇽</h3><blockquote>The president of Mexico starts the “<strong>new normality</strong>” in May to “reactivate” the economy, despite of the spike in infections</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nhEYm-KA_zD1etMU.jpg" /><figcaption>Outside a shop, customers waiting without respecting the healthy distance. Av. Juárez corner with Eje Central, CDMX. May 21, 2020. <strong>Photo: </strong><em>Angélica Escobar/Forbes México.</em></figcaption></figure><p><strong>Observation:</strong></p><p>We can see that Confirm/ Deaths / mobility start to growth in <strong>May 2021</strong> when the ‘<strong><em>new normality’</em></strong> started</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*C5nUKmjxbz-bvByUyaadfw.png" /><figcaption><strong>Death cases Mexico ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QwnC3Xu_FzMSxwZBJloO1w.png" /><figcaption><strong>Confirm cases (Diego Hurtado)</strong></figcaption></figure><p>I am using different datasets to see the mobility trends in Mexico during Covid 19</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*G5hkuea_XRXg_gMYq37wtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*LoRQusAaxrdx4x9Yw6CVRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*dPuMdb0TFSm8vQqCv63seg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*_Lv2fgo5UOBB2IvHuGFnUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*THkByvS5kzMQ5nmn9vFN_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*h_Zx-ELdJ8-AXJnPrFc2QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*2t1jTFm4SKQF8l-a6GAqTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*7B6hy0qhMb6lcfDp1cOIBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*IPXbUxj_bIHO97rsVPitDQ.png" /></figure><p>“The new normal is an illusion, we are in the midst of epidemic activity and I think that proposing the restart of social activity at this time is virtually <strong>suicidal</strong>, I think this can reactivate, at levels not yet seen, the number of sick people and of the dead ” — <strong>Malaquías López Cervantes</strong></p><p><strong>Observation:</strong></p><p><em>Evidently COVID-19 is spreading faster and has a higher mortality rate in Mexico, people living in slums could be a key factor in this case. </em>Perhaps this is the reason why in Mexico coronavirus cases keep increasing.</p><p>The average number of person that lives inside a house hold in Mexico is from 3 to 5 People.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UzFg0Kd2F79qRXOo9wV1_A.png" /><figcaption>Diego O’HURTADO</figcaption></figure><p>Today, by the most conservative estimates, about 900 million <a href="http://www.habitatforhumanity.org.uk/what-we-do/where-we-work/slum-definition">people live in slums</a> [4]. By 2030, it’s estimated that 1 in 4 people on the planet will live in a slum or other informal settlement. Let’s take a tour of the <a href="http://uk.reuters.com/article/uk-slums-united-nations-world-insight-idUKKBN12H1GK">world’s biggest slums</a>:</p><ul><li>Khayelitsha in Cape Town (South Africa): 400,000</li><li>Kibera in Nairobi (Kenya): 700,000</li><li>Dharavi in Mumbai (India): 1,000,000</li><li><strong>Neza (Mexico): 1,200,000</strong></li><li>Orangi Town in Karachi (Pakistan): 2,400,000</li></ul><p><strong>Ciudad Nezahualcoyotl (Neza), Mexico City</strong></p><p>Population: 1.1 million</p><p>While some contend that Ciudad Nezahualcoyotl, also known as Neza, has evolved from a <a href="https://www.reuters.com/article/us-mexico-slum-neza-idUSKBN12E1F2">slum into a suburb</a>, the brick-and-mortar houses are scattered among improvised shanties, and the neighborhood is considered extremely dangerous, even by drug war-plagued Mexico’s standards [5]. Community action prompted the government to formalize land titles, start garbage collection, and build some other key infrastructure. Now, about <a href="https://www.citylab.com/equity/2017/06/how-a-slum-became-a-city/529488/">70% of residents work within the area</a>, which is Mexico’s most densely populated municipality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uY50cAY047yW_gHc.jpg" /><figcaption>An aerial view of Ciudad Neza, short for Nezahualcóyotl, Mexico state, Mexico on September 30, 2016. Thomson Reuters Foundation/Johnny Miller</figcaption></figure><p><strong>Observation:</strong></p><p>We can observe that the counties with more population are the ones with more death cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*1jKLiTzh6mcsuvxRmpY5qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7zpU1YJh0UhLKn_R86JhYg.png" /></figure><p><strong>Observation:</strong></p><p>We can observe that the counties with more population are the ones with more confirm cases also</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*T0E6ufiwQxD5Po51pZLgdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UJi5wvQ6r2qo4ScRC9Tjbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UJi5wvQ6r2qo4ScRC9Tjbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*m7P_xKqcyFdEptF77Kqt6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Me012KZEbR8adKz57W8ePA.png" /><figcaption>Urban Areas of Mexico</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*7hS1Q45M1kaG0-HpWhzufQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*gS8v0JOoJk4FIGNnvWRxqA.png" /><figcaption>Urban Areas of Mexico</figcaption></figure><blockquote><em>Even though we can observe correlation, it does not prove causation.</em></blockquote><p>Data won’t answer the question when the problem moves away from very narrow situation but can’t explain how they’re connected.</p><h3>Mexico Counties Clustering 🇲🇽</h3><p>I am using a clustering algorithm to group the data of counties to discover some certain similarities</p><p>First I am clustering the counties based on coordinates to test the algorithm performance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*7RUqxTGwVvHhJvziI74BjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*lCKjexRoapq_cU4zs9eqTQ.png" /><figcaption>Diego O’HURTADO</figcaption></figure><p>The clustering algorithm looks good</p><p><em>The centroids are the bigger blue circle</em></p><p><em>The clusters has different color</em></p><p><em>The size of the circle is based on the population size</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*YWPo1Wfeig627HCVhRfcFw.png" /><figcaption>Diego O’HURTADO</figcaption></figure><h3>Death Analytics Segmentation</h3><p>To do the segmentation of the counties, I am using the number of death cases, population, hospitalized , health access, poverty level, extreme poverty and number of people occupation inside households.</p><p>The steps that I am doing are the following:</p><h4>Correlation Estimate</h4><p>Compute correlation coefficient for the features selected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nPz9L3NPqIeNCtPZS6QiXA.png" /></figure><h4>𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝𝐢𝐳𝐚𝐭𝐢𝐨𝐧</h4><p>Standardizing data, so that all features have equal weight</p><h4>Hierarchical Clustering</h4><p>I plot the results from the Hierarchical Clustering using a Dendrogram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*eVrkz-siYNxiqsI-YZSvew.png" /></figure><h4>𝐏𝐂𝐀</h4><p>Employ PCA to find a subset of components, which explain the variance in the data</p><p>Plot the cumulative variance explained by total number of components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*GnQJxaW-gPvnq0UCw2Ya1Q.png" /></figure><p>I choose three components. 3 or 4 seems the right choice according to the previous graph</p><p>HeatMap for Principal Components against original features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68zNinWqcCIq6Swid8VSoQ.png" /><figcaption>Diego O’HURTADO</figcaption></figure><h3>PCA Visualization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*51cvBVPG1DRteWWFYLK_hw.png" /><figcaption>Diego O’HURTADO</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*-2HAvBzunsV9JWl37LHMUQ.png" /><figcaption>Diego O’HURTADO</figcaption></figure><p>Plot the Within Cluster Sum of Squares for the K-means PCA model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*MBY6K15GRZk7_8C0GRFyhQ.png" /></figure><p>I have chosen 4 clusters</p><h3>K-means clustering with PCA Results 📊</h3><p><strong>Cluster 1:</strong> Very Hight number of Deaths</p><p><strong>Cluster 2:</strong> Hight number of Deaths</p><p><strong>Cluster 3:</strong> Medium number of Deaths</p><p><strong>Cluster 4:</strong> Low number of Deaths</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*py5eaL8Lr1SCe4m59T_ugA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Fhr45rOf9gmxuMXWec0nGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*gim1mj-4cd136zwVRhAM_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*51msMu1G7ut3H-_hnUdwZQ.png" /></figure><p>We can observed that the results are very similar of the previous analysis, counties with more density are the ones with more death cases.</p><h3>Mexico States Overview 🇲🇽</h3><h4>Mexico States confirm cases 🇲🇽</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf6Y1NlpVZXShYtD6gK8TQ.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>confirmed cases density (Diego Hurtado)</figcaption></figure><h4>Mexico States death cases 🇲🇽</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQ6aW8Bj9En-Mz18GtYEPg.png" /><figcaption>Top 10 death cases states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-c90gDNudR_WMoG2qB-OA.png" /><figcaption>Top 10 death cases states by gender (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKmDGVMfOwyZZX6HcwQkkA.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>death cases density (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnJ97QgD2DDTlwkmvk6GjQ.png" /><figcaption>Top 10 mortality rate states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQbGNcFOzB6EClarE4L2hw.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>mortality rate density (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HvkxMo_d9jIDbrIjo2Owg.png" /><figcaption>Top 10 death cases per 100K population (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46MGjVYZR859upOO9g974w.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>death cases per 100K population density (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZmGxud5WHx4jL-_0CJR-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHwYbKMsaD0H42-BKgVsOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeMqpTqdY_mOkM-0K4y_HA.png" /><figcaption>COVID-19 in Mexico: Total confirmed cases by states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpIuY0ObtBaCwEdI98MmiQ.png" /><figcaption>COVID-19 in Mexico: Total death cases by states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9wTMGMG7HwKZlq1CFlatQ.png" /><figcaption>The state with most deaths is Mexico city</figcaption></figure><h3>Mexico Needs to Take Action</h3><p><strong>Predictive Monitoring of COVID-19 in Mexico: </strong>COVID-19 predictions are fundamentally important for rationalizing planning and mentality, but also challenging due to the innate uncertainty of the complex, dynamic and global COVID-19 pandemic as a typical <a href="https://en.wikipedia.org/wiki/Wicked_problem">wicked problem</a>. Traditional prediction or forecasting efforts, which aim to make an accurate prediction now to come true in the future, might be misleading in this context of extreme uncertainty</p><h3>Correlation between Mexico and the countries of Latin America</h3><p>I extracted COVID-19 daily new cases and deaths in Latin America from the Johns Hopkins COVID-19 data repository. I use linear regression to test the correlation between Mexico and the countries of Latin America to examine correlations, respectively. The country with the most correlations is brazil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qw1fVTakcgsTehkFP6YTzw.png" /><figcaption>Data relation between Mexico and Brazil (Diego Hurtado)</figcaption></figure><p><strong><em>It is interesting that the two countries are governed by a left-wing country.</em></strong></p><h3>BTW : I am looking for new job opportunities! 📊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAZXGJ1C8P2CKDGtAUfRWQ.png" /></figure><p>I’m looking for an opportunity where I can put those abilities to work for a mission I’m passionate about!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*G4ayscstHmnUhs_-" /></figure><blockquote>“When you are asked if you can do a job, tell ’em, ‘Certainly I can!’ Then get busy and find out how to do it.” — Theodore Roosevelt.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0kAkOvVbouenRFwD.jpg" /><figcaption>Bailey the Golden Retriever Sitting at a Desk (knowyourmeme, 2022)</figcaption></figure><p><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/">https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/</a></p><p><a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/"><strong>Msc. Diego Hurtado</strong></a><br><strong> Business Analysis Consultant</strong></p><h3>Annex</h3><p>Epidemiologist and health economist <strong>Eric Feigl-Ding </strong>compared the positive cases of coronavirus in the country with those in cities such as New York, Madrid, and Lombardy and warned that the percentage of positivity in Covid-19 tests that Mexico would be experiencing is unprecedented.</p><p>This is because more than half of the tests performed are positive for the virus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4ts2DeSgRkt7eiAfmw2Syw.png" /><figcaption>DrEricDing. (2020, June 21)</figcaption></figure><blockquote>“I am crying for Mexico. More than 50% is the percentage of *POSITIVITY* More than half of all those who take a test are positive,” said the scientist on Twitter about the coronavirus cases.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*UZ6IYpsmKlKi_Okq" /><figcaption>DrEricDing. (2020, June 21)</figcaption></figure><blockquote>Mexico per capita cases and mortality versus the US. There is clearly underdiagnosis in Mexico and poor treatment. The 56% positivity reflects that. So yes, damnit, we need more testing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*2vQ435eRI6SIAIVA" /></figure><h3>Reminder</h3><p>The 1918 influenza pandemic was the most severe pandemic in recent history. It was caused by an H1N1 virus with genes of avian origin. Although there is no universal consensus regarding where the virus originated, it spread worldwide during 1918–1919.</p><p>The number of deaths was estimated to be at least 50 million worldwide with about 675,000 occurring in the United States.</p><p>Mortality was high in people younger than 5 years old, 20–40 years old, and 65 years and older. The high mortality in healthy people, including those in the 20–40 year age group, was a unique feature of this pandemic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*85VctOhmYZ_xGvJJGJEz6g.png" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><blockquote><strong>We are Here.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*T0GRDo_-tqZpKJ8WLE0uEA.jpeg" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><p><strong>Conclusion:</strong></p><p>This article gives a detailed analysis of how COVID-19 has impacted Mexico and how the derived insights can be used for downstream analysis. The charts can also be applied to other scenarios to infer key data insights.</p><blockquote><strong><em>Note from the editors:</em></strong><em> </em><a href="http://towardsdatascience.com/"><em>Towards Data Science</em></a><em> is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click </em><a href="https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports"><em>here</em></a><em>.</em></blockquote><h3>References</h3><p>[1] Xu, Z., Shi, L., Wang, Y., Zhang, J., Huang, L., Zhang, C., … &amp; Tai, Y. (2020). Pathological findings of COVID-19 associated with acute respiratory distress syndrome. <em>The Lancet respiratory medicine</em>, <em>8</em>(4), 420–422.</p><p>[2]Garcia-Garcia G, Aviles-Gomez R, Luquin-Arellano VH, et al. Cardiovascular risk factors in the Mexican population. <em>Ren Fail</em>. 2006;28(8):677–687. doi:10.1080/08860220600936096</p><p>[3] Cascella, M., Rajnik, M., Cuomo, A., Dulebohn, S. C., &amp; Di Napoli, R. (2020). Features, evaluation, and treatment coronavirus (COVID-19). In <em>Statpearls [internet]</em>. StatPearls Publishing.</p><p>[4] World Health Organization. (2020). Coronavirus disease 2019 (COVID-19): situation report, 72.</p><p>[5] “The World’s Largest Slums: Dharavi, Kibera, Khayelitsha &amp; Neza.” <em>Habitat for Humanity GB</em>, 7 Sept. 2018, <a href="http://www.habitatforhumanity.org.uk/blog/2017/12/the-worlds-largest-slums-dharavi-kibera-khayelitsha-neza/">www.habitatforhumanity.org.uk/blog/2017/12/the-worlds-largest-slums-dharavi-kibera-khayelitsha-neza/.</a></p><p>[6] “8 Cities With the World’s Largest Slums.” <em>U.S. News &amp; World Report</em>, U.S. News &amp; World Report, <a href="http://www.usnews.com/news/cities/articles/2019-09-04/the-worlds-largest-slums.">www.usnews.com/news/cities/articles/2019-09-04/the-worlds-largest-slums.</a></p><p>[7] Mexico. (n.d.). Retrieved from <a href="https://ddi.sutd.edu.sg/portfolio/items/448588">https://ddi.sutd.edu.sg/portfolio/items/448588</a></p><p>[8] Chart of influenza mortality in America and Europe, 1918–1919 | Otis Historical Archives National Museum of Health and Medicine (http://www.flickr.com/photos/medicalmuseum/5857153474/in/set-72157614214049255) by licensed as CC-BY-NC-SA (http://creativecommons.org/licenses/by-nc-sa/2.0/uk/)</p><p>[9] DrEricDing. (2020, June 21). Holy moly- I’m crying for MEXICO [Tweet]. <a href="https://twitter.com/DrEricDing/status/1274816278197342209">https://twitter.com/DrEricDing/status/1274816278197342209</a></p><p>[10] <em>Original Photograph of Bailey the Golden Retriever Sitting at a Desk</em>. knowyourmeme. <a href="https://knowyourmeme.com/photos/1330845-i-have-no-idea-what-im-doing">https://knowyourmeme.com/photos/1330845-i-have-no-idea-what-im-doing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf702ec80d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/covid-19-an-overview-of-mexico-ccf702ec80d9">An overview of Covid-19 in Mexico</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COVID-19 coronavirus: Top ten most affected countries]]></title>
            <link>https://medium.com/data-science/covid-19-coronavirus-top-ten-most-affected-countries-c165171c50d7?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c165171c50d7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 17:37:14 GMT</pubDate>
            <atom:updated>2022-12-05T08:44:00.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis of the COVID-19 pandemic in North America</h3><h4>An in-depth look at the spread of covid-19 in North America</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*y6hjg5o-HRnvJX3peoJR3w.png" /><figcaption>Covid-19 in North America (Diego Hurtado)</figcaption></figure><h3>Introduction</h3><p>The purpose of this note is to describe the general panorama of the current situation in North America, this can serve for people to take useful social and health measures to stop the spread of COVID-19.</p><p>Since late December 2019, an outbreak of a novel coronavirus disease (COVID-19; previously known as 2019-nCoV) was reported in Wuhan, China, which has subsequently affected 210 countries worldwide. In general, COVID-19 is an acute resolved disease but it can also be deadly. Severe disease onset might result in death due to massive alveolar damage and progressive respiratory failure. As of December 03, 2022, about 645M cases have been confirmed, over 6.64M deaths.</p><h3>USA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Y22WdPC_79SsjquoHWOkFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Uv_4BbPr5pPbQIXTYINwgQ.png" /></figure><p>The dataset is obtained from “The New York Times. (2021). Coronavirus (Covid-19) Data in the United States [4]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*x9pvz3BlMb3TCpfXtEO3aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*g-jWCeGdIC55iD34wYSPeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*suXSJvP5A9G3_IGd2Dhswg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*qeNnP1URVG9AgvQFltMJjw.png" /></figure><h4>States</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*J8wn28oHpjXlEXAaKz86yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*oWY-WxtyiHXHjPqH2b-WTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*yAJXZDO2_dQ8Rhm6UcV0xg.png" /></figure><h3>California</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cxeTwNqBKrhAYETPw63t_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*EKRAi4OsV-Vnook_BQ2MgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*E0bir-kMKxyb9SV3Dnl9Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Hwkksnq--Qc4FzwW3m_1yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*C0PUpy2HT6_qTbho3UwcWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*vgDlqnV9Fu7FApcKM5lzHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*eTHjg5HZHKBfx4HlaF0TqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*O5DL0l8LdvCeGH4PEMihWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*c7ddH-_puyw7S5vuKnFPvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*0Llhivp_AQz5Wa2-869lBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Z47tNbDjbovhSvSkRKhGQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*FDk5HsfH-zPRGBgEKS7G1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*uUj966Eqq-S2HO_XqV1vrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*NEUjXGnDKmHzGzclT4aHLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*L6XpYnDrYQ5euHIs0vsVjw.png" /></figure><h3>Texas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hl3ohGVfQbiEe1iuG8DHRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*AqsT8fs5GO1SRN_mjUPzIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*rJa5BhfYyU1CXsYlg6ZHlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*H6gAhHteuJ7lE8qSEvRBWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*aV0blCMVdakJQYi1GXE8dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*-9Prazv3Y2Hm0I-Jwit73g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*mtKg82vj0qBR6abWBU3kcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*zGv5PL_ZuKHeCc8KFN7TjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Lqtab3lL2hq3F-NFm5Aohw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1CImMCVLuL4YQkRZKnbXoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*B1XLdTPpBbMCml7vnethvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Q1kDjnXaVV5-duZJli0LTA.png" /></figure><h3>Florida</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JwUXPxkLdLZUZAgEfeN2HA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*plFyTabNRaVkYWyWYrFjJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*AfA3gQ43kaEWir1jCOA9OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZcaSQkFebgp4M4FIY2lBDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gaDv3RmtYD_3Ogd-Zb9_Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*cRmIhGe3USSo3jZgBkWPvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*UaaoUUWmH3ME5eamyB3rwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*PqKDZ6utVMEu9JMPN4L43g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*-zWlpfSbKq3llwzjGwvpHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BRFveYRFe5gxICYRia3KGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*TfWxIUdw3T8ss035keJ2Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*4hrgAEhRFiCiUveJSWLr5w.png" /></figure><h3>New York</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0AdwL_DtZCRe0dC2WRHu6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UhThQSm6qcljdcyT55UUnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Q_Rt3OPvUoIA7NZoj8EG1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9Q-WUWe23ATBdRHm7Qg8mA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*c1PVFLtU8ry_Wz-3x_JNvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*G58cNwvj4nrctFIMxID7EQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5k5CGwrM7wrPJWrhDroSkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ywXhuQcw_OYgZeWlnpl-sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*zGv5PL_ZuKHeCc8KFN7TjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*877hw9srgXzcO63tWkzS2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*alvklZAN9rdL4LlqjS_1oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*wZ59bEdPbtynEiD3v9LsAQ.png" /></figure><h3>Covid 19 — Mexico Overview 🇲🇽</h3><p>I am using time series of confirmed/death cases with combination of a dataset of description of the person during covid</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*m7P_xKqcyFdEptF77Kqt6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QwnC3Xu_FzMSxwZBJloO1w.png" /><figcaption><strong>Confirm cases (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jRSJUl9ZrZEyqbT_65GAiQ.png" /><figcaption><strong>Period with most of the confirm cases . the 3rd wave ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*C5nUKmjxbz-bvByUyaadfw.png" /><figcaption><strong>Death cases Mexico ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kOkZCxhajiwu8wbtA4HaSg.png" /><figcaption><strong>Period with most of the death cases ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*mjZtK7cdUtGt5tahoa2mAA.png" /><figcaption><strong>Dead ranges cases by age (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*tu9o6MCxGwR5B6EOnc5z1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*DO3Os8gELgN3hVDm4nEvtQ.png" /><figcaption><strong>Confirm range cases by age (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXHBMMJZ3DkJRKkXR5lmHQ.png" /><figcaption><strong>Age distribution by confirm cases (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UEBqp-mrMRIUbpJPV-gYmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLqcjeZw9Cavz6VS9xeThw.png" /><figcaption><strong>Proportion of confirm cases by gender (Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcwfXdiyDrcjaXO6YTQ2hw.png" /><figcaption><strong>Percentage of people Hospitalized (Diego Hurtado)</strong></figcaption></figure><h3>Mexico`s Mobility 🚗 🇲🇽</h3><blockquote>The president of Mexico starts the “<strong>new normality</strong>” in May to “reactivate” the economy, despite of the spike in infections</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nhEYm-KA_zD1etMU.jpg" /><figcaption>Outside a shop, customers waiting without respecting the healthy distance. Av. Juárez corner with Eje Central, CDMX. May 21, 2020. <strong>Photo: </strong><em>Angélica Escobar/Forbes México.</em></figcaption></figure><p><strong>Observation:</strong></p><p>We can see that Confirm/ Deaths / mobility start to growth in <strong>May 2021</strong> when the ‘<strong><em>new normality’</em></strong> started</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*C5nUKmjxbz-bvByUyaadfw.png" /><figcaption><strong>Death cases Mexico ( Diego Hurtado)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QwnC3Xu_FzMSxwZBJloO1w.png" /><figcaption><strong>Confirm cases (Diego Hurtado)</strong></figcaption></figure><p>I am using different datasets to see the mobility trends in Mexico during Covid 19</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*G5hkuea_XRXg_gMYq37wtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*LoRQusAaxrdx4x9Yw6CVRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*dPuMdb0TFSm8vQqCv63seg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*_Lv2fgo5UOBB2IvHuGFnUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*THkByvS5kzMQ5nmn9vFN_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*h_Zx-ELdJ8-AXJnPrFc2QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*2t1jTFm4SKQF8l-a6GAqTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*7B6hy0qhMb6lcfDp1cOIBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*IPXbUxj_bIHO97rsVPitDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*s5JFcn6x48l040OpWnkE8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*M0HENPJZ1rny0NGeJ3mFFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*cXBqC_vapSAH8WtU3f69vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*VzZQUOn08PEQXgCjhhpS7Q.png" /></figure><p>“The new normal is an illusion, we are in the midst of epidemic activity and I think that proposing the restart of social activity at this time is virtually <strong>suicidal</strong>, I think this can reactivate, at levels not yet seen, the number of sick people and of the dead ” — <strong>Malaquías López Cervantes</strong></p><h3>Canada</h3><h4>Confirmed cases by province</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_CdC-4_3tIJWDcb2ZWvS3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fO7CkxhQvev8mG0s3FVHAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*cZHh4vaRRLRm1ZJBIQ7aDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-3_0ddnzSuP_DRIkU2bFeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*3Gww2S1NOFt3MJ47Xdf3Bg.png" /></figure><h4>Death cases by province</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_um3dAk-qITN945jVqisLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2ddXZCr-Yfylu40CwkVjrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*vI4h8shvmXqVm3u1lcs_6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*NDjaPwCK_SMGeiS0ud5nkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*aHb7UsZTCErfTZC29aJqPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*s1FJzk3K4k5KSvcX24a77g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*bKq9jORiJ8J6mpUqUp5S1w.png" /></figure><h3><strong>Cases by state</strong></h3><h4>Ontario</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ckVi-RRVaa29FBsjZBEfGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Z1pKM7kgGrVTQbdhuP3CvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UizmTA7woDCQiie7CQGwUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*MoFSQnde0baF-Lu-Y8-7rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*g4-WGMwXUZaZ39Mtj9T3xA.png" /></figure><h4>Quebec</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VOXtPAUAmjzZgfhlZUzvTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Ghrw_p7X3NVshmhCmev1TQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*l28mnMqPmKhTVEKE0hQwWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*dvgYh6UaJQ2fXfKpfgD_1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ooPvCNslRCdv2l0f784R-g.png" /></figure><h4>Alberta</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZI7xiZZCFg1f2Uo1pcgR4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*v9ze6AkaY_KnVPUNvRhwzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*OkS_Uw62ohSdqYekLZVJsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*-Yj-rqM3kRurRKm0CtM-vg.png" /></figure><h3>BTW : I am looking for new job opportunities! 📊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAZXGJ1C8P2CKDGtAUfRWQ.png" /></figure><p>I’m looking for an opportunity where I can put those abilities to work for a mission I’m passionate about!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*G4ayscstHmnUhs_-" /></figure><blockquote>“When you are asked if you can do a job, tell ’em, ‘Certainly I can!’ Then get busy and find out how to do it.” — Theodore Roosevelt.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0kAkOvVbouenRFwD.jpg" /><figcaption>Bailey the Golden Retriever Sitting at a Desk (knowyourmeme, 2022)</figcaption></figure><p><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/">https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/</a></p><p><a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/"><strong>Msc. Diego Hurtado</strong></a><br><strong> Business Analysis Consultant</strong></p><h3>Reminder</h3><p>The 1918 influenza pandemic was the most severe pandemic in recent history. It was caused by an H1N1 virus with genes of avian origin. Although there is no universal consensus regarding where the virus originated, it spread worldwide during 1918–1919.</p><p>The number of deaths was estimated to be at least 50 million worldwide with about 675,000 occurring in the United States.</p><p>Mortality was high in people younger than 5 years old, 20–40 years old, and 65 years and older. The high mortality in healthy people, including those in the 20–40 year age group, was a unique feature of this pandemic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*85VctOhmYZ_xGvJJGJEz6g.png" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><p>Influenza Pandemic | Mortality in America and Europe during | 1918 and 1919.’ Chart: “Influenza pandemic. Mortality in America and Europe during 1918 and 1919.” Deaths from all causes each week expressed as an annual rate per 1000. Includes lines representing New York, London, Paris, and Berlin.</p><blockquote><strong><em>We are Here.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*RN0yBFn9VfPtKD_EFLezFQ.png" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><p><strong>Conclusion:</strong></p><p>This article gives a detailed analysis of how COVID-19 has impacted the world and how the derived insights can be used for downstream analysis. The charts can also be applied to other scenarios to infer key data insights.</p><p>I hope all of you enjoyed this post. All of the graphs were created using <a href="https://plot.ly/graphing-libraries/">Plotly</a>. Plotly is a wonderful visualization library for building interactive plots. They have graphing libraries in Python and JavaScript.</p><p>LinkedIn: <a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/">https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/</a></p><p><strong>Note from the editors:</strong> <a href="http://towardsdatascience.com/">Towards Data Science</a> is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click <a href="https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports">here</a>.</p><h3>References</h3><p>[1] Xu, Z., Shi, L., Wang, Y., Zhang, J., Huang, L., Zhang, C., … &amp; Tai, Y. (2020). Pathological findings of COVID-19 associated with acute respiratory distress syndrome. <em>The Lancet respiratory medicine</em>, <em>8</em>(4), 420–422.</p><p>[2] Cascella, M., Rajnik, M., Cuomo, A., Dulebohn, S. C., &amp; Di Napoli, R. (2020). Features, evaluation, and treatment coronavirus (COVID-19). In <em>Statpearls [internet]</em>. StatPearls Publishing.</p><p>[3] World Health Organization. (2020). Coronavirus disease 2019 (COVID-19): situation report, 72.</p><p>[4] Chart of influenza mortality in America and Europe, 1918–1919 | Otis Historical Archives National Museum of Health and Medicine (http://www.flickr.com/photos/medicalmuseum/5857153474/in/set-72157614214049255) by licensed as CC-BY-NC-SA (http://creativecommons.org/licenses/by-nc-sa/2.0/uk/)</p><p>[5] “The New York Times. (2021). Coronavirus (Covid-19) Data in the United States. Retrieved [Insert Date Here], from <a href="https://github.com/nytimes/covid-19-data">https://github.com/nytimes/covid-19-data</a>.&quot;</p><p>[6] Google LLC <em>“Google COVID-19 Community Mobility Reports”</em>.<br>https://www.google.com/covid19/mobility/ Accessed: &lt;fecha&gt;.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c165171c50d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/covid-19-coronavirus-top-ten-most-affected-countries-c165171c50d7">COVID-19 coronavirus: Top ten most affected countries</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyze and Visualize Data for COVID-19: Mexico]]></title>
            <link>https://medium.com/data-science/analyze-and-visualize-data-for-covid-19-mexico-b33cddf386bf?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b33cddf386bf</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[impact]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 16:21:00 GMT</pubDate>
            <atom:updated>2021-02-16T05:02:53.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 10 countries most affected by coronavirus and Mexico</h3><h4>An in-depth look at the spread of Covid-19 in Mexico with the top 10 worst-hit countries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RsZIhtiAfkOq4wkKYzbpAQ.png" /><figcaption>Choropleth map Mexico Confirmed cases density (Diego Hurtado)</figcaption></figure><p>By: <a href="https://medium.com/u/3b572bafb88a">Diego Hurtado</a></p><h3>Introduction</h3><p>The purpose of this note is to describe the general panorama of the current situation in Mexico with the most affected countries, this can serve for people to take useful social and health measures to stop the spread of COVID-19.</p><p>Since late December 2019, an outbreak of a novel coronavirus disease (COVID-19; previously known as 2019-nCoV) was reported in Wuhan, China, which has subsequently affected 210 countries worldwide. In general, COVID-19 is an acute resolved disease but it can also be deadly, with a 29% case fatality rate. As of Jan <strong>19</strong>, 2020, about 103M cases have been confirmed, over 2.24 M deaths and 57.3 M recovered in <strong>Mexico.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1gR02pLJSA-_U4VnBp-rFA.png" /><figcaption>Covid cases distribution (Diego Hurtado)</figcaption></figure><h3>Symptoms</h3><p>People may be sick with the virus for 1 to 14 days before developing symptoms. The most common symptoms of coronavirus disease (COVID-19) are fever, tiredness, and dry cough. Most people (about 80%) recover from the disease without needing special treatment [2].</p><ul><li>cough</li><li>fever</li><li>tiredness</li><li>difficulty in breathing(severe cases)</li></ul><h3>Recommendations</h3><p>Interrupt human-to-human transmission including reducing secondary infections among close contacts and health care workers, preventing transmission amplification events, and preventing further international spread [3].</p><ul><li>Identify, isolate and care for patients early, including providing optimized care for infected patients;</li><li>Identify and reduce transmission from the animal source;</li><li>Address crucial unknowns regarding clinical severity, the extent of transmission and infection, treatment<br>options, and accelerate the development of diagnostics, therapeutics, and vaccines;</li><li>Communicate critical risk and event information to all communities and counter misinformation;</li><li>Minimize social and economic impact through multisectoral partnerships</li></ul><h3>Data</h3><p>Novel Corona Virus (COVID-19) epidemiological data since 22 January 2020. Data loading from the <a href="https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series">John Hopkins CSSE data repository</a> from various sources including the World Health Organization (WHO), DXY.cn. The data is updated twice on a daily basis.</p><p>Fields available in the data include Province/State, Country/Region, Last Update, Confirmed, Suspected, Recovered, Deaths.</p><p>On 23/03/2020, a new data structure was released. The current resources for the latest time-series data are:</p><ul><li>time_series_covid19_confirmed_global.csv</li><li>time_series_covid19_deaths_global.csv</li><li>time_series_covid19_recovered_global.csv</li></ul><pre>confirmed_df = pd.read_csv(&#39;<a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv&#39;">https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv&#39;</a>)</pre><pre>recovered_df = <br>pd.read_csv(&#39;<a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv&#39;">https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv&#39;</a>)</pre><pre>country_df = pd.read_csv(&#39;<a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_country.csv&#39;">https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_country.csv&#39;</a>)</pre><h3>Mexico Overview 🇲🇽</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF5Hfk49ZUsXKXyb1ZUllw.png" /><figcaption>Mexico 🇲🇽 COVID Dashboard (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*1k6PvCXW3IYcrnlFbpVRkw.png" /><figcaption>Mexico Overview 🇲🇽 (Diego Hurtado)</figcaption></figure><h3>🇲🇽 Mexico (#3) occupies third place in deaths cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ppiFsFaiMOvC5wPeQFu7vg.png" /><figcaption>Choropleth Map Mortalty Rate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BPGhrj7IWYs467pSSKiFsw.png" /><figcaption>🇲🇽 Mexico (#3) third place in deaths cases (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8gJJ1tDg5HmEfJSqRNdH9w.png" /><figcaption>🇲🇽 Mexico (#3) third place in mortality rate (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbLN3RhCwVF5dumsL-v2tg.png" /><figcaption>Age distribution of death cases in Mexico</figcaption></figure><h3>🇲🇽 Mexico (#3) occupies third place in Mortality Rate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wveWKFj0RuVoFVQVjfvqmg.png" /><figcaption>🇲🇽 Mexico (#3) third place in mortality rate (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vZ5yjT4Wjs90IYONbIBgqA.png" /><figcaption>🇲🇽 Mexico (#3) third place in mortality rate (Diego Hurtado)</figcaption></figure><h3>🇲🇽 Mexico (#3) occupies fourth place in critical cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LNJc9qqhODglAl3CyqyNmw.png" /><figcaption>🇲🇽 Mexico (#4) occupies third place in deaths cases</figcaption></figure><h3>🇲🇽 Mexico Overview by states</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhxU5JyDIuyBcNxuecQAWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pE7Kv3bo9h3ioO7I6UktZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga1aqy72_YbfI_LBYMI-uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYiYfoyZBBbN61YOLUpCYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUKHRJZ04QTciiE4Us_bww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZmGxud5WHx4jL-_0CJR-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHwYbKMsaD0H42-BKgVsOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ajw_Ewvm92EryZk4Dz-Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lWXyyz07JPLrvb9dKopQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeMqpTqdY_mOkM-0K4y_HA.png" /><figcaption>COVID-19 in Mexico: Total confirmed cases by states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpIuY0ObtBaCwEdI98MmiQ.png" /><figcaption>COVID-19 in Mexico: Total death cases by states (Diego Hurtado)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9wTMGMG7HwKZlq1CFlatQ.png" /><figcaption>The state with most deaths is Mexico city</figcaption></figure><h3>Mexico Analysis 🇲🇽</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgtAVUCzrnAVEpz-if-0gA.png" /><figcaption><a href="https://towardsdatascience.com/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Choropleth map Mexico </a>death cases density (Diego Hurtado)</figcaption></figure><h3>Mexico`s Mobility 🇲🇽</h3><blockquote>The president of Mexico starts the “<strong>new normality</strong>” in May to “reactivate” the economy, despite of the spike in infections</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nhEYm-KA_zD1etMU.jpg" /><figcaption>Outside a shop, customers waiting without respecting the healthy distance. Av. Juárez corner with Eje Central, CDMX. May 21, 2020. <strong>Photo: </strong><em>Angélica Escobar/Forbes México.</em></figcaption></figure><p><strong>Observation:</strong></p><p>We can see that in May the confirmed and death cases started to growth exponentially!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZY6aJU6s2bEj-F29N_bnkg.png" /><figcaption>The relation between Confirmed Cases and Deaths in Mexico (Diego Hurtado)</figcaption></figure><p><strong>Confirmed Cases:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aX3i1CPH3Zh-OhX7yyiUQw.png" /><figcaption>Time series confirmed cases Mexico (Diego Hurtado)</figcaption></figure><p><strong>Death Cases:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dJ7_bdj4RNtIPdtlyytm5Q.png" /><figcaption>Time series confirmed cases Mexico (Diego Hurtado)</figcaption></figure><h4>Mobility behavior of the states with the most death cases (State of Mexico)</h4><p>We can see that mobility start to growth in <strong>May</strong> when the new normality started</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sS3pRU-OqP2mT5EXQp8Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*vFsZu5fGGoe1u0alONvcUw.png" /></figure><p>“The new normal is an illusion, we are in the midst of epidemic activity and I think that proposing the restart of social activity at this time is virtually <strong>suicidal</strong>, I think this can reactivate, at levels not yet seen, the number of sick people and of the dead ” — <strong>Malaquías López Cervantes</strong></p><h3>Mexico`s health 🇲🇽</h3><p>Severe disease onset might result in death due to massive alveolar damage and progressive respiratory failure. The Covid-19 pandemic is of high risk for patients on chronic hemodialysis due to their immunosuppressed state, advanced age, and the coexistence of significant comorbidities, in particular cardiovascular disease, diabetes mellitus, and others. Also remarkable that cardiovascular risk factors are highly common among the Mexican population and increasing at alarming rates, Cardiovascular diseases represent the first cause of death in Mexico [2].</p><h4>Age distribution of death cases in Mexico</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKMIziDCkdm_338CcDwOdw.png" /><figcaption>Age distribution of death cases in Mexico</figcaption></figure><h4>Age distribution of death cases in the state with the most deaths (State of Mexico)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjNUbMaLHUH2XiAvgvhBXg.png" /><figcaption>Age distribution of death cases in Mexico</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Dn4kNiW__E5tzTJ_zHQ12g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*XLvNjfp4TaW4VqtZZwvjzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ghCjEStqXBIISOWzD8iCrg.png" /></figure><h3>Mexico`s Vaccines 🇲🇽</h3><p>We can observe that countries like Israel 58% has the first dose, while Mexico only the 0.5 %</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tyu0xcD-vRNEePHUAZ1dBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*MiRA-FmAYjKFadhOgP5HtQ.png" /><figcaption>Top 10 countries Percentage Vaccinated</figcaption></figure><p>Today, by the most conservative estimates, about 900 million <a href="http://www.habitatforhumanity.org.uk/what-we-do/where-we-work/slum-definition">people live in slums</a> [4]. By 2030, it’s estimated that 1 in 4 people on the planet will live in a slum or other informal settlement. Let’s take a tour of the <a href="http://uk.reuters.com/article/uk-slums-united-nations-world-insight-idUKKBN12H1GK">world’s biggest slums</a>:</p><ul><li>Khayelitsha in Cape Town (South Africa): 400,000</li><li>Kibera in Nairobi (Kenya): 700,000</li><li>Dharavi in Mumbai (India): 1,000,000</li><li><strong>Neza (Mexico): 1,200,000</strong></li><li>Orangi Town in Karachi (Pakistan): 2,400,000</li></ul><p><strong>Ciudad Nezahualcoyotl (Neza), Mexico City</strong></p><p>Population: 1.1 million</p><p>While some contend that Ciudad Nezahualcoyotl, also known as Neza, has evolved from a <a href="https://www.reuters.com/article/us-mexico-slum-neza-idUSKBN12E1F2">slum into a suburb</a>, the brick-and-mortar houses are scattered among improvised shanties, and the neighborhood is considered extremely dangerous, even by drug war-plagued Mexico’s standards [5]. Community action prompted the government to formalize land titles, start garbage collection, and build some other key infrastructure. Now, about <a href="https://www.citylab.com/equity/2017/06/how-a-slum-became-a-city/529488/">70% of residents work within the area</a>, which is Mexico’s most densely populated municipality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uY50cAY047yW_gHc.jpg" /><figcaption>An aerial view of Ciudad Neza, short for Nezahualcóyotl, Mexico state, Mexico on September 30, 2016. Thomson Reuters Foundation/Johnny Miller</figcaption></figure><p><strong>Observation:</strong></p><p><em>Evidently COVID-19 is spreading faster and has a higher mortality rate in Mexico, people living in slums could be a key factor in this case. </em>Perhaps this is the reason why in Mexico coronavirus cases keep increasing.</p><h3>Mexico Needs to Take Action</h3><p><strong>Predictive Monitoring of COVID-19 in Mexico: </strong>COVID-19 predictions are fundamentally important for rationalizing planning and mentality, but also challenging due to the innate uncertainty of the complex, dynamic and global COVID-19 pandemic as a typical <a href="https://en.wikipedia.org/wiki/Wicked_problem">wicked problem</a>. Traditional prediction or forecasting efforts, which aim to make an accurate prediction now to come true in the future, might be misleading in this context of extreme uncertainty</p><h3>Correlation between Mexico and the countries of Latin America</h3><p>I extracted COVID-19 daily new cases and deaths in Latin America from the Johns Hopkins COVID-19 data repository. I use linear regression to test the correlation between Mexico and the countries of Latin America to examine correlations, respectively. The country with the most correlations is brazil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qw1fVTakcgsTehkFP6YTzw.png" /><figcaption>Data relation between Mexico and Brazil (Diego Hurtado)</figcaption></figure><p><strong><em>It is interesting that the two countries are governed by a left-wing country.</em></strong></p><h3>Annex</h3><p>Epidemiologist and health economist <strong>Eric Feigl-Ding </strong>compared the positive cases of coronavirus in the country with those in cities such as New York, Madrid, and Lombardy and warned that the percentage of positivity in Covid-19 tests that Mexico would be experiencing is unprecedented.</p><p>This is because more than half of the tests performed are positive for the virus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4ts2DeSgRkt7eiAfmw2Syw.png" /><figcaption>DrEricDing. (2020, June 21)</figcaption></figure><blockquote>“I am crying for Mexico. More than 50% is the percentage of *POSITIVITY* More than half of all those who take a test are positive,” said the scientist on Twitter about the coronavirus cases.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*UZ6IYpsmKlKi_Okq" /><figcaption>DrEricDing. (2020, June 21)</figcaption></figure><blockquote>Mexico per capita cases and mortality versus the US. There is clearly underdiagnosis in Mexico and poor treatment. The 56% positivity reflects that. So yes, damnit, we need more testing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*2vQ435eRI6SIAIVA" /></figure><h3>Reminder</h3><p>The 1918 influenza pandemic was the most severe pandemic in recent history. It was caused by an H1N1 virus with genes of avian origin. Although there is no universal consensus regarding where the virus originated, it spread worldwide during 1918–1919.</p><p>The number of deaths was estimated to be at least 50 million worldwide with about 675,000 occurring in the United States.</p><p>Mortality was high in people younger than 5 years old, 20–40 years old, and 65 years and older. The high mortality in healthy people, including those in the 20–40 year age group, was a unique feature of this pandemic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*85VctOhmYZ_xGvJJGJEz6g.png" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><p>Influenza Pandemic | Mortality in America and Europe during | 1918 and 1919.’ Chart: “Influenza pandemic. Mortality in America and Europe during 1918 and 1919.” Deaths from all causes each week expressed as an annual rate per 1000. Includes lines representing New York, London, Paris, and Berlin.</p><blockquote><strong>We are Here.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*T0GRDo_-tqZpKJ8WLE0uEA.jpeg" /><figcaption>Influenza pandemic chart (Reeve 003143), National Museum of Health and Medicine</figcaption></figure><p><strong>Conclusion:</strong></p><p>This article gives a detailed analysis of how COVID-19 has impacted Mexico and the world and how the derived insights can be used for downstream analysis. The charts can also be applied to other scenarios to infer key data insights.</p><p>I hope all of you enjoyed this post. All of the graphs were created using <a href="https://plot.ly/graphing-libraries/">Plotly</a>. Plotly is a wonderful visualization library for building interactive plots. They have graphing libraries in Python and JavaScript.</p><p>LinkedIn: <a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/">https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/</a></p><blockquote><strong><em>Note from the editors:</em></strong><em> </em><a href="http://towardsdatascience.com/"><em>Towards Data Science</em></a><em> is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click </em><a href="https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports"><em>here</em></a><em>.</em></blockquote><h3>References</h3><p>[1] Xu, Z., Shi, L., Wang, Y., Zhang, J., Huang, L., Zhang, C., … &amp; Tai, Y. (2020). Pathological findings of COVID-19 associated with acute respiratory distress syndrome. <em>The Lancet respiratory medicine</em>, <em>8</em>(4), 420–422.</p><p>[2] Cascella, M., Rajnik, M., Cuomo, A., Dulebohn, S. C., &amp; Di Napoli, R. (2020). Features, evaluation, and treatment coronavirus (COVID-19). In <em>Statpearls [internet]</em>. StatPearls Publishing.</p><p>[3] World Health Organization. (2020). Coronavirus disease 2019 (COVID-19): situation report, 72.</p><p>[4] “The World’s Largest Slums: Dharavi, Kibera, Khayelitsha &amp; Neza.” <em>Habitat for Humanity GB</em>, 7 Sept. 2018, <a href="http://www.habitatforhumanity.org.uk/blog/2017/12/the-worlds-largest-slums-dharavi-kibera-khayelitsha-neza/">www.habitatforhumanity.org.uk/blog/2017/12/the-worlds-largest-slums-dharavi-kibera-khayelitsha-neza/.</a></p><p>[5] “8 Cities With the World’s Largest Slums.” <em>U.S. News &amp; World Report</em>, U.S. News &amp; World Report, <a href="http://www.usnews.com/news/cities/articles/2019-09-04/the-worlds-largest-slums.">www.usnews.com/news/cities/articles/2019-09-04/the-worlds-largest-slums.</a></p><p>[6] Mexico. (n.d.). Retrieved from <a href="https://ddi.sutd.edu.sg/portfolio/items/448588">https://ddi.sutd.edu.sg/portfolio/items/448588</a></p><p>[7] Chart of influenza mortality in America and Europe, 1918–1919 | Otis Historical Archives National Museum of Health and Medicine (http://www.flickr.com/photos/medicalmuseum/5857153474/in/set-72157614214049255) by licensed as CC-BY-NC-SA (http://creativecommons.org/licenses/by-nc-sa/2.0/uk/)</p><p>[8] DrEricDing. (2020, June 21). Holy moly- I’m crying for MEXICO [Tweet]. <a href="https://twitter.com/DrEricDing/status/1274816278197342209">https://twitter.com/DrEricDing/status/1274816278197342209</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b33cddf386bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/analyze-and-visualize-data-for-covid-19-mexico-b33cddf386bf">Analyze and Visualize Data for COVID-19: Mexico</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make a Covid-19 Choropleth Map in Mapbox]]></title>
            <link>https://medium.com/data-science/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907?source=rss-3b572bafb88a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c93ac86e907</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[mapbox]]></category>
            <category><![CDATA[built-with-mapbox]]></category>
            <dc:creator><![CDATA[Diego O’Hurtado]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 23:39:46 GMT</pubDate>
            <atom:updated>2020-05-14T03:04:53.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Visualization of the Covid-19 rate across states in the USA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIL5MxvErJUOm35MwAL4Fw.png" /><figcaption>US Covid-19 Confirmed Cases. (Diego Hurtado)</figcaption></figure><p>By: <a href="https://medium.com/u/3b572bafb88a">Diego Hurtado</a></p><p>One way to show data distribution on a map is with a choropleth, a thematic map in which areas are shaded based on a particular value. Choropleth maps provide an easy way to visualize how a measurement varies across a geographic area or show the level of variability within a region, is a type of <a href="https://en.wikipedia.org/wiki/Thematic_map">thematic map</a> in which areas are shaded or patterned in proportion to a statistical variable that represents an aggregate summary of a geographic characteristic within each area, such as population density or Covid-19 cases. In this guide, you will use Mapbox Studio and Mapbox GL JS to make a map of US states showing Covid-19 confirmed cases density.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zV4ooaA1wJLRy9MFzKUZ_w.png" /><figcaption>US states showing Covid-19 confirmed cases density (Diego Hurtado)</figcaption></figure><h3><strong>Getting started</strong></h3><p>You will be using two Mapbox tools throughout this guide:</p><ul><li><a href="https://docs.mapbox.com/help/glossary/mapbox-studio">Mapbox Studio</a> to add your data and create your map style.</li><li><a href="https://docs.mapbox.com/help/glossary/mapbox-gl-js">Mapbox GL JS</a> to add interactivity to your map and publish it on the web.</li></ul><h3>Dealing with the data</h3><p>To start, download the from the <a href="https://covidtracking.com/api/states/daily">US Covid-19 Tracking</a> API, the <a href="https://vega.github.io/vega-datasets/data/us-state-capitals.json">US State Capitals</a>, and the <a href="https://raw.githubusercontent.com/DiegoFurtt/Covid-19-Choropleth-Map/master/covidData.geojson">GeoJSON</a> object that represents the US space (Geometry). According to <a href="https://tools.ietf.org/html/rfc7946">GeoJSON Specification (RFC 7946)</a>:</p><blockquote>GeoJSON is a format for encoding a variety of geographic data structures […]. A GeoJSON object may represent a region of space (a Geometry), a spatially bounded entity (a Feature), or a list of Features (a FeatureCollection). GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection. Features in GeoJSON contain a Geometry object and additional properties, and a FeatureCollection contains a list of Features.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*1krfso9B5UX8cxvV9YRJAw.png" /><figcaption>US space Geometry geoJson (Diego Hurtado)</figcaption></figure><p>We can even use these properties to style our Leaflet vectors. Here’s an example of the GeoJSON :</p><pre>var geojsonFeature = {     <br>    &quot;type&quot;: &quot;Feature&quot;,     <br>    &quot;properties&quot;: {         <br>    &quot;name&quot;: &quot;Alabama&quot;,         <br>    &quot;density&quot;: 6270,         <br>    &quot;geometry&quot;: { &quot;type&quot;: &quot;Polygon&quot;, &quot;coordinates&quot;: []} <br>};</pre><h3>Data cleanup</h3><p>Once you download the files, filter, and clean up the data. Parts of this process are completely optional, like renaming or filtering fields. However, filtering states that the API does not have information (‘AS’, ‘GU’, ‘MP’, ‘VI’). Filter out unwanted features like Guam and other US territories that aren’t displayed in the USA projection. If you don’t filter these states like Guam, you will end up with null geometries after reprojecting, which can pose an issue with the index of the information.</p><p>Once you clean the data, replace the density value of the geoJSON with the confirmed data of every state.</p><pre>for i in range(1,len(s_array)):<br>    features = data_geo[&#39;features&#39;][i]<br>    features[&#39;properties&#39;][&#39;density&#39;] = int(s_array[i])<br>    <br>    data_geo[&#39;features&#39;][i][&#39;properties&#39;][&#39;density&#39;] =    int(confirmedCasesStates[i])</pre><p>Example of updating the data:</p><pre>data_geo[&#39;features&#39;][Alabama][&#39;properties&#39;][6270] =    int(confirmedCasesStates[6500])</pre><h3>Upload and style in Studio</h3><p>To learn to reproject your data to add to your projection, follow along with our how-to video of How to create a choropleth map in Mapbox Studio, Follow along with <a href="https://www.youtube.com/watch?v=HZpNeQC0Obg&amp;feature=emb_title">this tutorial</a> to create a choropleth map with Mapbox Studi if you missed some step. Source: <a href="https://www.mapbox.com/videos/how-to/create-a-choropleth-map-in-mapbox-studio/">Mapbox</a></p><p>To upload the GeoJSON file to Mapbox, drag it and drop it directly into the <a href="https://studio.mapbox.com/tilesets/">tileset dashboard</a>, or tile it using Tippecanoe if the file is too large or the geometries need simplification.</p><p>On your Tilesets page, click the <strong>New tileset</strong> button. Select the <a href="https://raw.githubusercontent.com/DiegoFurtt/Covid-19-Choropleth-Map/master/covidData.geojson">file</a> covidataStates.geojson and upload it to your account.</p><p>When the upload is complete, click on the arrow next to the filename to open its information page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*IdRqToLSEJyG0s0sEu2Rxg.png" /><figcaption>S<a href="https://www.mapbox.com/videos/how-to/create-a-choropleth-map-in-mapbox-studio/">ource: Mapbox</a></figcaption></figure><h3>Create a new style</h3><p>After you’ve inspected your data, it’s time to create a new style so you can put it on the map! Go to your <a href="https://studio.mapbox.com/">Styles page</a>. Click the <strong>New Style</strong> button. Find the <em>Basic Template</em> style and click <strong>Customize Basic Template</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*0cCRWjc4w6-XPsovkWOXMQ.png" /><figcaption>S<a href="https://www.mapbox.com/videos/how-to/create-a-choropleth-map-in-mapbox-studio/">ource: Mapbox</a></figcaption></figure><h3>Add a new layer</h3><p>To add and style the population density data, you will need to add a new layer to the map:</p><ol><li>If the styling panel is displaying the <strong>Components</strong> tab, toggle to the <strong>Layers</strong> tab.</li><li>At the top of the layer panel, click the <strong>+</strong> button to add a custom layer.</li></ol><p>n the <em>New layer</em> panel, look in the list of <em>Data Sources</em> for the statedata source. Click the tileset and then select the source layer as the source for this new style layer.</p><p>The default Basic map view is not centered on the United States. Mapbox Studio recognizes that the data you have uploaded is focused on a different location, so it displays the message <em>“This tileset isn’t available from your map view.”</em> Click <strong>Go to data</strong>, and the map view will refocus on the United States.</p><p>Your new layer will be highlighted on the x-ray map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Qhp6rGHdvEBy2wDSaqHpeA.png" /><figcaption>S<a href="https://www.mapbox.com/videos/how-to/create-a-choropleth-map-in-mapbox-studio/">ource: Mapbox</a></figcaption></figure><p>Click the <strong>Style</strong> tab and the map will switch back to style mode displaying your new layer. You will see the state data on the map with a default style (black with 100% opacity).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*HP5m0Pgstv_xBauHw7gnaQ.png" /></figure><h3>Style the layer</h3><p>In the Mapbox Studio style editor, you can assign a color to each state based on its COVID-19 Confirmed cases density. Click the <strong>Style</strong> link in the statedata layer. Next, click <strong>Style across data range</strong>.</p><p>Choose a numeric data field, select density since you want to style each state according to its COVID-19 Confirmed cases density.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*NqkqMvmZgh94O1-B2hr9yA.png" /></figure><p>The rate of change is <em>linear</em>. Click <strong>Edit</strong> and select <strong>Step</strong> instead. Click <strong>Done</strong>. Since you have set the rate of change to step, the colors for each range of density between stops will be uniform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*LJN0luDItx7RtHb-KYy4PQ.png" /></figure><p>Now it’s time to start adding stops and colors! You will create several stops to break states up into groups with similar COVID-19 Confirmed cases densities. Click on <strong>Edit</strong> in the first density stop. The first stop is fixed at <em>1.264</em>, based on the information in the data set you uploaded. Click on it and change the color to #FFEDA0. Click <strong>Done</strong>.</p><p>Change <em>density</em> of the next stop to 361, and change the color to #FFEDA0 as well. Click <strong>Done</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*fYlzY089MHkaa0LFWxPrkQ.png" /></figure><p>Click <strong>+ Add another stop</strong>. Change <em>density</em> to 361 (min value of the data), and change the color to #FED976. Click <strong>Done</strong>.</p><p>Create the following additional steps depending on the number of confirmed cases Example:</p><ul><li>341: #FED976</li><li>1050: #FEB24C</li><li>2000: #FD8D3C</li><li>5911: #FC4E2A</li><li>13319: #E31A1C</li><li>288054: #BD0026</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgRx2lq0PgTeHNmCrQt9Ug.png" /></figure><h3>Publish the style</h3><p>Now that you’ve got your map looking good, it’s time to publish! Click the <strong>Publish</strong> button in the top right of the screen, then click <strong>Publish</strong> again on the next prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*xUQ03EcKr9u-2skfWdqG8Q.png" /></figure><h3>Web Page</h3><p>Here’s what you need to get started:</p><p>Download the <a href="https://github.com/DiegoFurtt/Covid-19-Choropleth-Map/blob/master/choroplethMapbox.html">template</a>:</p><ul><li><a href="https://docs.mapbox.com/help/glossary/access-token"><strong>An access token</strong></a>. You can find your access tokens on your <a href="https://www.mapbox.com/account/">Account page</a>.</li><li>The <a href="https://docs.mapbox.com/help/glossary/style-url"><strong>style URL</strong></a> for your style. From your <a href="https://www.mapbox.com/studio">Styles</a> page, click on the <strong>Menu </strong>button next to your population density style and then click the clipboard icon to copy the <strong>Style URL</strong>.</li><li><a href="https://www.mapbox.com/mapbox-gl-js"><strong>Mapbox GL JS</strong></a>. The Mapbox JavaScript API for building web maps.</li><li><strong>A text editor</strong>. You’ll be writing HTML, CSS, and JavaScript after all.</li></ul><p>Now that you’ve added structure to the page, you can start writing some JavaScript! The first thing you’ll need to do is add your access token. Without this, the rest of the code will not work. <em>Note: all the following code should be between </em><em>script tags.</em>:</p><pre>mapboxgl.accessToken = &#39;pk.......&#39;;</pre><p>Now that you’ve added the structure of the page, you can add a map object to the map div. Be sure to replace your-style-url with the <a href="https://docs.mapbox.com/help/glossary/style-url">style URL</a> for the style you created in part 1 of this guide -- otherwise, the code won&#39;t work!</p><pre>var map = new mapboxgl.Map({<br>  container: &#39;map&#39;, // container id<br>  style: &#39;your-style-url&#39; // replace this with your style URL<br>});</pre><h3>Create arrays of intervals and colors</h3><p>Creating a list of the stops you used when styling your layer that contains state data will allow us to add a legend to our map in a later step.</p><pre>var layers = [&#39;0-10&#39;, &#39;10-20&#39;, &#39;20-50&#39;, &#39;50-100&#39;, &#39;100-200&#39;, &#39;200-500&#39;, &#39;500-1000&#39;, &#39;1000+&#39;];<br>var colors = [&#39;#FFEDA0&#39;, &#39;#FED976&#39;, &#39;#FEB24C&#39;, &#39;#FD8D3C&#39;, &#39;#FC4E2A&#39;, &#39;#E31A1C&#39;, &#39;#BD0026&#39;, &#39;#800026&#39;];</pre><h3>Mission complete</h3><p>You have created an interactive choropleth map!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIL5MxvErJUOm35MwAL4Fw.png" /><figcaption>visualization of the Covid-19 rate across states in the USA (Diego Hurtado)</figcaption></figure><p>To learn to reproject your data to add to your projection, follow along with our how-to video of <a href="https://www.youtube.com/watch?v=HZpNeQC0Obg&amp;feature=emb_title">“How to create a choropleth map in Mapbox Studio”.</a></p><p>Another example with the visualization of the Covid-19 rate across states in <a href="https://towardsdatascience.com/analyze-and-visualize-data-for-covid-19-mexico-b33cddf386bf">Mexico</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-L9gna1MalelJ-72wMHUFw.png" /><figcaption>Visualization of the Covid-19 rate across Mexico</figcaption></figure><p>LinkedIn: <a href="https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/">https://www.linkedin.com/in/diego-gustavo-hurtado-olivares/</a></p><p><a href="https://twitter.com/hashtag/BuiltWithMapbox?">#BuiltWithMapbox</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c93ac86e907" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/make-a-covid-19-choropleth-map-in-mapbox-5c93ac86e907">Make a Covid-19 Choropleth Map in Mapbox</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>