<?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 Janos Tolgyesi on Medium]]></title>
        <description><![CDATA[Stories by Janos Tolgyesi on Medium]]></description>
        <link>https://medium.com/@janos.tolgyesi?source=rss-539653be15a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tqzDeXq3W0RaDjke0Gm9Fg.png</url>
            <title>Stories by Janos Tolgyesi on Medium</title>
            <link>https://medium.com/@janos.tolgyesi?source=rss-539653be15a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:03:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janos.tolgyesi/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[Mind the layers: a three-layer model for document AI]]></title>
            <link>https://medium.com/data-science-collective/mind-the-layers-a-three-layer-model-for-document-ai-4e153585e5c0?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e153585e5c0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 00:00:50 GMT</pubDate>
            <atom:updated>2026-10-06T13:30:07.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Piping a PDF straight into the prompt works in demos. In production, you need three layers to tell which one broke.</h4><figure><img alt="Abstract illustration: translucent layers of teal, grey and amber stacked like soft waves across a pale background." src="https://cdn-images-1.medium.com/max/1024/0*UYBAweAPIGC-rtdM.png" /><figcaption>Image generated by the author with OpenAI’s ChatGPT</figcaption></figure><p>In case you missed the <a href="https://medium.com/@janos.tolgyesi/pragmatism-for-document-ai-8b43792d9ab9">previous episode</a>: I argued that there is no single universal schema for what a document <em>means</em>, because what matters about a document is relative to the question you are asking. Knowledge is structured by use, the categories we extract are tools rather than universal truths, and the design move that follows is to <em>equip the inquiry</em> rather than model the document. That was the stance. This post is the architecture.</p><p>This is the second of a three-part series. <a href="https://medium.com/@janos.tolgyesi/pragmatism-for-document-ai-8b43792d9ab9">Part one</a> argued the case; part three will get into implementation. Here, in the middle, I want to make it concrete with a model I have come to rely on: the knowledge you pull out of a document lives on <em>three layers</em>, and the layers differ in how much of the work you can reuse from one document or task to the next. Then I will argue the single rule that keeps such a system debuggable when it breaks in production, which it will: <strong>never skip a layer</strong>. The model is the tidy part; the rule is the part that earns its keep at three in the morning. Let’s dive deeper.</p><h3>The three layers</h3><p>Here is the model in one sentence: the knowledge you extract from a document sits on three layers, and each layer has both a different <em>reuse profile</em> (how much of it carries over to the next document or task) and a different <em>epistemic status</em> (the kind of question it answers). I will take each layer in three beats: what it is, how reusable it is, and what kind of question it settles.</p><p><strong>Layer 1 is the document’s intrinsic structure</strong>: pages, blocks, tables, reading order, sections, signatures, the geometry of the thing on the page. This layer is <em>fully reusable</em>, because every document is, first and before anything else, a document: a contract, an invoice, a vaccination certificate, and a novel are all pages with blocks and a reading order. Its epistemic status is <em>perception</em>: it answers “what is physically on the page?” It is domain-free and, increasingly, engine-detectable by general-purpose <a href="https://en.wikipedia.org/wiki/Document_layout_analysis">document layout analysis</a>. Build it once, reuse it everywhere.</p><p><strong>Layer 2 is the domain’s entities and relations</strong>: the parties, dates, amounts, issuing authorities, and cross-references that a domain keeps caring about across documents. This layer is <em>partially reusable</em>. A sparse <a href="https://en.wikipedia.org/wiki/Upper_ontology">upper ontology</a> generalizes (most legal documents have parties and effective dates), and each domain extends it with its own. Its epistemic status is : it answers “what is this document about, in domain terms?” It is the layer that turns a block of text at coordinates on page four into “the governing-law clause naming the State of New York.”</p><p><strong>Layer 3 is workflow-specific knowledge</strong>: “is this a duplicate payment?”, “is this clause enforceable?”, “summarize this filing for the board.” This layer is <em>not reusable, and it should not be</em>. Its epistemic status is <em>inference</em>: it answers “what does this particular workflow need to conclude?” This is part one’s “equip the inquiry” layer, wearing its architectural hat. Each workflow builds the slice of knowledge its question needs, and retires it when the question changes.</p><p>None of this is specific to legal or financial documents. Run the same model over a novel and the layers still fall out cleanly: chapters, paragraphs, and dialogue at Layer 1; characters, places, and events at Layer 2; a question like “how does John change across the book?” at Layer 3. I will come back to that.</p><p>The following diagram shows the model, and the shortcut it warns against.</p><figure><img alt="Flowchart: a raw document flows down through Layer 1 (intrinsic structure, perception), Layer 2 (domain entities and relations, grounding) and Layer 3 (workflow knowledge, inference) to the workflow answer, while a dashed arrow skips straight from the document to the answer, labelled: errors compound, failure undiagnosable." src="https://cdn-images-1.medium.com/max/1024/1*k5DxqKMwU0QacgPE7nKdqQ.png" /><figcaption>Diagram by the author.</figcaption></figure><p>The three layers stacked from Layer 1 to Layer 2 to Layer 3, each labelled with its reuse profile and epistemic status; solid arrows extract, ground, then infer toward the answer, and a dashed arrow straight from the raw document marks the skip path this post argues against.</p><p>Hold on to the three epistemic statuses, because they turn out to be the point: <em>perception</em>, <em>grounding</em>, and <em>inference</em> are three different kinds of question, and a system that keeps them apart is a system that can tell you which one it got wrong.</p><h3>The shapes of Layer 2</h3><p>Layers 1 and 3 are easy to picture. Layer 2 is the interesting one, because it looks quite different from one domain to the next, and it is where most of the design judgment goes. Three contrasting examples make the point.</p><p>The first is the humble invoice, the same example that closed part one. An invoice has a <em>rich, stable</em> Layer-2 vocabulary: issuer, recipient, line items, amounts, tax, dates, a reference number. This is the reusable core I promised to give a home to, and here it is: capture that vocabulary once and reuse it across every workflow that touches invoices. For the invoice, Layer 2 is thick, and it is mostly a matter of naming the entities that are reliably there.</p><p>The second is a legal contract, and it behaves differently. Its <em>stable</em> vocabulary is comparatively <em>thin</em>: parties, governing law, a few effective dates. The real Layer-2 work is not naming entities; it is two harder jobs. The first is <em>reference resolution</em>. A contract cites statutes, articles of law, other clauses, and external agreements, and resolving each citation to a stable, canonical identifier (the task known in NLP as <a href="https://en.wikipedia.org/wiki/Entity_linking">entity linking</a>) is what lets an agent <em>reason about</em> the reference rather than merely follow the link: is the cited provision apt, is it still in force, has it been abrogated? Resolving a reference to a canonical identity is the precondition for reasoning about it, because the identifier is a key into a knowledge base where facts about the reference live, not just a pointer to its text. The second is <em>defined-term binding</em>. Contracts define their own terms (“Interest Rate” means what section 1.1 says it means, not what a dictionary says), so binding a defined term to the contract’s own definitions section, a within-document <a href="https://en.wikipedia.org/wiki/Coreference">coreference</a> between the term and the clause that defines it, is a first-class grounding task. Bind “Interest Rate” to its everyday sense and you have made a <em>grounding error</em>, quietly, and everything Layer 3 concludes from it will be wrong in a way that looks perfectly reasonable.</p><p>The third is not a legal or financial document at all, and that is the point of including it. As a thought experiment, take a novel. Its Layer 2 is a cast of <em>characters</em>, the <em>places</em> they move through, the <em>events</em> that occur, and the <em>timeline</em> that orders them. The characteristic Layer-2 work here is neither a fixed vocabulary nor citation resolution but <em>entity tracking</em> across a long narrative: knowing that the “he” on page three hundred is the boy introduced on page five (coreference again), and reconstructing a chronology from a story told out of order. Put a Layer-3 question to it, “how does John’s character develop across the book?”, and the discipline is unchanged: get the structure and the entities in place before you reason about the arc. The model does not seem to mind the domain. It seems to work.</p><p>The point is not that one document is harder than another. It is that Layer 2 is real everywhere, but its <em>thickness varies by domain</em>: for the invoice it is mostly vocabulary, for the contract it is mostly resolution and binding, for the novel it is tracking a cast of entities and a timeline across a long text. The machinery that does the contract job well (detecting references, resolving them, binding defined terms) is a field note of its own, which I will write separately.</p><h3>Keep Layer 2 sparse, Layer 3 disposable</h3><p>There is a standing temptation to let Layer 2 grow. A workflow needs some derived fact, computing it once in the shared layer feels efficient, and so a workflow convenience quietly migrates downward into Layer 2. Resist it. Every workflow-specific convenience you bake into Layer 2 erodes the one property that made it worth sharing: its reusability. The discipline is a two-sided rule: keep Layer 2 <em>sparse and stable</em>, and keep Layer 3 <em>rich and disposable</em>.</p><p>A concrete case. A due-diligence review and a litigation-risk review run over the same contracts, and they overlap: both care about which obligations survive termination. The instinct is to compute “surviving obligations” once, push it down into Layer 2, and let both share it. Resist it: “surviving obligations” is not a stable domain fact but a task-shaped judgment, and the two reviews define it differently. What belongs in Layer 2 is the raw material they agree on (the termination clause, the obligations it names); the interpretation stays in each review’s Layer 3, even though both interpret the same clause. That overlap is not duplication to factor away; hoisting the judgment into Layer 2 would bake one review’s assumptions into the shared layer and couple the two. The test: a fact that is task-independent and stable belongs in Layer 2; a judgment whose definition depends on the question stays in Layer 3.</p><h3>Never skip a layer</h3><p>Now the rule the whole post is named for. Never go straight from the raw document to the language model. The shortcut is seductive: drop the whole PDF, or a text dump of it, into the prompt, ask your Layer-3 question, and let a capable model sort out the rest. In a demo it works beautifully. In production it fails, and worse, it fails in a way you cannot debug.</p><p>The reason is that the three layers are three distinct places where a mistake can happen, and the shortcut collapses them into one. Consider the chain, kept deliberately generic: a table cell is misread (a <em>perception</em> error), so an amount is attached to the wrong party (a <em>grounding</em> error), so the workflow reaches a wrong contractual conclusion (an <em>inference</em> error). That errors cascade and compound down a chain of dependent stages is not a new observation: it is a long-studied failure mode of language-processing pipelines ( <a href="https://aclanthology.org/W06-1673/">Finkel, Manning, and Ng, 2006</a>), whose own remedy was to reduce the propagation with joint inference. The layered response makes a different and more modest bet. When you build the layers explicitly, each of those is a separate, inspectable step. When you throw everything into one prompt, all three failure modes happen inside the same opaque call, and when the answer comes back wrong you have no way to ask the only question that matters: <em>which layer failed?</em> Was the number misread, or read correctly and misattributed, or read and attributed correctly but reasoned about wrongly? One prompt cannot tell you. Three layers can.</p><p>That is the payoff, and it is worth stating plainly, because it is the entire reason to pay the tax of building the layers at all: <strong>explicit layers make a failure localizable to one layer.</strong> A layered system fails in a <em>place</em>; a skipped-layer system just fails. And what fails in a place can be <em>tested</em> in a place: each layer takes its own golden dataset, which is far less noisy than one end-to-end metric whose definition of success is hard to pin down (a topic I will take up in its own post). Diagnosability is not a nice-to-have you add later; it is a property you either designed in or gave away on day one. If this sounds like a familiar engineering discipline, it is: <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> applied to document knowledge, the same reason strict layering keeps systems like the <a href="https://en.wikipedia.org/wiki/OSI_model">OSI stack</a> tractable, where each layer builds on the one below without reaching around it.</p><p>Going back to the source is not the same as skipping a layer. A Layer-3 task will often need a detail the generalist Layer 2 never captured, and the right move is to reach back and re-read the exact span the lower layers point to: the full text of clause 4.2, or the chapter where the two characters first meet. That is using the layers to navigate back to grounded evidence, not bypassing them. What the rule forbids is the ungrounded shortcut, asking the final question of the raw document with no layers built at all.</p><p>There is a precondition hiding in here, which I will only gesture at now. Layering pays off only if the lower layers hand the upper layers something <em>stable</em> to point at. If Layer 1’s identifiers churn every time you re-extract the document (re-run the extraction pipeline after, say, an OCR or model upgrade), then Layer 2’s groundings and Layer 3’s conclusions dangle, and the whole structure collapses back into re-extract-everything. Stable identity across re-extraction is what makes layering hold together, and it is the subject of part three.</p><h3>A familiar split</h3><p>If some of this feels familiar, it may be because you have met it under other names. In a talk I gave on document AI at AWS, I split the pipeline into <em>extraction</em>, <em>knowledge</em>, and <em>generation</em>. Those are the same three layers wearing different labels: extraction is Layer 1, knowledge is Layer 2, generation is Layer 3. I find the layer framing more useful now precisely because it makes the never-skip rule obvious, and the rule is what tells you the split is worth keeping even in an era when a single large model could, in principle, do all three jobs in one call. Being <em>able</em> to skip the layers is exactly why you need a rule not to.</p><h3>What to carry forward</h3><p>In summary:</p><ul><li><strong>Three layers, three reuse profiles.</strong> Intrinsic structure is fully reusable, domain entities are partially reusable, and workflow knowledge is not reusable at all (and that last one is a feature, not a gap).</li><li><strong>Each layer answers a different kind of question:</strong> perception, grounding, inference. Keeping them separate is what lets a system tell you which one it got wrong.</li><li><strong>Never skip a layer.</strong> The raw-document-to-model shortcut compounds errors into one undiagnosable failure; explicit layers buy you the ability to say where it broke.</li></ul><p>The next time you are tempted to pipe a document straight into a prompt and ask the hard question, add the two intermediate stops: extract the structure, ground the entities, and only then infer. It costs more to build and it pays for itself the first time something goes wrong and you can point at the layer that did it.</p><p>The rule leans on a precondition I have only hinted at: the lower layers have to give the upper layers something stable to annotate. In part three I will build that out: a document object model that survives re-extraction, so identity does not churn underneath your groundings and conclusions. Stay tuned.</p><h3>Resources</h3><ul><li>Part one of this series, “Pragmatism for document AI”: <a href="https://mrtj.pro/posts/pragmatism-for-document-ai/">https://mrtj.pro/posts/pragmatism-for-document-ai/</a></li><li>Document layout analysis: <a href="https://en.wikipedia.org/wiki/Document_layout_analysis">https://en.wikipedia.org/wiki/Document_layout_analysis</a></li><li>Upper ontology: <a href="https://en.wikipedia.org/wiki/Upper_ontology">https://en.wikipedia.org/wiki/Upper_ontology</a></li><li>Symbol grounding problem: <a href="https://en.wikipedia.org/wiki/Symbol_grounding_problem">https://en.wikipedia.org/wiki/Symbol_grounding_problem</a></li><li>Entity linking: <a href="https://en.wikipedia.org/wiki/Entity_linking">https://en.wikipedia.org/wiki/Entity_linking</a></li><li>Coreference: <a href="https://en.wikipedia.org/wiki/Coreference">https://en.wikipedia.org/wiki/Coreference</a></li><li>Jenny Rose Finkel, Christopher D. Manning and Andrew Y. Ng, “Solving the problem of cascading errors: approximate Bayesian inference for linguistic annotation pipelines” (EMNLP 2006): <a href="https://aclanthology.org/W06-1673/">https://aclanthology.org/W06-1673/</a></li><li>Separation of concerns: <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">https://en.wikipedia.org/wiki/Separation_of_concerns</a></li><li>OSI model: <a href="https://en.wikipedia.org/wiki/OSI_model">https://en.wikipedia.org/wiki/OSI_model</a></li></ul><p><em>This post first appeared on my blog, where part three of the series will be published first: </em><a href="https://mrtj.pro/posts/never-skip-a-layer/"><em>https://mrtj.pro/posts/never-skip-a-layer/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e153585e5c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/mind-the-layers-a-three-layer-model-for-document-ai-4e153585e5c0">Mind the layers: a three-layer model for document AI</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pragmatism for document AI]]></title>
            <link>https://medium.com/data-science-collective/pragmatism-for-document-ai-8b43792d9ab9?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b43792d9ab9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[pragmatism]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 00:00:39 GMT</pubDate>
            <atom:updated>2026-09-24T08:44:05.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>The universal schema is one of document AI’s most expensive mistakes. A century-old philosophy explains why.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xCBMAsLa2RisUasG.png" /><figcaption>Image generated by the author with OpenAI’s ChatGPT</figcaption></figure><p>When a new document type lands on your desk (a contract, an invoice, a vaccination certificate), the first engineering instinct is almost always the same: design <em>the</em> schema. One data model per document type, rich enough to capture everything important, built once and reused across every workflow that will ever touch that document. It feels like the responsible thing to do. It is also, I have come to think, one of the most expensive mistakes in document AI.</p><p>This is the first of a three-part series on how I have learned to think about knowledge in document AI systems. Before the architecture (part two) and the implementation details (part three), I want to start with the stance, because the stance is what makes the rest coherent. That stance is borrowed, almost wholesale, from a hundred-year-old American philosophical tradition called <a href="https://plato.stanford.edu/entries/pragmatism/"><em>pragmatism</em></a>. Bear with the philosophy: it pays for itself quickly.</p><p>Let me state the claim up front, and state it carefully. It is not that structure never generalizes; for some documents a surprising amount of it does. It is that no single schema captures everything that matters about a document, because what matters is relative to the question you are asking. Knowledge is structured by use, and the categories we extract are tools rather than universal truths. Let’s dive deeper.</p><h3>The universal-schema instinct</h3><p>The instinct has a respectable pedigree. It goes back to Aristotle’s <a href="http://classics.mit.edu/Aristotle/categories.html"><em>Categories</em></a>, which set out to enumerate the fundamental kinds of things once and for all: substance, quantity, quality, relation, and so on. Every entity falls under a category, categories have structure, and reasoning becomes tractable. Computer science inherited the ambition directly. When Tom Gruber gave the field its canonical definition in 1993, an became “an explicit specification of a conceptualization”: a formal vocabulary of classes, relations, and constraints that a machine can reason over. The word was not borrowed by accident: computer science took over philosophy’s ambition of naming, once and for all, the kinds of things a domain contains.</p><p>For part of the problem, this works beautifully. A document, considered as an artifact, really does have stable structure: pages, blocks, tables, reading order, sections, signatures. That layer generalizes across contracts, certificates, and transcripts, because every one of them is, first, a document. Build it once, reuse it everywhere.</p><p>The instinct rarely stops at the artifact, though. Having modeled the document’s structure once, it reaches inward for the same universality: one schema for what the document <em>means</em>, rich enough that every future workflow can read what it needs off a single representation. That is the move I want to question. Some of what is inside genuinely generalizes, but the slice of meaning any given task actually needs does not settle into one shared form: how you carve up a document’s meaning depends on what you are trying to do with it.</p><p>You might reasonably push back here, and the strongest counterexample is the humble invoice. An invoice is so regular that a single generic schema (issuer and recipient, line items, amounts, tax, dates, a reference number) really does apply to almost all of them. That is a genuine, reusable schema, and I do not want to wave it away: capturing that shared core once, rather than reinventing it per project, is exactly the right move. We will give it a home in the next post, as the middle layer of a three-layer model.</p><p>But notice what that reusable core is and is not. It is a stable vocabulary of the entities an invoice tends to contain; it is not a schema that captures everything that matters, because what matters still depends on the question. Ask whether an invoice is a duplicate payment, whether its tax treatment is correct, or whether it is fraudulent, and the decomposition that actually helps diverges each time: which fields you trust, what counts as a match, what “correct” even means. That task-shaped knowledge is the layer the universal instinct cannot pre-model, and the one the next post argues you should build only when a task demands it. A contract makes the point more starkly still: its useful “joints” are completely different when you are checking enforceability, computing tax exposure, or screening for fraud. There is no view-from-nowhere decomposition that captures everything important, because importance is relative to a question. The pragmatist way to put it: decomposition is downstream of use.</p><p>Wittgenstein gave us the sharpest tool for seeing why. Concepts like “contract” are not natural kinds with a shared essence; they are <a href="https://en.wikipedia.org/wiki/Family_resemblance"><em>family resemblance</em></a> concepts ( <em>Philosophical Investigations</em>, sections 66 to 67), whose members overlap and criss-cross without a single defining feature. Their boundaries shift with jurisdiction and purpose. Trying to write the one definition that captures all contracts is chasing an essence that is not there. Mistaking a meaning problem for a structure problem is the root error, and it is an easy error to make precisely because our tools are so good at the structure part.</p><h3>Concepts are tools, not mirrors</h3><p>A category is just a concept put to work: the slice of meaning we decide is worth extracting. So if knowledge is structured by use, what is such a category actually for? Here the pragmatists are blunt. For <a href="https://plato.stanford.edu/entries/dewey/">John Dewey</a>, a concept is not a picture of reality; it is an instrument for resolving a problematic situation. Peirce got there first with his <a href="https://courses.media.mit.edu/2004spring/mas966/Peirce%201878%20Make%20Ideas%20Clear.pdf"><em>pragmatic maxim</em></a> of 1878: the meaning of a concept is the sum of the practical consequences of holding it. A category earns its place if it makes some downstream workflow succeed, and the same domain can legitimately warrant different categories for different tasks. A field that helps no inquiry is decoration, however correct it looks on paper.</p><p>That is the whole argument, and it points to a single design move: stop trying to model the document, and start trying to equip the inquiry. For any document type there is no one correct ontology, only the ontology that makes a specific downstream question answerable. Expect to hold more than one at a time. Expect to retire them when the question changes. This sounds permissive, but it is the opposite. “Structured by use” is not “anything goes”, it is “justified by use”: every category has to earn its keep against a real workflow.</p><h3>We already do this, on the evaluation side</h3><p>Here is the part I find quietly reassuring. Machine learning already practices pragmatism; it just practices it downstream. We do not ask whether a model’s outputs correspond to reality. We ask whether they hold up across distributions, support good decisions, and stay stable under perturbation. That is Peirce’s maxim almost verbatim, meaning cashed out in practical consequences, operationalized as a held-out test set. <a href="https://www.gutenberg.org/files/5116/5116-h/5116-h.htm">William James</a> would recognize it at once: truth as what proves itself in practice.</p><p>So the field is pragmatist about how it <em>judges</em> models, and rationalist about how it <em>designs schemas</em>, still reaching for the one universal conceptualization that will capture everything. The fix is not more philosophy. It is to bring the stance we already trust for evaluation upstream, to the point where we decide what to extract in the first place.</p><h3>Where to go from here?</h3><p>In summary:</p><ul><li><strong>Knowledge is structured by use.</strong> A document has no privileged decomposition; its joints depend on the question you are asking.</li><li><strong>Concepts are tools.</strong> A category is good if it helps a downstream workflow, so equip the inquiry rather than model the document.</li></ul><p>Concretely, the next time you reach for the one universal schema of a document type, stop and ask which task it serves: build the schema for that question, expect to hold more than one, and let each category earn its place against a real workflow. None of this argues against structure. The document-as-artifact layer is real, shared, and worth getting right once. The argument is about where universality stops and use begins, and about being honest that most of the interesting knowledge lives on the “use” side.</p><p>In the next part of this series I will make that concrete with a three-layer model that puts each kind of knowledge where it belongs, and a rule that keeps the whole thing diagnosable: never skip a layer. Stay tuned.</p><p><em>This post first appeared on my blog, where parts two and three of the series will be published first: </em><a href="https://mrtj.pro/posts/pragmatism-for-document-ai/"><em>https://mrtj.pro/posts/pragmatism-for-document-ai/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b43792d9ab9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/pragmatism-for-document-ai-8b43792d9ab9">Pragmatism for document AI</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Predictive Maintenance: Deploying a Linear Regression Model on AWS Lambda — Part 1]]></title>
            <link>https://medium.com/@janos.tolgyesi/efficient-predictive-maintenance-deploying-a-linear-regression-model-on-aws-lambda-part-1-1fed09834b4a?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fed09834b4a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 13:40:24 GMT</pubDate>
            <atom:updated>2024-10-29T22:03:37.641Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Predictive Maintenance: Deploying a Linear Regression Model on AWS Lambda</h3><h4>The Problem of Predictive Maintenance and Creating a Synthetic Dataset</h4><p>This article is part of a series that covers the implementation of a linear regression model on noisy sensor data. The aim is to predict when observed metrics will exceed a specific threshold, indicating the need for system repair. Throughout the series, we will generate synthetic sensor data, construct predictive models, and deploy them on AWS Lambda service for production readiness. You will find practical steps that you can follow to utilize this approach in real-world scenarios.</p><p>This is the first article in the series. We will explain how linear regression can be useful in predictive maintenance, create a synthetic dataset, train a model, and predict the maintenance date. In the second article we will discuss how to deploy the model to AWS Lambda. You can find all parts here:</p><ol><li><a href="https://medium.com/@janos.tolgyesi/efficient-predictive-maintenance-deploying-a-linear-regression-model-on-aws-lambda-part-1-1fed09834b4a">The Problem of Predictive Maintenance and Creating a Synthetic Dataset</a></li><li>Deploying a Linear Regression Model for Predictive Maintenance on AWS Lambda [TBD link]</li></ol><figure><img alt="A person repairing a traffic light" src="https://cdn-images-1.medium.com/max/1024/0*Xa5pIsCd18lEDXW4" /><figcaption>Photo by <a href="https://unsplash.com/@loran01?utm_source=medium&amp;utm_medium=referral">Dan Loran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Using Linear Regression in Predictive Maintenance</h3><p>Predictive maintenance has become a widely adopted approach for companies to optimize their maintenance operations and reduce downtime. It involves leveraging data and analytics to forecast when a machine or system is likely to fail, allowing maintenance to be performed proactively before the failure occurs. By using this proactive approach, companies can save significant amounts of money by preventing expensive equipment failures and minimizing downtime.</p><p>One common method for predictive maintenance is using linear regression. The assumption here is that there is a dependent variable in the system that is linearly proportional to the deterioration of the system. This can be seen in many industrial applications, such as monitoring the pressure of air filters. In this scenario, a pair of sensors measures the pressure before and after the air filter, and the difference in pressure is used to determine when the filter needs to be changed. However, the sensors provide noisy data, so a model needs to be created to accurately predict when the pressure difference will reach a certain threshold that indicates the filter needs to be changed.</p><figure><img alt="Air conditioner tubes" src="https://cdn-images-1.medium.com/max/1024/0*CTkZJN7KDBy30vq4" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Setting Up Your Development Environment</h3><p>Before we start implementing the linear regression predictor, let’s ensure that you have the necessary tools installed and set up on your local machine. In this section, we will guide you through the installation process for the conda virtual environment manager, Jupyter Notebooks, and the AWS Serverless Application Model Command Line Interface (SAM CLI). In addition these tools, you’ll also need to install scikit-learn, pandas, and matplotlib within your conda environment. These libraries will enable you to generate synthetic data, manipulate datasets, and visualize your results.</p><p><strong>Install Conda Virtual Environment Manager</strong>: To create an isolated Python environment for your project, we recommend using conda. Download and install the appropriate version of Miniconda for your operating system from the <a href="https://docs.conda.io/en/latest/miniconda.html">official website</a>. Once installed, you can create a new virtual environment with the following command:</p><pre>conda create --name my-env python=3.8</pre><p>Replace my-env with your preferred environment name. Activate your new environment with:</p><pre>conda activate my-env</pre><p><strong>Install Jupyter Notebooks and data science libraries</strong>: With your conda environment activated, install Jupyter Notebooks, scikit-learn, matplotlib and pandas by running:</p><pre>conda install -c conda-forge notebook scikit-learn matplotlib pandas</pre><p><strong>Install AWS SAM CLI</strong>: The SAM CLI is an essential tool for building and deploying serverless applications on AWS Lambda. You can follow the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">official AWS guide</a> to install the SAM CLI on your machine.</p><p>After installing scikit-learn, pandas, and matplotlib, your development environment will be ready for generating, processing, and visualizing synthetic sensor data in a Jupyter Notebook.</p><h3>Simulating Noisy Sensor Data with Synthetic Examples</h3><p>For the sake of simplicity, we will use synthetic data to simulate a noisy sensor in our predictive maintenance scenario. To generate this synthetic data, we will employ the widely used scikit-learn Python library. Scikit-learn provides a variety of tools for creating and processing datasets, making it an ideal choice for our purposes.</p><p>In order to visualize the generated data and better understand its characteristics, we will use a Jupyter Notebook. Jupyter Notebooks offer an interactive and user-friendly environment, enabling us to display plots and charts alongside our code, which makes data analysis more efficient and comprehensible.</p><p>Launch Jupyter Notebook with the command:</p><pre>jupyter notebook</pre><p>Create a new notebook instance and enter the following code snippet that uses the scikit-learn library to generate a synthetic dataset for the regression problem:</p><pre>from sklearn.datasets import make_regression<br><br>gt_samples = 1000    # The number of samples in the generated dataset.<br>gt_noise = 10        # The standard deviation of the Gaussian noise to be<br>                     # added to the output. This simulates noisy sensor data.<br>gt_bias = 13         # The bias term, which represents the intercept of the<br>                     # underlying linear function.<br>gt_random_state = 42 # A seed for the random number generator, ensuring that<br>                     # the generated dataset is reproducible.<br><br>X, y, gt_coef = make_regression(<br>    n_samples=gt_samples,<br>    n_features=1,<br>    bias=gt_bias,<br>    noise=gt_noise,<br>    coef=True,<br>    random_state=gt_random_state<br>)<br>x = X.reshape(-1)</pre><p>When dealing with sensor readings, most likely the data will arrive in time series format. Thus we will change the x axis of our dataset to timestamps. To be able to convert back model predictions to timestamps.</p><pre>import pandas as pd<br>import numpy as np<br>import datetime<br><br>df = pd.DataFrame(np.stack((x, y), axis=1), columns=(&#39;x&#39;, &#39;y&#39;))<br>x_to_dt = lambda x: datetime.timedelta(days=x * 30)<br>start = datetime.datetime.now() - x_to_dt(min(df[&#39;x&#39;]))<br>dt_index = [start + x_to_dt(x) for x in df[&#39;x&#39;]]<br>df.index = pd.DatetimeIndex(dt_index, name=&#39;date&#39;)<br>df = df.sort_index()<br>df = df.drop(columns=&#39;x&#39;)<br>print(df.head())</pre><p>Our dataset looks like this:</p><pre>date                                    y<br>2023-03-29 09:19:20.207695     -28.145488<br>2023-04-14 17:16:34.974649     -34.823622<br>2023-04-16 02:20:11.409799     -13.469901<br>2023-04-17 00:49:05.843353     -22.405377<br>2023-04-21 11:27:02.608824     -26.338877</pre><p>This simulates sensor readings at non regular intervals, the most generic case that you might face in real-world scenarios.</p><p>Let’s visualize the generated synthetic dataset with matplotlib:</p><pre>from matplotlib import pyplot as plt<br><br>df[&#39;y&#39;].plot(style=&#39;.&#39;)<br>plt.title(&#39;Synthetic Linear Regression Data&#39;)<br>plt.show()</pre><figure><img alt="The diagram of a point cloud arranged diagonally, representing the noisy measurements of a linear system" src="https://cdn-images-1.medium.com/max/1024/1*y8LVg8c5Lwi47SEDW03zUQ.png" /><figcaption>Synthetic Linear Regression Data. Author’s own work.</figcaption></figure><p>Save the generated data as a comma-separated values (CSV) file:</p><pre>df.to_csv(&#39;./data/data.csv&#39;)</pre><h3>Efficient Linear Regression Model with NumPy</h3><h4>Preprocessing</h4><p>In the following Python snippet, we load the dataset in CSV format with Pandas, which emulates acquiring data from an external source. To facilitate further processing, we must transform the timestamp values into numeric representations. We achieve this by “normalizing” these values using the earliest timestamp (start_date) as the reference point and expressing the difference in seconds. We will take note of start_date and the information that the dataset units are seconds, so we can convert back model predictions to timestamps.</p><pre>import pandas as pd<br><br>df = pd.read_csv(dataset_path, parse_dates=[&#39;date&#39;])<br>start_date = df[&#39;date&#39;].min()<br>df[&#39;x&#39;] = (df[&#39;date&#39;] - start_date).dt.total_seconds()<br>x = df[&#39;x&#39;].to_numpy()<br>y = df[&#39;y&#39;].to_numpy()</pre><h4>Model development</h4><p>In the next section, we will focus on training a linear regression model using the noisy data generated earlier. Most online tutorials and resources utilize the sklearn.linear_model.LinearRegression class from the scikit-learn library for this purpose. However, in this guide, we will use the numpy.linalg.lstsq function instead.</p><p>There are two main reasons for choosing the numpy.linalg.lstsq function over the scikit-learn approach:</p><p>1. <em>Performance</em>: The numpy.linalg.lstsq function is typically an order of magnitude faster than the LinearRegression class, making it a more efficient choice for training linear regression models, especially for large datasets.</p><p>2. <em>Smaller dependency footprint</em>: When deploying your linear regression model to AWS Lambda, minimizing the size of your Python dependencies is crucial. Using the lstsq function from numpy allows you to avoid importing the entire scikit-learn library, resulting in a much smaller dependency footprint.</p><p>By leveraging the numpy.linalg.lstsq function for training our linear regression model, we can achieve better performance and a more lightweight deployment, which will be highly beneficial when it comes to deploying our function on AWS Lambda. Here is how to do it:</p><pre>import numpy as np<br><br>A = np.vstack([x, np.ones(len(x))]).T<br>coef, bias = np.linalg.lstsq(A, y, rcond=None)[0]</pre><p>After importing numpy, the first line creates a 2D array A with two columns. The first column contains the feature values x from the synthetic dataset, and the second column is filled with ones. The purpose of adding a column of ones is to include a constant term (bias or intercept) in the linear regression model (see also the example in the <a href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html">numpy documentation</a>). The np.vstack() function stacks the two input arrays vertically, and the .T attribute transposes the resulting array to obtain the desired shape.</p><p>The second line performs the actual linear regression by solving the least squares problem using the numpy.linalg.lstsq function. The function takes three arguments:</p><ul><li>A: The previously created 2D array containing the feature values x and a column of ones.</li><li>y: The output values (dependent variable) from the synthetic dataset.</li><li>rcond=None: This parameter is used to set the relative condition number for determining the rank of the input matrix A. When set to None, the function uses a machine-dependent value as the cutoff.</li></ul><p>The lstsq function returns several values, but we are only interested in the first element of the output tuple, which contains the least squares solution (i.e., the coefficients of the linear regression model). By using array unpacking, we assign the first element of the solution (the slope or weight) to the variable coef and the second element (the bias or intercept) to the variable bias.</p><h4>Visualizing results</h4><p>Let’s visualize the obtained model with this snippet:</p><pre>plt.plot(x, y, &#39;.&#39;, label=&#39;original data&#39;)<br>plt.plot(x, coef*x + bias, &#39;r&#39;, label=&#39;model&#39;)<br>plt.title(&#39;np.linalg.lstsq model&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="The same point cloud as above, with a red line crossing the middle of the point cloud, representing the linear regression model trained from the data points." src="https://cdn-images-1.medium.com/max/1024/1*KJD6lxbQwX3XIriQC6wQRQ.png" /><figcaption>numpy.linalg.lstsq model. Author’s own</figcaption></figure><h4>Predicting the date of maintenance</h4><p>Over time, the system experiences degradation, leading to a rise in the observed metrics. Utilizing linear regression, the model forecasts future metric values. Eventually, the predicted value surpasses a pre-established threshold, signifying the need for system repair beyond this point. The exact value of the threshold is specific to the problem domain and the scale of the metrics, here we will use an arbitrary value of 100. We will calculate the crossing moment using the coef and bias parameters along the numeric y axis, then convert the crossing to a date using the start_date and seconds as unit.</p><pre>target_threshold = 100<br><br>crossing = (target_threshold - bias) / coef<br>crossing_dt = start_date + pd.Timedelta(seconds=crossing)<br>print(f&#39;Predicted threshold crossing: {crossing_dt}&#39;)</pre><p>Output:</p><pre>Predicted threshold crossing: 2023-12-08 12:25:47.156814252</pre><h3>Conclusion</h3><p>In conclusion, this article has demonstrated the potential of linear regression as a valuable tool for predictive maintenance. By creating a synthetic dataset, training a model, and predicting maintenance dates, we have illustrated how this relatively simple statistical method can provide actionable insights for maintaining equipment and systems. The step-by-step instructions for setting up a development environment, along with ready-to-use Python snippets, aim to empower practitioners to apply linear regression in their own predictive maintenance tasks. Although linear regression may not be suitable for all scenarios, it serves as an accessible starting point for those interested in exploring data-driven approaches to optimize equipment maintenance and minimize downtime.</p><p>In the next article in this series we will explore how to deploy this model in a cost-effective, scalable way on AWS Lambda. Continue reading here. [TBD title and link to second article].</p><h3>About the author</h3><p>Janos Tolgyesi is an AWS Community Builder and Machine Learning Team Leader at Neosperience with 5+ years of expertise in ML technologies and 8+ years on AWS. He loves building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a>, or <a href="https://www.neosperience.com/solutions/user-insight/">a user profiler based on clickstream events</a>. You can find me on <a href="https://twitter.com/jtolgyesi">Twitter</a>, <a href="https://towardsdatascience.com/@janos.tolgyesi">Medium</a>, and <a href="http://linkedin.com/in/janostolgyesi">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fed09834b4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy your first computer vision app for AWS Panorama in five minutes]]></title>
            <link>https://medium.com/data-science/deploy-your-first-computer-vision-app-for-aws-panorama-in-five-minutes-221e974606e3?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/221e974606e3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[panorama]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 13:44:29 GMT</pubDate>
            <atom:updated>2022-10-25T13:46:25.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to set up your first Panorama application the easy way</h4><figure><img alt="An eagle flying in the sky" src="https://cdn-images-1.medium.com/max/1024/0*6YfQ1_vqMWcvarIL" /><figcaption>Photo by <a href="https://unsplash.com/@mrsrachelmcdermott?utm_source=medium&amp;utm_medium=referral">Rachel McDermott</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I published <a href="https://towardsdatascience.com/deploy-an-object-detector-model-at-the-edge-on-aws-panorama-9b80ea1dd03a">a step-by-step guide</a> here on Towards Data Science on deploying an object-detector application on AWS Panorama almost a year ago. The article was quite long (17 minutes to read!) and involved a lot of delicate steps. Creating a Panorama application with official tools is not easy: you should use a fixed and complex project structure, remember many parameters regarding your project, and pass them to the tools each time you invoke them. Then files and folders must be named in a particular way, and you must maintain consistent copies of the same information (for example, the deep-learning model properties) in different parts of the project. All these “housekeeping” tasks do not deliver real business value: they serve only to keep the project and the boilerplate code up to date.</p><p>In the last few months, I have built and deployed a dozen of Panorama applications, experiencing this burden on my own. Obviously, some repeating tasks and patterns emerged that pushed me to automate the setup and deployment process of any Panorama app as much as possible. I am pleased to introduce <a href="https://github.com/mrtj/cookiecutter-panorama">cookiecutter-panorama</a>, an AWS Panorama project generator tool and build system. Let’s dive deeper, starting with the definition of an AWS Panorama app.</p><h3>The anatomy of a Panorama application</h3><p>In case you missed the <a href="https://towardsdatascience.com/deploy-an-object-detector-model-at-the-edge-on-aws-panorama-9b80ea1dd03a">previous</a> <a href="https://towardsdatascience.com/remote-view-your-computer-vision-models-running-on-aws-panorama-32922369ecf">episodes</a>, AWS Panorama is a <a href="https://aws.amazon.com/panorama/">hardware and software platform</a> that enables running computer vision (CV) applications analyzing video streams from on-premises internet protocol (IP) cameras.</p><p>A <em>Panorama Application</em> is a collection of packaged deep learning models, business logic code, and a manifest structure (also called “application graph”) that defines the data pipeline between these components.</p><p>In the case of “classic” Panorama applications, the deep learning model (trained in Pytorch, Tensorflow, or MXNet) is packaged in an artifact called “model asset” by the build process of the app. Similarly, your business logic code (written in Python, using the Panorama Application SDK) is packaged in the “code asset” artifact. These artifacts are registered and uploaded to your AWS account. Whenever you want to deploy your CV application to a Panorama appliance, you must provide the manifest structure that refers to these artifacts and describes how the device should connect them.</p><p>So, a Panorama application is loosely coupled to a set of deep learning and business logic packages bound together by the manifest file. The developer must constantly synchronize the references in the application manifest file and within the packages. This is one of the biggest maintenance tasks that cookiecutter-panorama can automate.</p><h3>Cookiecutter</h3><p>Let’s talk about how to make cookies!</p><figure><img alt="Uncooked gingerbread dough being cut into different shapes by cookie cutters" src="https://cdn-images-1.medium.com/max/1024/0*uE68IXHGkVXYOWah" /><figcaption>Photo by <a href="https://unsplash.com/@anshu18?utm_source=medium&amp;utm_medium=referral">Anshu A</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://github.com/cookiecutter/cookiecutter">Cookiecutter</a> is a command-line utility that creates projects from cookiecutters (project templates). It became the de-facto standard for generating projects in the Python ecosystem because of its beautifully simple design matches with compelling features. Currently, there are more than <a href="https://github.com/search?q=cookiecutter&amp;type=Repositories">7000 cookiecutter project templates</a> published on GitHub. Cookiecutter-panorama adds the Panorama application template to this pantheon.</p><h3>Get started!</h3><p>First, <a href="https://cookiecutter.readthedocs.io/en/stable/installation.html">install the cookiecutter command-line</a> tool with pip (<strong>pip install cookiecutter</strong>), conda (<strong>conda install -c conda-forge cookiecutter</strong>) or <a href="https://pypa.github.io/pipx/">pipx</a> (<strong>pipx install cookiecutter</strong>, the recommended way).</p><figure><img alt="The launch of a Space-X rocket" src="https://cdn-images-1.medium.com/max/1024/0*-PoJJ-41MB0QPuoF" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating a Panorama application project is as simple as:</p><pre><strong>$ cookiecutter </strong><a href="https://github.com/mrtj/cookiecutter-panorama.git"><strong>https://github.com/mrtj/cookiecutter-panorama.git</strong></a></pre><p>The template engine will ask you the value of a bunch of parameters. However, it also provides reasonable default values that you can leave as they are in most cases and confirm the option.</p><p>You have to set up only two parameters: project_name and s3_working_bucket. The latter should be the name of an existing S3 bucket in your account where you have read/write privileges. You can find a detailed description of the parameters in the <a href="https://github.com/mrtj/cookiecutter-panorama/blob/main/README.md">README file of cookiecutter-panorama</a>.</p><pre><strong>$ cookiecutter </strong><a href="https://github.com/mrtj/cookiecutter-panorama.git"><strong>https://github.com/mrtj/cookiecutter-panorama.git</strong></a><br>project_name [Panorama Video Processor]: ↲<br>project_slug [panorama_video_processor]: ↲<br>s3_working_bucket [my_bucket]: <strong>my_real_bucket</strong><br>s3_working_path [s3://my_real_bucket/panorama_projects/panorama_video_processor]: ↲<br>camera_node_name [camera_input]: ↲<br>display_node_name [display_output]: ↲<br>code_package_name [panorama_video_processor_logic]: ↲<br>code_package_version [1.0]: ↲<br>code_asset_name [panorama_video_processor_logic_asset]: ↲<br>code_node_name [panorama_video_processor_logic_node]: ↲<br>model_package_name [panorama_video_processor_model]: ↲<br>model_package_version [1.0]: ↲<br>model_asset_name [panorama_video_processor_model_asset]: ↲<br>model_node_name [panorama_video_processor_model_node]: ↲<br>model_input_name [input0]: ↲<br>model_processing_width [224]: ↲<br>model_processing_height [224]: ↲</pre><p>Cookiecutter will generate your project in a directory named the project_slug parameter, in the above case panorama_video_processor:</p><pre><strong>$ cd </strong><strong>panorama_video_processor</strong></pre><h3>Batteries included: the build system</h3><p>Once the project has been generated, you can start interacting with the Makefile. The build system provides a rich set of functionalities: configure a git repository, build the application container and the deep learning model, upload the packages to your AWS account ready to be deployed to the Panorama appliance, run your application on your development workstation with <a href="https://github.com/aws-samples/aws-panorama-samples">Test Utility</a>, safeguard you from leaking your AWS account id in public git repositories, etc. For a complete list of features, refer to the README file generated within the Panorama project. <a href="https://github.com/mrtj/cookiecutter-panorama/blob/main/%7B%7Bcookiecutter.project_slug%7D%7D/README.md">Here</a> is a preview.</p><figure><img alt="A construction site with cranes" src="https://cdn-images-1.medium.com/max/1024/0*_GloJiI8-zNkQnUs" /><figcaption>Photo by <a href="https://unsplash.com/@hojipago?utm_source=medium&amp;utm_medium=referral">EJ Yao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some tasks provided by cookiecutter-panorama you can benefit:</p><ul><li><strong>make init-repo</strong>: initialize a git repository</li><li>Install the required build tools: <a href="https://aws.amazon.com/cli/">aws-cli</a>, <a href="https://github.com/aws/aws-panorama-cli">panorama-cli</a> and <a href="https://docs.docker.com/get-docker/">docker</a>. <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">Configure</a> the aws-cli to the credentials of the account where the Panorama appliance is registered.</li><li><strong>make import</strong>: import the project to your AWS account</li><li><strong>make build</strong>: build the project and create a dummy deep learning model that you can replace later with an actual model. The dummy model will calculate the mean of the RGB channels of the input video frame using the model package infrastructure and the real GPU of the Panorama appliance.</li><li><strong>make package</strong>: upload the compiled application container and packaged deep learning model to your AWS account. This script will also output the path of the compiled manifest JSON.</li></ul><p>Then you can pick up the manifest JSON, head to <a href="https://console.aws.amazon.com/panorama/home">AWS Panorama Console</a> and deploy your application!</p><p>Questions? Issues? Suggestions? <a href="https://github.com/mrtj/cookiecutter-panorama/issues/new/choose">Open an issue</a> in the <a href="https://github.com/mrtj/cookiecutter-panorama">cookiecutter-panorama github project</a>, or reach out using the contacts below!</p><h3>About the author</h3><p>Janos Tolgyesi is an AWS Community Builder and Machine Learning Team Leader at Neosperience with 5+ years of expertise in ML technologies and 8+ years on AWS. He loves building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a>, or <a href="https://www.neosperience.com/solutions/user-insight/">a user profiler based on clickstream events</a>. You can find me on <a href="https://twitter.com/jtolgyesi">Twitter</a>, <a href="https://towardsdatascience.com/@janos.tolgyesi">Medium</a>, and <a href="http://linkedin.com/in/janostolgyesi">LinkedIn</a>.</p><p>The open-source project of cookiecutter-panorama was supported by <a href="https://www.neosperience.com/">Neosperience</a>.</p><p>I would like to express my special thanks to <a href="https://medium.com/u/6550450171ac">Luca Bianchi</a> for proofreading this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221e974606e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploy-your-first-computer-vision-app-for-aws-panorama-in-five-minutes-221e974606e3">Deploy your first computer vision app for AWS Panorama in five minutes</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[Remote View your Computer Vision Models Running on AWS Panorama]]></title>
            <link>https://medium.com/data-science/remote-view-your-computer-vision-models-running-on-aws-panorama-32922369ecf?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/32922369ecf</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[panorama]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Sat, 07 May 2022 05:40:37 GMT</pubDate>
            <atom:updated>2022-06-20T20:57:21.493Z</atom:updated>
            <content:encoded><![CDATA[<h4>Monitoring a Panorama app</h4><h4>Introducing SkyLine: A library to view the output of a Panorama application from your workstation</h4><figure><img alt="A fixed telescope overlooking a city landscape" src="https://cdn-images-1.medium.com/max/1024/0*vLsXUmuRTxrxDobj" /><figcaption>Photo by <a href="https://unsplash.com/@elisasch?utm_source=medium&amp;utm_medium=referral">Elisa Schmidt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Real-time smart video analytics application development and edge device deployment is a tricks task. In the last few years, the industry players built platforms to support this activity. Notable examples include <a href="https://www.nvidia.com/en-us/autonomous-machines/intelligent-video-analytics-platform/">NVIDIA Metropolis</a>, <a href="https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/overview.html">Intel’s OpenVINO</a>, and <a href="https://aws.amazon.com/panorama/">AWS Panorama</a>. While these solutions make some aspects of the video-analytics application development more straightforward, there are still many issues to deal with before deploying a video analytics application in production. This post introduces SkyLine, the first in a <a href="https://github.com/Neosperience/backpack">series of open-source tools</a> to make developing AWS Panorama application simpler.</p><p>AWS Panorama is a machine learning appliance and software framework that allows you to deploy video analytics applications on edge. For a thorough introduction and a step-by-step tutorial on deploying a Panorama application, refer to <a href="https://towardsdatascience.com/deploy-an-object-detector-model-at-the-edge-on-aws-panorama-9b80ea1dd03a"><em>Deploy an Object-Detector Model at the Edge on AWS Panorama</em></a>.</p><p>AWS Panorama framework eases many aspects of video analytics application development, including camera connection management, video decoding, frame extraction, model optimization and loading, display output management, over-the-air deployment of your application, and other features. Nevertheless, some tasks are still challenging, including diagnostic tasks when a model does not work as expected.</p><h3>Introducing SkyLine</h3><p>The only available way to get visual feedback on the correct functionality of a Panorama application is to physically connect a display to the HDMI port of the appliance. The display will show the output video stream of a single application deployed on the device. However, physically accessing the appliance is not always feasible. SkyLine allows to re-stream the output video of any Panorama application to an external service, for example, to <a href="https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html">AWS Kinesis Video Streams</a>. This feature can be very convenient for monitoring an application remotely.</p><h4>How does SkyLine work?</h4><p>SkyLine instantiates a <a href="https://gstreamer.freedesktop.org/documentation/application-development/introduction/basics.html">GStreamer pipeline</a> with an <a href="https://gstreamer.freedesktop.org/documentation/app/appsrc.html">appsrc</a> element at the head. An <a href="https://docs.opencv.org/4.5.5/dd/d43/tutorial_py_video_display.html">OpenCV </a><a href="https://docs.opencv.org/4.5.5/dd/d43/tutorial_py_video_display.html">VideoWriter</a> is configured to write to the appsrc: instead of saving the consecutive frames to a video file, it streams to the output sink. When opening the VideoWriter instance, the user should specify the frame width and height and the frame rate of the output stream. You can manually set these parameters or let SkyLine infer them from the input dimensions and the frequency you feed new frames to it. If using this auto-configuration feature, some frames (by default 100) will be discarded at the beginning of the streaming because SkyLine will use them to calculate statistics of the frame rate and measure the frame dimensions. This is the “warmup” of SkyLine. If you send frames with different sizes, SkyLine will resize the input, but this comes with a performance penalty. You are also expected to send new frames to SkyLine with the frequency specified in the frame-per-second parameter. If frames are sent at a different frequency, the video fragments get out of sync in Kinesis Video Streams, and you won’t be able to replay the video smoothly.</p><figure><img alt="Cogwheels of a complicated mechanism" src="https://cdn-images-1.medium.com/max/1024/0*q_5X7-6bJxIl45XF" /><figcaption>Photo by <a href="https://unsplash.com/@joshredd?utm_source=medium&amp;utm_medium=referral">Josh Redd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SkyLine is an abstract base class that handles the state machine of the GStreamer pipeline. The concrete implementation KVSSkyLine sends frames to <a href="https://aws.amazon.com/kinesis/video-streams/">Amazon Kinesis Video Streams</a> service. It is easy to extend SkyLine to support other services, especially if there is already a GStreamer plugin for that.</p><h3>Integrating SkyLine into a Panorama application</h3><h4>Configuring the Docker container</h4><p>SkyLine depends on custom compiled external libraries. All these libraries must be compiled and configured correctly in your application’s docker container to make SkyLine work. These libraries include:</p><ul><li>GStreamer 1.0 installed with standard plugins pack, libav, tools, and development libraries;</li><li>OpenCV 4.2.0, compiled with GStreamer support and Python bindings;</li><li>numpy (it is typically installed by the base docker image of your Panorama application).</li></ul><p>In the case you want to use KVSSkyLine, the SkyLine implementation that streams the video to Amazon Kinesis Video Streams, it will need also the following libraries:</p><ul><li>Amazon Kinesis Video Streams (KVS) Producer SDK compiled with GStreamer plugin support;</li><li>Environment variable GST_PLUGIN_PATH configured to point to the directory where the compiled binaries of KVS Producer SDK GStreamer plugin is placed;</li><li>Environment variable LD_LIBRARY_PATH including the third-party open-source dependencies compiled by KVS Producer SDK;</li><li>boto3 (it is typically installed by the base docker image of your Panorama application).</li></ul><p>In the source code repository of SkyLine, a <a href="https://github.com/Neosperience/backpack/blob/master/examples/Dockerfile">sample Dockerfile</a> is provided in the examples folder that shows how to install these libraries and SkyLine in any container correctly. In most cases, it is required just to copy the relevant sections from the sample to your application’s Dockerfile. Please note that the first time you compile the docker container, it might take up to one hour to correctly compile all libraries.</p><h4>Setting up AWS IAM privileges for KVSSkyLine</h4><p>KVSSkyLine uses the Amazon Kinesis Video Streams (KVS) Producer library, wrapped in a GStreamer sink element, to send the processed frames to the KVS service. KVS Producer needs AWS credentials. It can use the credentials associated with the Panorama Application Role, but you must explicitly configure it. KVSSkyLine needs privileges to execute the following actions:</p><pre>kinesisvideo:DescribeStream<br>kinesisvideo:GetStreamingEndpoint<br>kinesisvideo:PutMedia</pre><p>If KVSSkyLine needs to automatically create the Kinesis Video Stream the first time it is used, you should also include the kinesisvideo:CreateStream action. An example policy allowing KVSSkyLine to write data to Kinesis Video Streams could look like this:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;kinesisvideo:DescribeStream&quot;,<br>                &quot;kinesisvideo:CreateStream&quot;,<br>                &quot;kinesisvideo:GetDataEndpoint&quot;,<br>                &quot;kinesisvideo:PutMedia&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><h4>Setting up credentials</h4><p>There are two types of AWS security credentials: static and temporary. The former never expire and in case of a leak, you should invalidate them manually and reconfigure the applications. For this reason, their use is strongly discouraged in a production environment. Examples of static AWS credentials include the IAM user’s Access Key Id and Secret Access Key pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4vYvkW-ZE4BZmvmJ" /><figcaption>Photo by <a href="https://unsplash.com/@mangelinka?utm_source=medium&amp;utm_medium=referral">Angela Merenkova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Temporary credentials expire after a predefined period. In case of a leak, they can be used only within their expiration time, typically in the order of several hours. Temporary credentials can be renewed before they expire so their lifespan can be extended, or they can be exchanged for new ones with a later expiration time. This process needs additional coordination from the application using this type of credentials. Examples of temporary credentials include the AWS Access Key Id, the Secret Access Key, and the Session Token.</p><p>We offer different options to provide credentials withKVSCredentialsHandler subclasses provided in the kvs module. If you want to use static credentials for testing purposes, <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html">create an IAM user</a> in your AWS account and <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html">attach a policy</a> like the one above to the user. You should configure this user to have programmatic access to AWS resources and get the user’s <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html">AWS Access Key and Secret Key pair</a>: create a KVSInlineCredentialsHandler or KVSEnvironmentCredentialsHandler instance in the application’s code to pass these credentials to KVS Producer Plugin directly in the GStreamer pipeline definition or as environment variables. However, as these credentials do not expire, using this configuration in a production environment is not recommended. Even in a development and testing environment, you should take the appropriate security measures to protect these credentials: never hardcode them in the source code. Instead, use AWS Secret Manager or a similar service to provide these parameters to your application.</p><p>KVSSkyLine can also use the <a href="https://docs.aws.amazon.com/panorama/latest/dev/permissions-application.html">Panorama Application Role</a> to pass the application&#39;s credentials to KVS Producer. These credentials are temporary, meaning that they expire within a couple of hours, and the user should renew them before expiration. The Producer library expects temporary credentials in a text file. KVSFileCredentialsHandler manages the renewal of the credentials and periodically updates the text file with the new credentials. If you want to use this method, attach a policy similar to the example above to your Application Role. Remember to always test your Panorama application — KVS integration if it still works after the KVSFileCredentialsHandler refreshed the credentials. Let your application run for several hours and periodically check if it continues to stream the video to KVS. You will also find diagnostic information in the CloudWatch logs of your application when the credentials were renewed.</p><h4>Environment variables</h4><p>KVSSkyLine needs two environment variables to have GStreamer find the KVS Producer plugin. The name of these variables is GST_PLUGIN_PATH and LD_LIBRARY_PATH. They point to the folder of KVS Producer GStreamer plugin and its 3rd party dependencies. In the sample Dockerfile provided, the correct values of these variables are written to a small configuration file named /panorama/.env in the container. You should pass the path of this file to KVSSkyLine or otherwise ensure that these environment variables contain the correct value.</p><h3>Usage example</h3><p>When initializing a KVSSkyLine instance, you should pass the AWS region name where your stream is created, the name of the stream, and a credentials handler instance. If you want to configure the frame rate and the dimensions of the frames manually, you should also set them here. When both parameters are specified, SkyLine skips the warmup period and sends the first frame directly to KVS. When you are ready to send frames, call the start_streaming method which opens the GStreamer pipeline. After this method is called, you are expected to send new frames to the stream calling the put method periodically, with the frequency specified in the frame rate or inferred by KVSSkyLine. You can stop and restart streaming on the same KVSSkyLine instance.</p><p>The following example uses the temporary credentials of the IAM Application Role assumed by your Panorama application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f819242f7c24cc6519dc6f4c767dd598/href">https://medium.com/media/f819242f7c24cc6519dc6f4c767dd598/href</a></iframe><p>If everything works well, you can watch the restreamed video on the <a href="https://console.aws.amazon.com/kinesisvideo/home">Kinesis Video Streams page</a> of the AWS console. Certainly, you can modify the image before sending it to SkyLine: draw annotations on it based on the inference result of the deep-learning model.</p><h3>Annotations</h3><p><em>Annotations</em> and <em>annotation drivers</em> provide a unified way to draw annotations on different rendering backends. Currently, two annotation drivers are implemented:</p><ul><li>PanoramaMediaAnnotationDriver allows you to draw on panoramasdk.media object, and</li><li>OpenCVImageAnnotationDriver allows you to draw on an OpenCV image (numpy array) object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C-kmqUh2Cb_qHcip" /><figcaption>Photo by <a href="https://unsplash.com/@lucasgwendt?utm_source=medium&amp;utm_medium=referral">Lucas George Wendt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The library can draw two types of annotations: labels and boxes.</p><h4>Using annotations</h4><p>Depending on the available backends, you can create one or more annotation driver instances at the beginning of the video frame processing loop. During the process of a single frame, you are expected to collect all annotations to be drawn on the frame in a python collection (for example, in a list). When the processing is finished, you call the rendermethod on any number of drivers, passing the same collection of annotations. All coordinates used in annotation are normalized to the [0; 1) range.</p><p>Example usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d32c2df0fd1cc80a265dd476702f1e77/href">https://medium.com/media/d32c2df0fd1cc80a265dd476702f1e77/href</a></iframe><h3>Postface</h3><p>Even if SkyLine can be a helpful tool, its usage might raise two concerns that you should consider carefully. We discourage using SkyLine in a production environment: it is a development aid or and a debugging tool.</p><figure><img alt="A warning sign of steep terrain in front of a snowy mountain" src="https://cdn-images-1.medium.com/max/1024/0*L-i9f6e6JStovyIG" /><figcaption>Photo by <a href="https://unsplash.com/@greg_rosenke?utm_source=medium&amp;utm_medium=referral">Greg Rosenke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first concern is of technical nature. Currently, the application code in a Panorama app does not have direct access to the onboard GPU; thus, all video encoding done by SkyLine run on the device’s CPU. This behavior could slow down the appliance: streaming a single output stream with SkyLine could require anything between 10–30% of the CPU capacity of the device.</p><p>The second concern is related to data protection. The Panorama appliance is designed to protect the video streams being processed. It has two ethernet interfaces to separate the network of the video cameras (typically a closed-circuit local area network) from the device’s Internet access. Using SkyLine, you relay the video stream from the protected, closed-circuit camera network to the public Internet. You should carefully examine the data protection requirements of your application and the camera network before using SkyLine. Moreover, you are responsible for keeping private all AWS credentials used by SkyLine, as required by <a href="https://aws.amazon.com/compliance/shared-responsibility-model/">AWS Shared Responsibility Model</a>.</p><h3>Where to go from here?</h3><p>SkyLine is part of Backpack, a broader set of tools that aims to help software development on AWS Panorama. Other components will be presented in a future post, so keep tuned and follow us to get updated.</p><p>Backpack is open source and available <a href="https://github.com/Neosperience/backpack">on GitHub</a>. You can build and run the <a href="https://github.com/Neosperience/backpack/blob/master/examples/Dockerfile">example docker container</a> on an ARM64 based system. For example, suppose you’ve already <a href="https://github.com/aws-samples/aws-panorama-samples/blob/main/docs/EnvironmentSetup.md">set up the Panorama Test Utility</a> on a t4g type EC2 instance. In this case, you can build and launch a shell in this container with the following commands on the EC2 instance:</p><pre>$ git clone <a href="https://github.com/Neosperience/backpack.git">https://github.com/Neosperience/backpack.git</a><br>$ cd backpack/examples<br>$ docker build . -t my_backpack_example:1.0<br>$ docker run -it my_backpack_example:1.0 bash</pre><p>The container can be built and executed also on a MacBook Pro with the new M1 ARM-based chip.</p><p>The backpack library is extensively documented with docstrings. You can read the <a href="https://s3.eu-west-1.amazonaws.com/github-ci.experiments.neosperience.com/Neosperience/backpack/docs/index.html">detailed API docs online</a> or using the python3 interpreter in the container shell:</p><pre>root@my_backpack_example:/# python3<br>&gt;&gt;&gt; import backpack.skyline, backpack.kvs, backpack.annotation<br>&gt;&gt;&gt; help(backpack.skyline)<br>&gt;&gt;&gt; help(backpack.kvs)<br>&gt;&gt;&gt; help(backpack.annotation)</pre><p>You can also try other SkyLine implementations found in Backpack. For example, RTSPSkyLine allows you to host an RTSP server right in the application container, and connect directly to your Panorama appliance with an RTSP client to monitor your application.</p><p>Let me know how you use SkyLine, which new features you would like to see, and stay tuned for future posts about the other components of Backpack.</p><p><strong>Update as of 20/06/2022</strong>: The remote viewing module of the backpack library was renamed to skyline.</p><h3>About the author</h3><p>Janos Tolgyesi is an AWS Community Builder working as Machine Learning Solution Architect at Neosperience. He has worked with ML technologies for five years and with AWS infrastructure for eight years. He loves building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a> or a <a href="https://www.neosperience.com/solutions/user-insight/">user profiler based on clickstream events</a>. You can find me on <a href="https://twitter.com/jtolgyesi">Twitter</a>, <a href="https://medium.com/@janos.tolgyesi">Medium</a>, and <a href="http://linkedin.com/in/janostolgyesi">LinkedIn</a>.</p><p>The open-source project of Backpack was supported by <a href="https://www.neosperience.com/">Neosperience</a>.</p><p>I would like to express my special thanks to <a href="https://medium.com/u/6550450171ac">Luca Bianchi</a> for proofreading this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32922369ecf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/remote-view-your-computer-vision-models-running-on-aws-panorama-32922369ecf">Remote View your Computer Vision Models Running on AWS Panorama</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[Deploy an object detector model at the edge on AWS Panorama]]></title>
            <link>https://medium.com/data-science/deploy-an-object-detector-model-at-the-edge-on-aws-panorama-9b80ea1dd03a?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b80ea1dd03a</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[making-sense-of-big-data]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Fri, 26 Nov 2021 19:38:22 GMT</pubDate>
            <atom:updated>2022-03-18T17:43:31.583Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/making-sense-of-big-data">Making Sense of Big Data</a>, A STEP-BY-STEP GUIDE TO AWS PANORAMA MODEL DEPLOYMENT</h4><h3>Deploy an Object-Detector Model at the Edge on AWS Panorama</h3><h4>Learn how to deploy state-of-the-art computer vision models on AWS Panorama, a powerful edge device to realize online and cost-effective object detection.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WO3r6HtVpByf2oKk" /><figcaption>Photo by <a href="https://unsplash.com/@v2osk?utm_source=medium&amp;utm_medium=referral">v2osk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article was co-authored by </em><a href="https://medium.com/@janos.tolgyesi"><em>Janos Tolgyesi</em></a><em> and </em><a href="https://medium.com/@aletheia"><em>Luca Bianchi</em></a><em>.</em></p><p>In recent years, Computer Vision has become one of the most exciting fields of application for Deep Learning: trained convolutional neural networks (CNN) models can reach human-like accuracy levels detecting objects within an image or a video stream. These incredible advancements opened a broad field of application ranging from retail customer behavior analysis to security and industrial quality assurance.</p><p>In this scenario, a couple of different deep learning models emerged to solve a frequent use case for computer vision: object detection. It is a desirable result per se and a universal foundation of a wide range of applications such as object tracking, pose estimation, and environment monitoring.</p><p>Moreover, when video cameras produce input images, modern computer vision capabilities raise the bar of what is achievable with object detection deep learning models applied to security and monitoring. Such scenarios are nevertheless highly challenging due to the short response time requirement of real-time applications. An alarm should fire within a few seconds from danger detection; otherwise, it would be useless or even harmful.</p><p>Latency plays a significant role in defining constraints to the kind of computation available. Due to restricted bandwidth and unreliable networks, streaming massive video streams to the cloud, processing the video by fast and accurate deep learning model running on a cloud instance is often not feasible or has prohibitive costs. Video analysis constantly requires high provisioned computation capacity, and this requirement fades the advantages of an on-demand or serverless-like, autoscaling infrastructure. Additionally, bandwidth is never cost-effective, making such solutions unaffordable in most use cases.</p><p>Edge computing became a desirable solution to achieve better latencies and lower the total system cost, opening an entirely new market. Unfortunately, building reliable and not expensive hardware with a GPU to run a computer vision model is not an easy task for most data scientists. Considering that the video streams managed by some use cases might contain sensitive information of people’s video footage, security requirements make this task is even more difficult.</p><h3>Entering AWS Panorama</h3><p>In the 2020 virtual edition of Amazon re:Invent, former CEO of Amazon Web Services Andy Jassy <a href="https://aws.amazon.com/about-aws/whats-new/2020/12/introducing-aws-panorama-for-computer-vision-at-the-edge/">presented a new device</a> named AWS Panorama, wholly designed for edge computing. Inside a small package with a compact design and an IP5 enclosure, an Nvidia Jetson Xavier graphic processing unit can analyze up to 16 concurrent video streams. The device’s appearance and setup are presented more in detail in the <a href="https://www.youtube.com/watch?v=xRxAWClUTZc">amazing video</a> by AWS Machine Learning Hero Mike Chambers.</p><p>The easy initial configuration and provisioning experience makes Panorama suitable for installation for non-technical users.</p><h3>Development concepts</h3><p>Under the hood, AWS Panorama does not just deploy a deep learning model but requires the developer to define a <em>Panorama Application</em>. A <em>Panorama Application</em> is a collection of packaged deep learning models, business logic code, and a manifest structure (application graph) that defines the data pipeline between these components.</p><p>The application components are called <em>nodes</em>. Every resource on the device is represented by a <em>node</em>: deep learning models, business logic code, camera streams, even display output, and parameters. Each <em>node</em> has one or more <em>interfaces</em> that define its <em>inputs</em> and <em>outputs</em>. Before deployment, the model and code-type node resources are archived into binary <em>assets</em>. The <em>assets</em> together with a <em>manifest file</em> (package.json) are referred to as <em>packages</em>. The package’s<em> manifest file</em> contains all the information about its <em>assets</em> and defines the <em>interfaces</em> used within the <em>application graph</em>. Additional node-specific details can be provided in a <em>package descriptor</em>, for example, the dimensions of the input tensor of the deep learning model or the application executable entry point. The <em>packages</em> are uploaded to an S3 access point managed by the AWS Panorama service and registered with the service.</p><p>When the developer is deploying the application with the AWS Panorama service, an <em>application manifest</em> file (graph.json) should be provided, defining the application as a graph built up from nodes and edges. At deployment time, the Panorama service finds the registered <em>packages</em> referred by name in the <em>manifest file</em> and downloads them to the Panorama appliance.</p><p>In summary:</p><ul><li>A <em>Panorama application</em> is a collection of connected <em>nodes</em>. The connections are described by the <em>application manifest</em> (or <em>application graph</em>).</li><li>The <em>nodes</em> can have the following <em>types</em>: deep learning model, application source code, camera input, display output, and deploy-time parameters.</li><li>The <em>nodes</em> also define their <em>interfaces</em>. An <em>interface</em> is a list of <em>input</em> and <em>output ports</em>. The <em>ports</em> are named and typed data fields. Numeric, boolean, string, and “media” types are supported.</li><li>Application code and ML models are archived into <em>assets</em>. The <em>assets,</em> together with their manifest file, are referred to as <em>packages</em>. Packages are uploaded and registered by the Panorama service.</li><li>At deployment time, the user should specify the <em>application graph</em>. The Panorama service looks up the <em>packages</em> associated with the single <em>nodes</em> in the graph and downloads the required packages to the appliance.</li></ul><p>For additional information, refer to the <a href="https://docs.aws.amazon.com/panorama/latest/dev/">AWS Panorama Developer Guide</a>.</p><h3>Choosing a state-of-the-art computer vision model for object detection</h3><p>You Only Look Once (YOLO) deep learning model for real-time object detection was <a href="https://arxiv.org/pdf/1506.02640v5.pdf">presented at CVPR 2016</a>. Since then, it has become the standard benchmark for this kind of task. It provides real-time inference performance, generalized object representation understanding (improved accuracy on never seen before images), and scale along the model size / accuracy axis. In contrast to earlier Region-Based Convolutional Neural Networks (R-CNN), YOLO models process the image in just one step. The models have dramatically improved in the following years, introducing a wide range of enhancements, moving through YoloV2, YoloV3, YoloV4, and YoloV5.</p><p>YOLO models can detect objects and identify their position within an image, drawing a bounding box encompassing them. In earlier implementations, the models used a list of pre-defined bounding boxes called anchors and predicted their offset within the image. This approach requires specifying the number of anchors to be detected within a given image region, which can be constraining in some use cases.</p><p>In 2021 the model was further improved, adopting an anchor-free approach with the rise of <a href="https://arxiv.org/abs/2107.08430">YOLOX</a>. YOLOX is implemented in PyTorch, and pre-trained models on the COCO dataset are <a href="https://github.com/Megvii-BaseDetection/YOLOX">released on GitHub</a>. The <a href="https://cocodataset.org/">COCO dataset</a> contains <a href="https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/">80 different object classes</a> including persons, vehicles, some animals, sports equipment, and everyday objects, so the pre-trained model is ready to detect these objects out-of-the-box.</p><h3>Creating a Panorama Application</h3><h4>Prerequisites</h4><p>To follow this step-by-step guide, an AWS Account and an AWS Panorama device are needed. The Panorama device should be provisioned into the account (please refer to Mike’s tutorial above for these steps).</p><p>An RTSP stream is also required for testing the solution, and the Panorama appliance should be able to access it from the network to that it is connected. The stream can be provided by most IP cameras or by a computer running an RTSP server.</p><p>The deployment steps will be carried out using AWS Command Line Interface (CLI) and Panorama (CLI), starting from the sample application provided in the <a href="https://docs.aws.amazon.com/panorama/latest/dev/gettingstarted-deploy.html">AWS Panorama Developer Guide</a>. Ensure that the AWS CLI, the Panorama CLI, and Docker are installed and configured on your workstation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWQSeGGvxU_vTOUfP1zh6g.png" /><figcaption>Panorama Sample Application. Diagram from <a href="https://github.com/awsdocs/aws-panorama-developer-guide/blob/main/docs-source/gettingstarted-sample.md">AWS Panorama Developer Guide</a> (CC BY-SA 4.0).</figcaption></figure><p>This tutorial also comes with an accompanying <a href="https://github.com/mrtj/yolox-panorama-tutorial">GitHub repository</a>, where you can follow the evolution of the project commit by commit, and use it as a reference if you are stuck. We will provide a link to the relevant commit after each step with the bookmark icon: 🔖.</p><h4>The packages of a Panorama application</h4><p>First of all, initialize a project using init-project command of AWS Panorama CLI:</p><pre>$ panorama-cli init-project --name yolox-panorama</pre><p>This command will generates an empty project template. It is just a scaffolding with empty folders named assets and packages, and a JSON file in graphs/yolox-panorama/graph.json. <a href="https://github.com/mrtj/yolox-panorama-tutorial/commit/88ba525">GitHub checkpoint: 🔖</a></p><p>To deploy a Panorama application, at least the following nodes have to be defined:</p><ul><li>camera input,</li><li>model (will wrap YOLOX),</li><li>application code (business logic), and</li><li>display output (HDMI, for debug).</li></ul><p>AWS Panorama defines a particular concept, the “abstract nodes”, because during application development the exact RTSP URI is unknown since it is dependent on the source camera stream.</p><p>This abstraction allows the same application to be released to different appliances, processing different streams (with different RTSP URIs). The Panorama SDK provides an “abstract camera,” a placeholder node for a camera whose connection URI will be defined at deployment time.</p><p>The abstract camera node is added running using the</p><pre>add-panorama-package --type camera</pre><p>command of Panorama CLI. Defining abstract nodes for cameras is not mandatory: a specific RTPS camera stream can be added, using the command</p><pre>create-package --type camera</pre><p>then providing the camera RTSP URI, username, and password inside the “interfaces” field of the generated file packages/${AWS_ACCOUNT_ID}-[camera_name]-1.0/package.json.</p><p>AWS Panorama also offers another type of abstract node to map an HDMI display output. Using this media sink, an annotated video can be displayed on an HDMI monitor connected to the Panorama appliance. A note to consider is that the display is for debugging purposes, and only one application can use it at a time, the first one that was deployed using such a resource.</p><p>Wrapping together all the commands so far, the configuration is achieved through:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57be06d1676cb4ea9ca5736a3d7b4fce/href">https://medium.com/media/57be06d1676cb4ea9ca5736a3d7b4fce/href</a></iframe><h4>A note about AWS account IDs</h4><p>Every Panorama project uses the owner’s AWS account ID in numerous project artifacts. It is used in the folder names, as well as in multiple JSON configuration files. The account ID is typically considered a piece of sensitive information that one might not want to expose publicly. In this tutorial, the account ID is replaced with ${AWS_ACCOUNT_ID} in the command line examples. This expression refers to a variable that can be initialized with the real AWS account ID so that the shell will automatically substitute it. In the JSON snippets, we will use the dummy account ID 123456789012 that should be always replaced manually with the actual AWS account ID.</p><h4>Define the nodes of the application</h4><p>The AWS Panorama CLI does not create nodes in the <em>application graph</em> for the business logic and the deep learning model, so the developer must add them manually.</p><p>This can be done by opening graphs/yolox-panorama/graph.json and adding the following objects in the nodeGraph.nodes array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d2839e267ba8ce56fc98dba2d50c58/href">https://medium.com/media/68d2839e267ba8ce56fc98dba2d50c58/href</a></iframe><p><em>Parameters</em> can be added to a Panorama application, and their value will be specified at deployment time. The application logic can access the value of these parameters at runtime. Parameters are useful for a series of purposes: to define model-related parameters (for example, a detection threshold) or application settings (for example, an S3 bucket name). AWS Panorama supports the following parameter types: int32, float32, boolean, and string.</p><p>In this deployment, a single float32 parameter represents the confidence threshold of the object detector. A detection confidence level below this threshold makes the relative object discarded. <em>Parameters</em> need to be added to the <em>application graph</em> manually as parameter-type <em>nodes</em>. Default values and overriding configuration can be specified along with a human-readable text displayed to the user at deployment time. Add the following object to the nodes array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c9a95f390bb616c68e76428b9336043/href">https://medium.com/media/1c9a95f390bb616c68e76428b9336043/href</a></iframe><p>More information about parameters here can be found in the <a href="https://docs.aws.amazon.com/panorama/latest/dev/applications-manifest.html#applications-manifest-parameters">relevant section</a> of the Panorama Developer Guide.</p><h4>Build the computer vision pipeline</h4><p>Each <em>node</em> plays a particular role within the <em>application</em>: some emit information (camera_node, detection_threshold), others consume data (display_node), and some either emit and consume data such as code_node and model_node.</p><p>Edges direct the information that flows through the application, connecting an <em>output port</em> of a <em>node</em> to the <em>input port</em> of the following one. <em>Input</em> and <em>output ports</em> have a particular type, and only compatible types can be connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oO3ZS8WBzWtJjfIonrdDrw.png" /><figcaption>The component diagram of the application being developed. Source: author’s own work.</figcaption></figure><p>The detection threshold parameter and camera node are linked to the code node. The output of the code node is then linked to the display node. The model node is not connected to other nodes in the graph because the application logic handles information flow to/from the model. We will see later how to send input data to the model after pre-processing, and read out the inference results from the model for post-processing.</p><p>Nodes are connected through edges in the graphs/yolox-panorama/graph.json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee9c670f651326586d8f1778da506d17/href">https://medium.com/media/ee9c670f651326586d8f1778da506d17/href</a></iframe><h4>Add machine learning model artifact</h4><p>The YOLOX model has to be converted to TorchScript, one of the formats supported by AWS Panorama. The full workflow is outlined in the <em>yolox-torchscript</em> <a href="https://github.com/mrtj/yolox-panorama-tutorial/blob/main/yolox-torchscript.ipynb">Jupyter notebook</a>.</p><p>One important aspect is to remember the expected input shape of the exported model, which is needed at a later stage when writing inference code. For image processing models, the input shape has the format of [batch_size, channel_size, width, height]. In this case, batch_size is 1, channel_size equals 3 (red, green, blue), and model specifications define width and height. For <em>yolox-s</em> model the input shape is [1, 3, 640, 640].</p><p>In the last steps of the Jupyter notebook, the TorchScript model is saved as a .tar.gz package. This archive will be used to create the <em>package</em> of the model node.</p><p>The Panorama CLI adds the archive as a project <em>asset</em>, taking the path of the .tar.gz file in the --model-local-path parameter. Before issuing any of these commands, it is important to export the local AWS account ID to have reproducible and portable steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f18500df95292e0355cd2b49da8afb5f/href">https://medium.com/media/f18500df95292e0355cd2b49da8afb5f/href</a></iframe><p>The result is a new <em>node</em> in graph.json, named yolox_s_asset, that should be merged to the already created model_node. Edit the nodes list in a way that only one node remains with this contents:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ddb805fd8d38156eaf725e04d8dca74/href">https://medium.com/media/2ddb805fd8d38156eaf725e04d8dca74/href</a></iframe><p>The interface field refers to the interface attribute in the yolox_s <em>package</em>. The interface name created by Panorama CLI can be changed to a more suitable one, editing the name attribute simply to “interface” in the nodePackage.interfaces array inside packages/${AWS_ACCOUNT_ID}-yolox_s-1.0/package.json.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c593e21fcbd161a44f7f5a1b7830c99/href">https://medium.com/media/0c593e21fcbd161a44f7f5a1b7830c99/href</a></iframe><p>The model descriptor at packages/${AWS_ACCOUNT_ID}-yolox_s-1.0/descriptor.json should contain additional required metadata about your model. Edit this file and adding the framework name PYTORCH and the input name and shape. The final version of the model descriptor should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32107e10ca917935949135b09132fd13/href">https://medium.com/media/32107e10ca917935949135b09132fd13/href</a></iframe><h4>Implementing a computer vision pipeline</h4><p>A computer vision application deployed on AWS Panorama should implement at least the following functionalities:</p><ul><li>continuously query the last frame from the video stream,</li><li>preprocess the frame and convert it into a NumPy array that has the same shape as the deep learning model’s input,</li><li>pass the preprocessed frame to the model (it is already initialized for you by the model node),</li><li>read the inference results and eventually post-process them,</li><li>annotate the frame with the inference result bounding boxes,</li><li>send the annotated frame to the downstream display node.</li></ul><p>In addition to these basic video pipeline handling steps, a model usually implements some business logic, for example:</p><ul><li>counting the number of persons and measuring the distance between them,</li><li>generating alarms if certain conditions verify, for example, the persons do not respect social distancing rules,</li><li>send these alarms to interested parties using a messaging protocol, for example, MQTT or AWS SNS,</li><li>generate business metrics and persistent them (for example, in CloudWatch or in an S3 bucket via Amazon Kinesis Data Firehose) that can be later used for analytics purposes,</li><li>in general, integrate with downstream business applications, or</li><li>take a “screenshot” of an interesting frame and upload it to a data storage service.</li></ul><p>In this tutorial we implement only the media pipeline, with no particular emphasis on the business logic. The main focus is to display the video stream on the HDMI monitor, then integrate the YOLOX object detector model.</p><h4>Build a Panorama application with an Open Container Image format</h4><p>AWS Panorama uses the Open Container Image (OCI) format, to provide the context for an application to run on the device. A minimal docker file, bundled with OpenCV and NumPy to handle respectively images and arrays in Python can be crafted from the stub file created by the Panorama CLI in packages/${AWS_ACCOUNT_ID}-application_logic-1.0/Dockerfile.</p><p>The resulting file should resemble:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7961c4471e195fc6755772863b97a5b1/href">https://medium.com/media/7961c4471e195fc6755772863b97a5b1/href</a></iframe><p>The Dockerfile above performs the following steps:</p><ol><li>Builds on top of the panorama-application base image (this is obligatory for all Panorama applications). This base image contains the Panorama SDK, the infrastructure of communication with other nodes, and others.</li><li>Updates pip and installs OpenCV and NumPy.</li><li>Copies the contents of the host’s src folder inside the /panorama folder in the container.</li></ol><p>Other required dependencies can be installed within the same Dockerfile as well.</p><h4>Define the interface of the application node</h4><p>The first step to do before writing application code for inference is to define the <em>interface </em>of the code <em>node</em> <em>: </em>a construct that lists the <em>input</em> and <em>output ports</em>, providing a way to communicate with other nodes. The interface is defined in packages/${AWS_ACCOUNT_ID}-application_logic-1.0/package.json. Add these objects in the nodePackage.interfaces array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7331dd0734cfafbb0e1717fac006ccd6/href">https://medium.com/media/7331dd0734cfafbb0e1717fac006ccd6/href</a></iframe><p>This defines the video_in input for the media stream, the threshold input as a float32 parameter, and a video_out output for the downstream media consumers. Refer to the edges section of graph.json on how these inputs and outputs are connected with other nodes.</p><h4>Logging setup</h4><p>Since there is no way to debug application logic directly on the Panorama appliance, diagnostic log messages need to be used to achieve application observability. Access to the standard output of the container running on Panorama is disabled, which means that printing messages to the stdout or using a naive configuration of Python logger will not work. Logging needs to be integrated with the logging infrastructure of the Panorama SDK.</p><p>The Panorama daemon watches /opt/aws/panorama/logs folder of the container running on the appliance: any text file written to this folder is going to be sent incrementally to AWS CloudWatch logs. This means that adding a log entry to a file in that folder pushes the new lines directly to the cloud.</p><p>A standard Python logger configuration to fulfill this by the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be35ca2385238c3c4b64c75bf88c010/href">https://medium.com/media/9be35ca2385238c3c4b64c75bf88c010/href</a></iframe><h4>Create an application stub</h4><p>The stub of an application can be created in a new file called <br>packages/${AWS_ACCOUNT_ID}-application_logic-1.0/src/application.py with the following contents:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfefbd6107c3d7221acc2a80d9b7e440/href">https://medium.com/media/dfefbd6107c3d7221acc2a80d9b7e440/href</a></iframe><p>The initializer of the Application class saves the logger as an instance property and initializes the threshold property that later will be populated with the node parameter value. Actually, there is no way to retrieve the name and the expected input size of the model from the model node itself. For this reason, in this example they have been hardcoded.</p><p>Then, the init function reads the node parameter values. The inputs of the code node are defined in the node <em>interface</em> and accessible through the self.inputs property. The names of the inputs come from the code node <em>interface</em> definition. Here the value of the threshold parameter is read and saved as an instance property.</p><p>Whenever more than one camera is connected to the application, the process_streams method iterates over all input streams and call process_media for every one of them. At the end, it sends the modified (annotated) media streams to the video_out output, to be processed by downstream nodes, which here is going to be the HDMI display.</p><p>The process_media method computes every single frame of each stream. It passes the frame to the preprocessor method, calls the model node with the preprocessed frame, and finally post-processes the inference results.</p><p>The preprocess and the postprocess core functions are just stubbed here.</p><p>At last, the main application loop should be started, implementing an entry point for the application. Add the following at the end of application.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23273d21e7f8660c6e059332ae6041b0/href">https://medium.com/media/23273d21e7f8660c6e059332ae6041b0/href</a></iframe><p>One last thing regarding to the application execution is to specify the entry point script of the processing container in the application’s package descriptor. Open packages/${AWS_ACCOUNT_ID}-application_logic-1.0/descriptor.json and modify it to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18be6a3164bb3ce29dee51e169e65404/href">https://medium.com/media/18be6a3164bb3ce29dee51e169e65404/href</a></iframe><h4>Building the application skeleton</h4><p>Building the docker container is easy with Panorama CLI tool:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d1c015b1e4b8b5062c49f7ee2b65d2/href">https://medium.com/media/84d1c015b1e4b8b5062c49f7ee2b65d2/href</a></iframe><p>After running this, edit the node section of graphs/yolox-panorama/graph.json to remove every code_node except the following and change the interface name to interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b8f390def6f8a841b09114ac469137/href">https://medium.com/media/75b8f390def6f8a841b09114ac469137/href</a></iframe><p>Sometimes, Panorama CI adds a second interface within packages/${AWS_ACCOUNT_ID}-application_logic-1.0/package.json. There should be only one of them, so after remove the redundant one, update the other as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bab3c57240d19362300513d3fd815fa9/href">https://medium.com/media/bab3c57240d19362300513d3fd815fa9/href</a></iframe><h4>Packaging the application</h4><p>The AWS Panorama appliance downloads the application packages from a central package repository, implemented by an S3 access point, and maintained by AWS. The compiled package must be uploaded to this central repository with the following command:</p><pre>panorama-cli package-application</pre><p>Panorama CLI uses the <a href="https://aws.amazon.com/cli/">AWS CLI</a> under the hoods to deploy the application’s assets, which means it is going to use the default configured AWS region. Make sure that the default region is the same region where the Panorama appliance was provisioned.</p><h4>Deploy the basic pipeline</h4><p>The application can be deployed to the Panorama appliance as described in the <a href="https://docs.aws.amazon.com/panorama/latest/dev/gettingstarted-deploy.html">Panorama Developer Guide</a>. Since the application does not use any AWS service, there is no need to provide an IAM role for the application. After the deployment phase, the application has the control of the HDMI display (as long as it is the only application deployed to the device). The RTSP video stream coming from the camera is then shown on the screen. Apparently not a big achievement for so much work, but it sets the baseline for further development and closes the loop of deployment.</p><h3><strong>Deploying the YOLOX object detector model to the AWS Panorama</strong></h3><p>The YOLOX model requires the input frames to be sent with a specific format and outputs raw predictions. This means that images have to be pre-processed and post-processed. Pre-processing consists of resizing the input frame to the correct dimensions. Post-processing is a fundamental step for object detection because it projects the prediction array to bounding boxes and detected object classes. These pre- and postprocessing directly can be picked directly from the <a href="https://github.com/Megvii-BaseDetection/YOLOX">YOLOX repository</a>, double checking to have all the dependencies within the Docker image.</p><p>The original <em>yolox-s</em> pytorch model has a dynamic computational graph that allows using dynamic sized inputs but this has some inference-time performance drawback. AWS Panorama requires the model in an optimized TorchScript format, using a static graph.</p><p>Pre-processing is all about resizing the input frame to 640 x 640 pixel input size. Resizing is achieved using a “fit+padding” strategy that does not crop any part of the image but resizes it in a way that the longer side of the image fits the 640 x 640 square. The eventually remaining empty space is padded with gray color. The logic is implemented in <a href="https://github.com/Megvii-BaseDetection/YOLOX/blob/dd5700c24693e1852b55ce0cb170342c19943d8b/yolox/data/data_augment.py#L144">preproc</a> function of <a href="https://github.com/Megvii-BaseDetection/YOLOX/blob/dd5700c24693e1852b55ce0cb170342c19943d8b/yolox/data/data_augment.py">yolox/data/data_augment.py</a> script in the YOLOX repository and should be added to the packages/${AWS_ACCOUNT_ID}-application_logic-1.0/src/application.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5aad446eb80bbf40aeb638f601be4f/href">https://medium.com/media/1c5aad446eb80bbf40aeb638f601be4f/href</a></iframe><p>The model outputs 8400 bounding box candidates of the detected objects, and a single detection can have multiple candidates. Using <a href="https://towardsdatascience.com/non-maximum-suppression-nms-93ce178e177c">Non-maximum suppression (NMS) algorithm</a> in the post-processing method, it is possible to find the candidate with the highest probability to contain the actual object. The YOLOX repository contains this function and some other helpers that can be added to a newly created packages/${AWS_ACCOUNT_ID}-application_logic-1.0/src/yolox_postprocess.py file. Add the following functions from <a href="https://github.com/Megvii-BaseDetection/YOLOX/blob/2c2dd1397ab090b553c6e6ecfca8184fe83800e1/yolox/utils/demo_utils.py">yolox/utils/demo_utils.py</a> in YOLOX repository to the yolox_postprocess.py file:</p><ul><li>demo_postproces</li><li>nms</li><li>multiclass_nms</li><li>multiclass_nms_class_aware</li><li>multiclass_nms_class_agnostic</li></ul><p>The resulting application.py file, after having imported the NMS functions and wired them up in the process_results method should contain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5484d94677b4c6eeba2cb017a4ccc24d/href">https://medium.com/media/5484d94677b4c6eeba2cb017a4ccc24d/href</a></iframe><p>The process_results method iterates over the output of the model and calls the post-processor methods to extract the bounding boxes of the detections. The boxes are scaled to the [0; 1] interval as expected by the stream class of Panorama SDK. Then a rectangle is added for each detection for the output stream. The postprocess method (taken from <a href="https://github.com/Megvii-BaseDetection/YOLOX/blob/2c2dd1397ab090b553c6e6ecfca8184fe83800e1/demo/ONNXRuntime/onnx_inference.py#L73">demo/ONNXRuntime/onnx_inference.py</a> in the YOLOX repository) converts the model output to the expected format of the Non-maximum Suppression algorithm.</p><p>Change the process_media method to invoke process_results instead of preprocess:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85c715896c980e83f5d01335db231b32/href">https://medium.com/media/85c715896c980e83f5d01335db231b32/href</a></iframe><p>Now the application can be built and deployed to the Panorama appliance following the steps described in the previous sections. AWS Panorama sends application logs to CloudWatch console using the above configuration. It can be found filtering the logs with /aws/panorama/devices/ log prefix.</p><h3><strong>Where to go from here?</strong></h3><p>This article just scratched the surface of what can be achieved with computer vision at edge and AWS Panorama offers a great production environment to do that. This step-by-step tutorial is a first example about how a state-of-the-art object detection model can be deployed, allowing to recognize the 80 different object classes of the COCO dataset and locate them with a bounding box, showing the annotated video stream on an HDMI display.</p><p>From here a custom YOLOX model can be trained with a custom image dataset, then deployed to a Panorama application to implement a very specific classification.</p><p>The above results have been developed for a joint project of Neosperience Cloud Services (formerly Mikamai) and Cogen to improve PeopleAnalytics technologies for video surveillance. These results can further raise the bar of applications on edge devices.</p><p>On the “developer side” a lots of business logic can be added to build a complete service around the model, since with the proper IAM role, the application running in the Panorama device can directly access AWS resources such as S3 buckets, MQTT topics, SNS notifications, or CloudWatch metrics.</p><h4>About the authors</h4><p>Janos Tolgyesi is an AWS Community Builder and Machine Learning Solution Architect at Neosperience. He works with ML technologies for five years and with AWS infrastructure for eight years. He loves building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a> or a <a href="https://www.neosperience.com/solutions/user-insight/">user profiler based on clickstream events</a>. You can find me on <a href="https://twitter.com/jtolgyesi">Twitter</a>, <a href="https://medium.com/@janos.tolgyesi">Medium</a>, and <a href="http://linkedin.com/in/janostolgyesi">LinkedIn</a>.</p><p>Luca Bianchi, PhD is an AWS Hero and Chief Technology Officer at Neosperience. He loves serverless and machine learning and is in charge of Neosperience Research and Development. Passionate about technology, ML and computer vision, can be contacted on <a href="https://twitter.com/bianchiluca">Twitter</a>, <a href="https://medium.com/@aletheia">Medium</a>, and <a href="https://www.linkedin.com/in/lucabianchipavia/">LinkedIn</a>.</p><p>Neosperience unlocks the power of empathy with software solutions that leverage AI to enable brands to understand, engage and grow their customer base. Reach out at <a href="http://www.neosperience.com/">www.neosperience.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b80ea1dd03a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploy-an-object-detector-model-at-the-edge-on-aws-panorama-9b80ea1dd03a">Deploy an object detector model at the edge on AWS Panorama</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 the Earth a better place with machine learning at re:Invent 2021]]></title>
            <link>https://medium.com/@janos.tolgyesi/make-the-earth-a-better-place-with-machine-learning-at-re-invent-2021-7d85fb1015f4?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d85fb1015f4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinvent]]></category>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[climate-change]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 20:51:13 GMT</pubDate>
            <atom:updated>2021-11-11T07:00:12.398Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to fight climate change with machine learning skills at one of the biggest tech conferences</h4><figure><img alt="A morning picture of a green, summertime forest" src="https://cdn-images-1.medium.com/max/1024/0*B6rbJPiGEA1UOW4E" /><figcaption>Photo by <a href="https://unsplash.com/@jplenio?utm_source=medium&amp;utm_medium=referral">Johannes Plenio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>From time to time, I contemplate how lucky I am to do a work I really enjoy. I suppose most machine learning practitioners agree with me: we love doing our job because it is fun, interesting, challenging, and ever-changing. Still, sometimes I stop and think about: besides the intellectual satisfaction, can I be proud of what am I doing also in the moral sense? Do I make the world better with my work?</p><p>Without a doubt, one of our and the coming generation’s biggest issues is climate change. We write notices in public toilets saying, “Please leave this place at least as tidy as you’ve found it!” but we can’t keep up with this simple message regarding our planet. So, what if you could utilize your machine learning skills to make the Earth a better place? The good news is that if you want to learn about how to do it, you should just tune in to the following sessions on AWS re:Invent.</p><p>By the way, what is AWS re:Invent? It is the one of the most influential annual learning conferences in the cloud space. Organized by Amazon Web Services in 2021 it will happen between <a href="https://reinvent.awsevents.com/">November 29 and December 3 in Las Vegas</a>. If you can’t participate in person, most of the learning materials will be available online for free. I will provide the identifier of each session so you can easily search them in the session catalog.</p><h4>Get the data and start predicting the climate change</h4><p>All data scientists know that the hardest part of any machine learning project is to get good quality data. If you want to start analyzing climate and weather-related data, you are lucky: you can find more than 50 datasets already collected, organized, and published in their <a href="https://registry.opendata.aws/">Registry of Open Data</a> that anyone can access at no cost.</p><figure><img alt="A picture of a threatening thunderstorm over a crop field." src="https://cdn-images-1.medium.com/max/1024/0*2VjZw-1Y9tH8wi7h" /><figcaption>Photo by <a href="https://unsplash.com/@davehoefler?utm_source=medium&amp;utm_medium=referral">Dave Hoefler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>But how to get started? Learn from Earth scientist <a href="https://www.linkedin.com/in/zflamig/">Zac Flamig</a> at the chalk talk titled “Methods for analyzing climate and weather data” (WPS202). He promises you to show solving practical problems, like how hot it will be tomorrow, if your building will flood more frequently over the next 100 years, or how much solar power you will generate in the next hour.</p><h4>So Long, and Thanks for All the Fish</h4><p>Next time when you eat your tuna nigiri sushi or poke bowl, think a second to the valiant guys who dedicate their carrier to let you eat fish even tomorrow and the day after. Indeed, large-scale fisheries seriously threaten the extinction of tuna species.</p><figure><img alt="A school of vermillion snapper swim over the reef." src="https://cdn-images-1.medium.com/max/1024/0*S5PotlPfDaZHz76J" /><figcaption>Photo by <a href="https://unsplash.com/@noaa?utm_source=medium&amp;utm_medium=referral">NOAA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Responding to this problem, non-profit organizations like <a href="https://www.nature.org/">The Nature Conservancy</a> create a sustainable tuna supply chains model. And guess what, they also use machine learning for doing so. Figure out how at the “AI/ML for sustainability innovation: Insight at the edge” breakout session (AIM207) held by <a href="https://www.linkedin.com/in/nelsonricardogonzalez/">Nelson Gonzalez</a>, Head of Global Impact Computing at AWS, and <a href="https://www.linkedin.com/in/mark-zimring-6892b911/">Mark Zimring</a>, Director of Large Scale Fisheries Program at The Nature Conservancy.</p><h4>Cottage or your arena, build it with zero-carbon emissions</h4><p>Housing is responsible for <a href="https://theconversation.com/5-charts-show-how-your-household-drives-up-global-greenhouse-gas-emissions-119968">one-third of CO2 emissions</a> in the U.S, so constructing sustainable buildings can make a big difference. Amazon wants to tell you the way they do it. As usual, they think in big: they’ve just finished the reconstruction works of their <a href="https://en.wikipedia.org/wiki/Climate_Pledge_Arena">Climate Pledge Arena</a> in Seatle, turning it into the first zero-carbon arena in the world.</p><figure><img alt="The name plate of the Climate Pledge Arena" src="https://cdn-images-1.medium.com/max/1024/1*iBbsJjOvI9dPjXkpEwRLkw.jpeg" /><figcaption>Photo by <a href="https://www.flickr.com/photos/matthucke/">Matt Hucke</a> on <a href="https://www.flickr.com/">Flickr</a></figcaption></figure><p>Machine learning also has an important role in this field: accurately analyzing energy, water, and air-quality data and building forecasting models can help optimally distribute these resources. Check out their breakout session “Driving sustainable operations at Amazon and Climate Pledge Arena” (AMZ202); maybe you can get some hints on how to build also a cottage in a greener way.</p><h4>Get the big picture</h4><p>Our planet is continuously changing. We have many thousands of satellites monitoring it every second, generating hundreds of terabytes of data every day. How to handle this data? And how to notice a relatively small change, for example, a forest fire, or an oil pipeline leakage, as quickly as possible?</p><figure><img alt="View of the Earth as seen by the Apollo 17 crew traveling toward the Moon." src="https://cdn-images-1.medium.com/max/1024/0*nruidIji39S0Bb2f" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You guessed right: using machine learning. <a href="https://ursaspace.com/">Ursa Space Systems</a> does exactly so, and they will tell you how they do it in the chalk talk “Illustrating changes on the earth with insights from space” (WPS209). If you would like to see the big picture, this session is for you.</p><h4>The bonus track</h4><p>So, you saved the planet also today. You deserve some chilling: let’s get a fresh handcrafter beer. You would like to try out something new today, but where to get it?</p><figure><img alt="A photo of a pint of beer in a frosted mug." src="https://cdn-images-1.medium.com/max/1024/0*UIKGLedrWWuKoTRD" /><figcaption>Photo by <a href="https://unsplash.com/@patrickian4?utm_source=medium&amp;utm_medium=referral">Patrick Fore</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Don’t panic, re:Invent has the response also for this question: find your new beet with the Craft Beer mobile app. Personalized recommendations generated by machine learning models! Real-time feedback taken into account to improve future recommendations! What else could you wish? Drop yourself in the breakout session “Build an app to find your next favorite brew” (BOA302) and get … at least some beer suggestions.</p><p>I am Janos Tolgyesi, Machine Learning Solution Architect and ML Team Leader at <a href="https://www.neosperience.com/">Neosperience</a>. I am working with ML technologies for five years and with AWS infrastructure for eight years. I love building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a> or a <a href="https://www.neosperience.com/solutions/user-insight/">user profiler based on clickstream events</a>. For any questions, you can find me on <a href="https://medium.com/@janos.tolgyesi">Medium</a> or Twitter as <a href="https://twitter.com/jtolgyesi">@jtolgyesi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d85fb1015f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-validate your machine-learning model with SageMaker and Step Functions]]></title>
            <link>https://medium.com/data-science/cross-validate-your-machine-learning-model-with-sagemaker-and-step-functions-6610e9c6ab32?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6610e9c6ab32</guid>
            <category><![CDATA[step-functions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Thu, 06 May 2021 12:25:37 GMT</pubDate>
            <atom:updated>2021-05-06T12:25:37.869Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Automatize cross-validated machine-learning training jobs on AWS infrastructure</em></h4><figure><img alt="Antelopes on the savanna" src="https://cdn-images-1.medium.com/max/1024/1*8470iQKEHAKdcRXDDwelLw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/teefarm-199315/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=3758346">TeeFarm</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=3758346">Pixabay</a></figcaption></figure><p>Cross-validation is a powerful technique to build machine learning models that perform well on unseen data. However, it can also be time-consuming as it includes training multiple models. This post will show you how to easily cross-validate a machine-learning model using several services of Amazon Web Services (AWS), including SageMaker, Step Functions, and Lambda.</p><h3>Why do you need cross-validation?</h3><p><em>If you know the concept of cross-validation, feel free to jump directly to the section introducing </em><a href="#1d23"><em>SMX-Validator</em></a><em>.</em></p><h4>The problem of small datasets and sample distribution</h4><p>Imagine the antelopes of the savanna entrust you to train an image classifier model that helps them recognize jaguars in a picture. They give you 50 photos of a jaguar and 50 photos of the savanna with no jaguars. You divide the dataset into a training set of 80 images and a test set of 20, taking care that there would be an equal number of jaguar and non-jaguar photos in each partition. You train your model with your favorite image classifier algorithm and get an impressive validation accuracy of 100%.</p><p>As a visual check, you look at some correctly classified photos in the test set:</p><figure><img alt="Amur Leopard" src="https://cdn-images-1.medium.com/max/1024/1*UqT5MDhuavRN6snemDfqOA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/markmurphy-10772193/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4112011">Mark Murphy</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4112011">Pixabay</a></figcaption></figure><p>Everything looks good.</p><p>Sometime later, you retrain your model. You split the same dataset again into 80% train — 20% test sets, use the same hyperparameters that you used for the first model, and get a validation accuracy of 80%, with a couple of false negatives (lethal for the antelopes!). So what has happened?</p><p>You look at the false negatives in the test set and find photos like this:</p><figure><img alt="Camouflaged Sri Lankan Leopard" src="https://cdn-images-1.medium.com/max/1024/1*ajqHP7kNpQzJxGojsI85hA.jpeg" /><figcaption>Photo by <a href="https://commons.wikimedia.org/wiki/File:Camouflaged_Sri_Lankan_leopard_(Panthera_pardus_kotiya).jpg">Senthiaathavan</a> from <a href="https://commons.wikimedia.org/wiki/Main_Page">Wikimedia Commons</a></figcaption></figure><p>It seems that there are “easier” and “harder” examples in your dataset. When you split your dataset into the train/test sets, your goal is always that the <em>test set would be a good representative of the whole dataset</em>. Talking about class distribution, you can enforce this using a stratified split strategy, but what about sample “hardness”? It is a much more difficult task. Especially if you have a small dataset, you could easily get a split where all “hard” samples finish in the training set, so your test set will contain only “easy” ones that lead to a good test score. On the other hand, if most “hard” examples are in the test set, you will get a worse result using a model trained with the same hyperparameters.</p><h4>Hyperparameter optimization</h4><p>Another significant case is when you are tuning the hyperparameters of your model. In the case of <a href="https://en.wikipedia.org/wiki/Hyperparameter_optimization">hyperparameter optimization</a>, you iteratively modify some hyperparameters of the model, retrain it with the same training set and check the performance on the validation set. If the model performance improves, you know that the hyperparameter adjustment was likely in the correct direction, so you know how to continue the tuning phase.</p><figure><img alt="Sound Mixer Image" src="https://cdn-images-1.medium.com/max/1024/1*hP4-qGAGmEDNQlmlZR9oIg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/niklas_ahrnke-10296613/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=3721929">Niklas Ahrnke</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=3721929">Pixabay</a></figcaption></figure><p>The problem with this approach is that some information is leaking from the validation set to the training process. As the hyperparameter update step depends on the model’s performance on the validation set, you might end up with a hyperparameter set (and model) optimized for <em>that particular validation set</em> and not for the generic case. The simplest solution to this problem is splitting the dataset into three partitions: <a href="https://en.wikipedia.org/wiki/Training,_validation,_and_test_sets">training, validation, and test sets</a>; tune your model with the training and validation set and get the final performance metrics with the completely unseen test set. Unfortunately, this means that the portion of the training samples is even smaller as you should split your dataset, for example, into 60% train — 20% validation — 20% test partitions.</p><h4>Other reasons</h4><p>There are some other scenarios when cross-validation can be particularly useful, for example:</p><ul><li>when your dataset contains interdependent data points,</li><li>or when you plan to stack up machine learning models so that the input of one model is the prediction output of the previous model.</li></ul><p>For a detailed discussion of these cases, check out <a href="https://towardsdatascience.com/5-reasons-why-you-should-use-cross-validation-in-your-data-science-project-8163311a1e79">this article</a>.</p><h3>How can cross-validation help?</h3><p><a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)"><em>Cross-validation</em></a> is a group of techniques to assess how well your model can generalize for unseen data. Think about the standard train-test split of the dataset as one round of a cross-validation process. Indeed, most cross-validation strategies use multiple rounds to split the dataset into different partitions, train models on each split and assess their combined performance.</p><p>One of the most often used cross-validation strategies is called <em>k-fold cross-validation</em>. Wikipedia gives a <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation">precise definition</a> of what it is:</p><blockquote>In k-fold cross-validation, the original sample is randomly partitioned into k equal-sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k−1 subsamples are used as training data. The cross-validation process is then repeated k times, with each of the k subsamples used exactly once as the validation data. The k results can then be averaged to produce a single estimation.</blockquote><p>For example, if you use 5-fold cross-validation, you will train five different model using the following splits:</p><figure><img alt="5-fold cross-validation split scheme" src="https://cdn-images-1.medium.com/max/1024/1*PiqYaSYz99-j9KDPtrQX-Q.png" /><figcaption><em>Illustration by the author</em></figcaption></figure><p>In the jaguar classification example above, the “hard” sample will turn up in the test set of one training round and the training set of the other four rounds. Examining the accuracy of all five models will give you a better overall picture of how your model will perform on an unseen dataset. At the same time, you’ve used all available data to train and validate your model.</p><p>This process might sound good, but it means that you have to execute the following additional steps before training your model:</p><ul><li>split the dataset into five folds,</li><li>assemble the splits into the training sets and a test set of the five training rounds,</li><li>schedule the training of each machine learning models on the available hardware, and</li><li>collect the training metrics from each training job.</li></ul><p>The steps above are a considerable overhead to deal with, especially if you need to train your model regularly.</p><p>Here comes into play SMX-Validator.</p><h3>SMX-Validator</h3><p>SMX-Validator is an application directly deployable to AWS infrastructure that manages the cross-validated training of almost any supervised machine learning model that you can train with SageMaker.</p><p>The application is built upon several AWS services:</p><ul><li><a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a> is a cloud machine learning platform that enables developers to create, train, and deploy machine learning models in the AWS cloud.</li><li><a href="https://aws.amazon.com/step-functions/">AWS Step Functions</a> is a serverless function orchestrator and state machine implementation that can sequence AWS Lambda functions and other AWS services, including SageMaker.</li><li><a href="https://aws.amazon.com/lambda/">AWS Lambda</a> is a serverless computing platform that runs code in response to events, such as a SageMaker “training finished” event. It also automatically manages the computing resources to run that code.</li><li><a href="https://aws.amazon.com/s3/">Amazon S3</a> is an object storage service that allows storing data in the cloud with a filesystem-like interface.</li></ul><p>After deploying SMX-Validator to your AWS account, you specify a machine learning training template, an input dataset, and the number of folds you want to use in the training phase. The application will automatically orchestrate all training jobs, execute them in parallel and report back the results and performance of each training job. Follow along to train your first cross-validated job with SMX-Validator. In this walkthrough, we will use an image classification task as an example.</p><h4>Prerequisites</h4><ol><li>An AWS account. If you don’t have one yet, open a <a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/">new one</a>.</li><li>AWS offers a <a href="https://aws.amazon.com/free/">free tier</a> for new accounts. However, GPU instances (highly recommended for training image classifiers) are not included, so you should expect some training costs in the order of magnitude of several USDs.</li><li>A dataset that you want to use for training. In the <a href="#d5c4">Prepare your data</a> section below, I will describe how to get a dataset if you don’t already have one.</li><li>SMX-Validator is a <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html">Serverless Application Model (SAM)</a> application. You can <a href="https://serverlessrepo.aws.amazon.com/applications/eu-west-1/043458249825/SMX-Validator">deploy it directly</a> from the <a href="https://aws.amazon.com/serverless/serverlessrepo/">Serverless Application Repository (SAR)</a>, or you can build it with the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">SAM Command Line Interface (CLI)</a> and deploy it manually to your AWS account. If you choose manual installation, you should install the SAM CLI with Docker and set up your AWS credentials as described in the documentation.</li></ol><h4>Supported SageMaker algorithms and containers</h4><p>You can use any supervised training container with SMX-Validator that accepts a newline-separated file as input, for example:</p><ul><li><strong>Linear Learner</strong> with <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html#ll-input_output">CSV input format</a>,</li><li><strong>K-Nearest Neighbors Algorithm</strong> with <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/k-nearest-neighbors.html#kNN-input_output">CSV input format</a>,</li><li><strong>Image Classification Algorithm</strong> with <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/image-classification.html#IC-augmented-manifest-training">Augmented Manifest Image Format</a>,</li><li><strong>XGBoost Algorithm</strong> with <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html#InputOutput-XGBoost">CSV input format</a>,</li><li><strong>BlazingText</strong> in Text Classification mode with <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/blazingtext.html#blazingtext-data-formats-text-class">File Mode or Augmented Manifest Text Format</a>,</li><li>or your custom training container that accepts newline-separated files as input.</li></ul><h4>Prepare your data</h4><p>In this tutorial, we will use a binary image classification dataset. If you don’t have one, you can use the famous <a href="https://www.kaggle.com/c/dogs-vs-cats">dogs-vs-cats</a> dataset. Download the dataset from Kaggle to a directory on your computer. <a href="https://s3.console.aws.amazon.com/s3/bucket/create">Create also an S3 bucket</a> and upload all image files to the bucket.</p><p>To use SMX-Validator with SageMaker Image Classification, we will organize the dataset metadata into an <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/image-classification.html#IC-augmented-manifest-training">Augmented Manifest Image Format</a> file. Assuming you use the Dogs vs. Cats dataset, this python snippet should do the job:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97820ae842172c68e90bff7e2d0e3ff/href">https://medium.com/media/c97820ae842172c68e90bff7e2d0e3ff/href</a></iframe><p>Remember to change my_bucket/dogs_vs_cats to the bucket name and prefix of your input dataset location. This script will assign the class id 0 for dogs and 1 for cats. Upload also the created manifest.jsonl to the input bucket.</p><p>If you prefer to generate the manifest file directly from the contents of the S3 bucket, you could use a script similar to the following. You should point the bucket and the prefix variables to your dataset also in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e66ff92e8262c7407c7903e73a645eb/href">https://medium.com/media/3e66ff92e8262c7407c7903e73a645eb/href</a></iframe><h4>Deploy SMX-Validator</h4><p><a href="https://serverlessrepo.aws.amazon.com/applications/eu-west-1/043458249825/SMX-Validator">SMX-Validator is published on AWS Serverless Application Repository</a>. The simplest way to deploy the application is by clicking the “Deploy” button on the application page. You should fill out two parameters before deploying the application:</p><ul><li>InputBucketName: the name of the S3 bucket where you uploaded your dataset. The application will create an <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html">IAM Role</a> at deployment time that allows reading data from this bucket.</li><li>OutputBucketName: the name of an S3 bucket where the application can write partial results and working data. Reading and writing data to this bucket will be granted to the application via the IAM role above.</li></ul><p>You might want to create these two buckets before deploying the application. You should also acknowledge that the app will create custom IAM roles. These roles enable the application to start SageMaker training jobs and read/write from/to the above buckets.</p><p>Alternatively, you can clone the git repo of SMX-Validator and build the application with the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">SAM-CLI</a>. Follow the <a href="https://github.com/mrtj/smx-validator">readme in the project repository</a> for details.</p><h4>Start a cross-validated training job</h4><p>SMX-Validator deploys a Step Functions state machine that orchestrates the training of the cross-validated folds. You can start a cross-validated job launching a new execution of the state machine.</p><p>You should specify some input parameters of the cross-validated training job in a JSON file, like:</p><ul><li>the S3 path of the input manifest.jsonl,</li><li>the output path (these paths should point to the buckets you specified at application deploy time),</li><li>the name of the cross-validated training job,</li><li>the number of folds, and</li><li>a SageMaker training job template including training hyperparameters and the training resource configuration.</li></ul><p>You can find the <a href="https://github.com/mrtj/smx-validator/blob/master/resources/schemas/input.schema.json">input schema specification</a>, <a href="https://github.com/mrtj/smx-validator/blob/master/doc/input.schema.md">detailed documentation</a>, and a complete <a href="https://github.com/mrtj/smx-validator/blob/master/doc/sample_event.json">example of an input file</a> in the documentation of <a href="https://github.com/mrtj/smx-validator">SMX-Validator</a>.</p><p>Once you created your input JSON file, you have different options to start the execution of the state machine:</p><ul><li>Using the <a href="https://docs.aws.amazon.com/cli/latest/reference/stepfunctions/start-execution.html">AWS CLI</a>:</li></ul><pre>aws stepfunctions start-execution \<br>  - state-machine-arn {CrossValidatorStateMachineArn} \<br>  - input file://my_input.json</pre><ul><li>In the <a href="https://console.aws.amazon.com/states/home#/statemachines">AWS Step Functions web console</a>, select CrossValidatorStateMachine-*, and on the State Machine page, click the “Start execution” button. Copy the contents of your input JSON into the Input text area.</li><li>Using the <a href="https://aws.amazon.com/tools/">AWS SDKs</a> from a local script or a lambda function.</li></ul><p>SMX-Validator will split the input dataset into folds, assemble the training and test sets and launch <em>k</em> training jobs possibly in parallel. You can adjust the number of concurrently executed jobs in the state machine specification file (by default two) to the number of available ml-instances in your AWS account. The diagram below illustrates the state machine of the SMX-Validator. The steps in the dashed boxes are executed concurrently.</p><figure><img alt="Step Functions state machine diagram" src="https://cdn-images-1.medium.com/max/1024/1*d8GOp70wSsJ9ZTIedWe8BA.png" /><figcaption>Illustration by the author</figcaption></figure><h4>Training jobs</h4><p>SMX-Validator will launch a SageMaker training job for each cross-validated training rounds. The number of splits (and the training jobs) you define in the crossvalidation.n_splits parameter. The training jobs will be named based on the following template:</p><pre>crossvalidator-{input.job_config.name}-{YYYYMMDD}-{HHMMSS}-fold{fold_idx}</pre><p>where {input.job_config.name} is the job name from the input configuration, {YYYYMMDD}-{HHMMSS} is the timestamp at the start of the job and {fold_idx} is the zero-based index of the round.</p><p>Visit the <a href="https://console.aws.amazon.com/sagemaker/home#/jobs">SageMaker Training Jobs</a> page in the AWS management console to get an overview of all jobs launched by SMX-Validator. You can find the training and validation metrics diagrams and the final metric values on the page of a single training job.</p><p>The application will also report the details of the training jobs in the Step Functions execution output JSON. This JSON will contain the following fields:</p><ul><li>job_config: Parameters of generic for the whole cross-validated training job, like job name, SageMaker Experiment and Trial name, job input, and output data.</li><li>crossvalidation: Cross-validation parameters, like the number of splits used in the job.</li><li>training: The template structures used to create the training jobs.</li><li>splits: This array contains the detailed results of each training job. It corresponds to the output of the DescribeTrainingJob SageMaker API call. Besides the exact training job inputs, you can find the training time and duration, billable seconds, final metrics value, and output artifacts location in this structure.</li></ul><h3>Conclusion</h3><p>Cross-validating a machine learning model is a powerful tool in the toolbelt of every data scientist. It can help you to efficiently assess models trained on a small dataset, in the case the dataset contains samples of variable “difficulty” or if you are optimizing model hyperparameters. However, training multiple models on limited hardware resources can be time-consuming and needs manual orchestration. SMX-Validator helps training k-fold cross-validated machine learning models on AWS infrastructure, taking care of the heavy-duty task orchestration of the training jobs.</p><p>Check out also the source code and the complete documentation on the <a href="https://github.com/mrtj/smx-validator">GitHub page of SMX-Validator</a>.</p><p>I am Janos Tolgyesi, Machine Learning Solution Architect and ML Team Leader at <a href="https://www.neosperience.com/">Neosperience</a>. I am working with ML technologies for four years and with AWS infrastructure for seven years. I love building things, let it be a <a href="https://www.neosperience.com/solutions/people-analytics/">video analytics application on the edge</a> or a <a href="https://www.neosperience.com/solutions/user-insight/">user profiler based on clickstream events</a>. For any questions, you can find me on <a href="https://medium.com/@janos.tolgyesi">Medium</a> or Twitter as <a href="https://twitter.com/jtolgyesi">@jtolgyesi</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6610e9c6ab32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cross-validate-your-machine-learning-model-with-sagemaker-and-step-functions-6610e9c6ab32">Cross-validate your machine-learning model with SageMaker and Step Functions</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[How many people really die connected to COVID-19 in Italy?]]></title>
            <link>https://medium.com/@janos.tolgyesi/how-many-people-really-die-connected-to-covid-19-in-italy-e6facbf0c862?source=rss-539653be15a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6facbf0c862</guid>
            <category><![CDATA[mortality]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[epidemic]]></category>
            <category><![CDATA[italy]]></category>
            <dc:creator><![CDATA[Janos Tolgyesi]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 16:45:58 GMT</pubDate>
            <atom:updated>2020-04-23T07:19:00.384Z</atom:updated>
            <content:encoded><![CDATA[<p>At the end of February 2020 the <a href="https://en.wikipedia.org/wiki/2019%E2%80%9320_coronavirus_pandemic">COVID-19 epidemic</a> was a shocking surprise for Italy, the first affected country in Europe. Very soon after the outbreak local authorities started to publish daily epidemic information including the number of confirmed cases and deaths. However after several weeks it became clear that the official data is flawed because of data collection methodology issues and other reasons.</p><p>In this analysis we make an attempt to estimate the real death toll of the COVID-19 epidemic during March 2020 in several regions of Italy. We compare the daily mortalities in 2020 as reported by the Italian National Institute of Statistics to the same period of previous years. We will see that the real death toll of the epidemic is most likely several times underestimated by the official figures but also that the lockdown measures by local authorities were effective.</p><h3>History of publishing COVID-19 epidemic data in Italy</h3><p>Italy was the first European country to be hit hard by the COVID-19 epidemic in the last days of February 2020. After the initial shock the authorities, particularly the <a href="http://www.protezionecivile.it/">Civil Protection Department</a> started to publish <a href="http://www.salute.gov.it/portale/nuovocoronavirus/dettaglioContenutiNuovoCoronavirus.jsp?id=5351&amp;area=nuovoCoronavirus&amp;menu=vuoto">daily bulletins</a> about the number of infected persons, deaths and recoveries. Worried epidemiologists, statisticians, data scientist and data enthusiasts started to write computer programs to automatically analyze the bulletin webpage on a daily basis. A lot of effort was dedicated to register the day-to-day evolution of the epidemic and to create time series that later could be analyzed. The government authorities were asked to publish the same data also in a machine-readable way.</p><p>Several days later, on 7th of March, the Civil Protection Department created a <a href="https://github.com/pcm-dpc/COVID-19">GitHub repository</a> with an extraordinary agility and started to publish daily updates of the epidemic data as well as historic time series in CSV and JSON format. The daily time series data are currently available on national and regional level for the number of infected, hospitalized (in ICU or not), recovered people, as well as the number of tests carried out that day and the deaths attributed to COVID-19. The total number of confirmed cases is available also on “comune” (municipality) level. Making available the data with this level of details should be an exemplary transparency of the authorities.</p><h3>Reliability of the official data</h3><p>Unfortunately it became clear very soon that the methodology of the <em>collection</em> of this data lacks the same exactitude as of <em>publishing</em> the data. This might be due to a number of facts.</p><p>First, the Italian healthcare system and the testing capacities were overwhelmed in an unprecedented way within a couple of days after the beginning of the outbreak. They had simply no resources for systematic testing and reporting.</p><p>Second, in Italy the <a href="https://en.wikipedia.org/wiki/Healthcare_in_Italy">healthcare system is fragmented</a> as they are managed on a regional level: in fact each region has its own healthcare system. These organizations interpret the government policies (for example about COVID-19 testing) in sightly different ways so they collect the data also in different ways.</p><p>And at last, there might be political reasons not to change an established, nevertheless wrong data collection methodology. <a href="https://edition.cnn.com/2020/02/21/health/coronavirus-reported-cases-covid-19-change-intl/index.html">China changed several times</a> its testing policy and on 12th February one such change resulted in a sudden jump in the positive cases. Almost all published diagrams showing the Chinese COVID-19 cases note that the cause of this jump is a change in the methodology, but not all people read the small letter annotations. There is a real risk that such a methodology change can cause confusion or even scare in the public.</p><figure><img alt="China changed case definition on 12th February" src="https://cdn-images-1.medium.com/max/952/1*B3bbs05jDaJWPneeQ7-DOg.png" /><figcaption>China changed case definition on 12th February</figcaption></figure><h4>Testing only people reaching the hospital</h4><p>During March representatives of Italian national, regional and local authorities acknowledged the flaws of the COVID-19 epidemic data collection methods. As soon as 28 February Ministry of Health of Italy <a href="https://www.repubblica.it/cronaca/2020/02/28/news/cambia_il_metodo_di_conteggio_esclusi_i_positivi_asintomatici-249765660/">announced that they will not count the asymptomatic cases</a> in future statistics even if they were tested positive.</p><p>Several days later they decided to do virology tests only for persons who have reached the hospital, and stopped home testing at all because of capacity issues. After the first week of March the healthcare system at least in several territories of Lombardy became so overwhelmed that they could not provide hospital care even for some serious cases. In the emergency or even telephone triage factors like patient age and preexisting medical conditions were considered more and more aggressively. Only people with considerably good prognosis could get hospitalization.</p><p>In practice this meant that a number of elderly and vulnerable people died at their home because of pneumonia or heart failure. As home or post-mortem testing was not available, these victims were never tested for COVID-19 and so they are invisible for the statistics.</p><h4>Number of ICU cases capped at the number of beds</h4><p>Having the hospital beds and especially the ICU beds capacity utilized near at 100% means also that number of cases in hospital or ICU unit does not reflect the number of persons who actually needed it. These numbers are capped at the number of available places. Furthermore this data reflects only a daily snapshot of the situation without the details of how many new patients are accepted in these structures and how many are discharged.</p><h4>Multiple tests for the same patient counted separately</h4><p>In the same period it became evident that even the number of virology tests executed daily is practically useless for statistical analysis. This number contains <em>all</em> tests evaluated that day. For a single patient at least three tests are done: the initial positive test and then at least two negative tests before they are considered recovered. Naturally even more than 3 tests can be also carried out for the same individual. Considering that only the total sum of the tests are included in the report, it is impossible to deduct which percentage of the tested people is actually positive. Not talking about that the results of the test (and so the inclusion of the result in the statistics) is delayed by an arbitrary number of 2–8 days after the sample was taken.</p><h4>Combined variable for “discharged” and “recovered” cases</h4><p>At last we should talk about the variable in the official statistics that is called “dimessi guariti” (discharged recovered). This number is commonly interpreted as the number people who have recovered from COVID-19, for example by the <a href="https://coronavirus.jhu.edu/map.html">Johns Hopkins University dashboard</a> or by <a href="https://www.worldometers.info/coronavirus/country/italy/">Worldometer</a>. The trick of this naming is that it does not specify if we are speaking about “discharged <em>and</em> recovered” or alternatively “discharged <em>or</em> recovered” persons. Two NGO <a href="https://www.ilpost.it/2020/04/02/guariti-coronavirus-protezione-civile/">tried to understand the real meaning</a> of this variable and independent healthcare sources confirmed them that in fact it should be interpreted the second way: the number of discharged <em>or</em> recovered persons. It might seem a subtle difference but this way the variable includes the number of persons who visited the hospital, tested positive for COVID-19 but then sent home to stay in quarantine at their place because they had mild conditions or because there were no available hospital beds for them. No follow up is provided for these cases: we do not know anything if and when they were really recovered, and typically no more testing is done for them.</p><h4>Regional differences</h4><p>To make the situation even more confused, as mentioned above, different regions interpret the government guidelines in different ways so the methodology of data collection changes also from region to region. It is practically impossible to get a clear picture about the current epidemic situation looking at the official data, still even serious political decisions are done based on it.</p><h3>Pursuing a reliable data source</h3><p>After reading the above paragraphs you might ask: all right, but where can we get reliable information about how is going the COVID-19 epidemic in Italy? Fortunately the <a href="https://www.istat.it/">Italian National Institute of Statistics</a> (ISTAT) publishes the mortality rate on a daily base for some of Italian municipalities. This service is used to measure the effect of the summer heat waves on the elderly population or to estimate the death tolls of the seasonal flu epidemics year after year.</p><p>Confronting the mortality rate of 2020 with the baseline (the mean mortality rate for the same period in the last years) this demographic information <em>might</em> be used to estimate the approximate death toll for some extraordinary event, like the COVID-19 epidemic. Certainly people can die for any reason. But during the epidemic we see an extreme deviance from the baseline and it seems plausible to attribute the number of deaths in excess at least in part to the disease.</p><h4>Collecting the data</h4><p>The daily mortality rate for the participating municipalities can be <a href="https://www.istat.it/it/files//2020/03/comune-giorno.zip">downloaded</a> directly from the <a href="https://www.istat.it/it/archivio/240401">dedicated webpage of ISTAT</a>. This archive contains the number of deaths per day per comune (municipality) of the first four months for the years 2015–2019 and from 1st January until 28th March for 2020, at the time of writing. If we want to calculate the divergence of the mortality rate for 2020 for a single municipality, it is rather simple to take the average number of deaths for a given day of the proceeding years (some statisticians calls this “expected mortality”) and compare it to the number of persons died the same day in 2020.</p><p>The following diagram shows the expected mortality and the actual mortality in Bergamo, one of the Italian municipalities that was hit particularly hard by the COVID-19 epidemic. We used here a 7 days moving average with a central window to smooth out the daily fluctuations in the data.</p><figure><img alt="Expected mortality and the actual mortality in Bergamo" src="https://cdn-images-1.medium.com/max/1024/1*_IQ44sMqp2b3eKF1yIGBQA.png" /><figcaption>Expected mortality and the actual mortality in Bergamo</figcaption></figure><h4>Excess mortality rate on municipality level</h4><p>The following diagrams shows the excess mortality during March 2020 in selected Italian municipalities. The blue line shows the daily expected mortality rate i.e. how many person died out of 1000 residents that day between 2015 and 2019. The 95% <a href="https://en.wikipedia.org/wiki/Confidence_interval">confidence interval</a> is shown by the light blue stripe. The orange line shows the mortality rate for the same day in 2020. The area under the curves for the month of March is filled with a diagonal pattern: the size of these areas effectively tells us how many persons died in the whole month. The difference of these numbers is the <em>excess mortality</em>, most like to be attributed to COVID-19, and the quotient of the same number is called <em>excess mortality rate</em>.</p><p>For different municipalities different “start date” was selected, i.e. when the 2020 mortality trend stepped out of the confidence interval of the previous years mortality.</p><figure><img alt="Expected and actual mortality in several municipalities of Italy" src="https://cdn-images-1.medium.com/max/1024/1*msMf4hBpvle7CtJ4B6MoXw.png" /><figcaption>Expected and actual mortality in several municipalities of Italy</figcaption></figure><p>You can have a look at the bigger figures here: <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-nembro.png">Nembro</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-albino.png">Albino</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-seriate.png">Seriate</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-codogno.png">Codogno</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-cremona.png">Cremona</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-pesaro.png">Pesaro</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-piacenza.png">Piacenza</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-tortona.png">Tortona</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-excess-pavia.png">Pavia</a> and you can download the excess mortality values and rate during March 2020 for all Italian municipalities with available data from <a href="https://github.com/mrtj/articles/blob/master/mortality-covid19/data/excess_mortality_march_2020.csv">here</a>.</p><h4>Issues of geographic aggregations</h4><p>Unfortunately the daily mortality data is available only for 1450 municipalities (out of 7904) of Italy. In these municipalities live approximately 17.04 million persons (out of 60.36 million) that corresponds to 28% of the population of Italy. The data availability varies significantly between regions, for example in Lombardy 554 municipalities (out of 1506) provide the data that corresponds to 67% of the population.</p><p>Because we do not have the mortality rate for all municipalities in a given region, we should find a way to estimate the mortality for the region. We can not simple add the number of deaths in the local municipalities with data available as it would heavily underestimate the real mortality. For the sake of simplicity (and because we do not have other data source) we will scale up the mortality data based on the quotient of the total population of the region and that one of the municipalities in the territory that provided mortality data. This way we implicitly suppose that these municipalities are representative in their region from the point of view of mortality, which is not necessarily true.</p><p>The population dataset of all Italian municipalities (as of 1st January 2019) can be <a href="http://dati.istat.it/Index.aspx?DataSetCode=DCIS_POPRES1">downloaded from ISTAT</a>. We will use this dataset to calculate the percentage of the population in the municipalities with daily mortality data available compared to the total population of the given region.</p><p>This table shows:</p><ul><li>the population of the municipalities with mortality data available for each region,</li><li>the mean and standard deviation of the mortality per 1000 persons in the municipalities, weighted by the municipality population,</li><li>and the percentage of this population to the total population of the region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05XICu1z59q79n3G6_zT3Q.png" /><figcaption>Population and mean mortality for Italian regions</figcaption></figure><p>We will consider only the regions that have at mortality data available at least for the 30% of the population. These regions are written with <em>italic font</em> in the table above.</p><p>Incidentally these are the northern regions of Italy (with the exception of Marche) that were hit most seriously by the COVID-19 epidemic.</p><h4>Number of victims officially attributed to COVID-19</h4><p>The number of deaths officially attributed to COVID-19 is available on no lower than regional level, so we will estimate the mortality rate for the regions. This dataset can be accessed from the <a href="http://github.com/pcm-dpc/COVID-19">GitHub repository</a> of the Civil Protection Department.</p><h3>Results</h3><p>The following figure shows the daily excess mortality (calculated subtracting the expected mortality from the actual mortality in 2020) and the number of deaths officially attributed to COVID-19 in March 2020, for the region of Lombardy:</p><figure><img alt="Excess mortality and official COVID-19 victims in Lombardy" src="https://cdn-images-1.medium.com/max/1024/1*qvg1oKTFHoz5t0T1nmrTKA.png" /><figcaption>Excess mortality and official COVID-19 victims in Lombardy</figcaption></figure><p>In the following table we list the estimated excess mortalities on a region level for March 2020 (since at the time of the writing official data will not be available) and compare it to the official number of COVID-19 victims.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKngonGDnh6cZPWFO_6aSw.png" /><figcaption>Estimated excess mortality rate and official COVID-19 deaths in some Italian regions</figcaption></figure><p>You can download the bigger figures from here: <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-lombardia.png">Lombardia</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-veneto.png">Veneto</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-emilia-romagna.png">Emilia-Romagna</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-piemonte.png">Piemonte</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-liguria.png">Liguria</a>, <a href="https://raw.githubusercontent.com/mrtj/articles/master/mortality-covid19/figures/mortality-covid-marche.png">Marche</a>.</p><p>It is also worth to pay attention to the “start date” in the table of the sampled municipalities. This date shows when the actual mortality stepped out from the confidence interval of the expected mortality and started to trend upwards. According to the <a href="https://www.epicentro.iss.it/coronavirus/">Italian National Institute of Health</a> the median time from the onset of symptoms to the eventual deaths is 10 days. The most commonly cited incubation period of COVID-19 is 6–7 days. Subtracting the median incubation period and duration of illness from these dates suggests that the coronavirus disease was widely spread as early as the first days of February 2020 at least in some provinces of Lombardy (for example in Bergamo, Cremona, Pesaro and Lodi). The first endemic cluster was identified only on <a href="https://en.wikipedia.org/wiki/2020_coronavirus_pandemic_in_Italy">21st February</a> in the city Codogno (province of Lodi).</p><p>Let’s have a closer look at the “date of peak” column in both tables of municipalities and regions. As we mentioned above, the first site of the epidemic onset included Codogno and surrounding municipalities. In this area the authorities immediately (the same day of 21st February) <a href="https://en.wikipedia.org/wiki/2020_Italy_coronavirus_lockdown#Initial_lockdowns">enforced a lockdown</a> effectively prohibiting the people to leave their house without serious reason. If we add to this date the median duration of 16–17 days from the infection to the eventual death, we get 8th of March which corresponds exactly to the peak of the mortality in Codogno.</p><p>On 8th March the quarantine zone was expanded to cover much of northern Italy and on the next day to the whole national territory. Approximately two weeks later, around 20–22 March the mortality in other areas started to decrease as well.</p><p>We can conclude that the two main takeaway of this analysis are:</p><ol><li>There is a huge number of excessive deaths not explained by the official figures. Most likely the number of COVID-19 victims in Italy is heavily underestimated.</li><li>The measures of lockdown imposed by the authorities, from the point of view of stopping the growth of the number of victims, were effective.</li></ol><p>Written by <a href="http://twitter.com/jtolgyesi">@jtolgyesi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6facbf0c862" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>