<?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 Srijith Rajamohan, Ph.D. on Medium]]></title>
        <description><![CDATA[Stories by Srijith Rajamohan, Ph.D. on Medium]]></description>
        <link>https://medium.com/@srijith.rajamohan?source=rss-6748d4108382------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*I2jxL6xlupJYxrWV</url>
            <title>Stories by Srijith Rajamohan, Ph.D. on Medium</title>
            <link>https://medium.com/@srijith.rajamohan?source=rss-6748d4108382------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:16:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srijith.rajamohan/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[Building domain-specific LLMs for reliable accounting solutions at Sage]]></title>
            <link>https://medium.com/sage-ai/building-domain-specific-llms-for-reliable-accounting-solutions-at-sage-f5f49479c8ad?source=rss-6748d4108382------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5f49479c8ad</guid>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Srijith Rajamohan, Ph.D.]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 12:56:55 GMT</pubDate>
            <atom:updated>2024-09-04T12:56:55.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klcicqOFlaFBo2cafnU64g.png" /></figure><p>Authors: <a href="https://medium.com/u/6748d4108382">Srijith Rajamohan, Ph.D.</a>, <a href="https://medium.com/u/bcd78e714d58">Josh Frazier</a>, <a href="https://medium.com/u/e79972c92570">Ahmed Salhin</a>, <a href="https://medium.com/u/418bd48c536f">Yu-Cheng Tsai</a>, <a href="https://medium.com/u/1cdf128a8cb2">Todd Cook</a></p><h3>Introduction</h3><p>When we started this journey almost 9 months ago, we had the collective wisdom of the <a href="https://www.sage.com/en-us/news/press-releases/2024/03/sage-transform-2024-unveils-sage-copilot/">Sage Copilot</a> team and their learnings from building LLM (Large Language Model)/RAG (Retrieval Augmented Generation) based products using OpenAI models such as GPT3.5 turbo, GPT4 etc. What the copilot team found is that these commercial LLMs worked well for a lot of scenarios, however we noted a common theme: the LLM’s failures generally seem to stem from a fundamental lack of nuanced understanding of accounting.</p><p>In order to build reliable accounting products for our customers it is critical that any LLM we use comprehend the language and nuances of accounting. It is often the case that to be effective, such an LLM often needs to have a grasp of the fundamental principles of accounting and a thorough understanding of the product. <strong>Trust is paramount to us.</strong> In the world of accounting, our customers trust us with their critical financial information and expect us to provide correct and precise information. Therefore we operate under the guiding principle that a product that provides no response is better than a product that provides an incorrect response.</p><p>Guided by this north star, we set out to train two LLMs from two open-source models to test these hypotheses. While the journey has not been without its perils, we have already deployed a general financial accounting LLM that is fine-tuned from Mistral 7B Instruct, and a second product-specific LLM is being developed using Phi-3 Medium. While we had identified a targeted use-case for this deployed model, we realized that there is significant value in making this LLM available to the rest of Sage AI for experimentation or as a drop-in replacement for their existing commercial LLM. This has already paid off with product teams recommending 3 additional use-cases for the accounting LLM .</p><p>The purpose of this post to provide an overview of our motivations, guiding principles, challenges and developments. Keep an eye on the Sage AI blog as we roll out a series of deep dives on the various several topics mentioned here.</p><h3>Why do we want an accounting LLM?</h3><p>There are 3 primary reasons why you might want something more than a commercial off-the-shelf LLM:</p><ol><li>Technical — At the risk of stating the obvious, we train an accounting-specific LLM to be better at accounting-related tasks. However, and more importantly, a local LLM does not suffer from ‘temporal stability’ often seen in many commercial LLMs. The term ‘temporal stability’ is defined here as a property of a model whereby you obtain varying outputs over multiple invocations with the same prompt + input (non-determinism in LLMs irrespective of the parameter values). Then there is the case of model behavior evolution over time that happens ostensibly when the model is updated but without a corresponding version change. The lack of predictability stemming from such behavior is very problematic when building production systems. This results in data science and engineering teams coming up with fixes only to find out that it has undone bug fixes of the past — a regression testing nightmare indeed!</li><li>Strategic — As opposed to closed-source subscription based LLMs, you have ownership and, as a result, control over the behavior of the LLM that you deploy. Features cannot be deprecated or APIs changed from under you when you least expect it, all of which has happened in the past! Additionally, this could also address data privacy concerns that some customers might raise with commercial LLMs.</li><li>Costs — This is difficult to generalize and is heavily dependent on how a deployed LLM will be utilized. Billing for commercial LLM services(such as GPT-4) are based on tokens supplied and tokens generated, however the cost of a self-hosted model is primarily based on the hourly instance cost. To make this more concrete, consider the example of an agent which might invoke an LLM multiple times in a process flow, not to mention error handling retries in the event of failures all of which can rack up the bill. Depending on your scale of operation, budgeting for your consumption can also become challenging since the spend is intrinsically tied to the behavior of the LLM consumer.</li></ol><h3>Building a production-ready LLMOps stack</h3><h4><strong>The LLMOps stack is still evolving and maturing</strong></h4><p>When we started this journey 9 months ago, we didn’t expect it to be easy, but the frenetic pace of the evolving GenAI ecosystem and the corresponding software stack meant that we had our work cut out for us. Building a production-ready LLMOps pipeline required extensive experimentation with various frameworks. We have arrived at a steady-state, with a pipeline worthy of being called a production-ready LLMOps stack. Huggingface is still the most feature-rich package with the support for most LLMs, if you are ok with slightly slower training speeds. LitGPT is fast, easy to debug and extend; our team was able to add pre-training with LoRA fairly easily. For scaling up training we use Ray with Deepspeed and we track our experiments with MLFlow. We deployed our model using the Nvidia Triton server with the vllm backend for inferencing. Safety and security of all LLM based systems were evaluated using questions from <a href="https://academy.test.io/en/articles/9353170-llm-testing-prompt-injection">Test IO</a>, <a href="https://github.com/utkusen/promptmap">promptmap</a>, and <a href="https://huggingface.co/meta-llama/Prompt-Guard-86M">Prompt-Guard-86M</a>.</p><h4><strong>Almost nothing is plug-and-play</strong></h4><p>It is easy to believe the hype that we have democratized access to GenAI. While it is true that we have the tools and infrastructure necessary; building something that delivers value to your customers is still a long journey. We have had to come up with scalable, guided data curation techniques. Data augmentation techniques exist but most struggle with factual inaccuracies of domain knowledge. When you prioritize data quality over quantity, data curation comes across as part art and part science. We carefully evaluated over a dozen open-source LLMs. While we used leaderboards as a guideline for shortlisting our candidates, we have had to build our own evaluation toolkits for model selection that measure downstream performance. While macro statistics are collected and reported, inspecting outputs tokenwise was eye-opening. We noticed a weak correlation between the rankings and those that made our list. Lastly, quantization is often touted as a way to reduce the model footprint but this is something we had to forego altogether due to that quality degradation that resulted from it. Our team had observed this in March and the recent <a href="https://arxiv.org/abs/2407.09141">MSFT paper</a> confirms our findings.</p><h4><strong>Trust is paramount to us</strong></h4><p>As previously outlined, in our line of work being unable to provide an answer is not nearly as bad as providing an incorrect answer. As a result, we seek predictable behavior or in other words: determinism from our LLMs. To make up for their deficiencies, we build systems or agents where the LLM is only one critical part of the solution. There is a suite of components in this system made up of vector stores for data and business rules, expert functions, access to external services, error handling and sometimes even a planner. The outputs of LLMs are constrained through a combination of data representation during fine-tuning and prompt engineering. Parsers are built to extract the outputs when the LLM inevitably refuses to comply with producing the outputs in the desired formats. (Constrained sampling poses a number of challenges for us). As already mentioned above, we have eschewed quantization due to the quality loss observed in an accounting context. Lastly, but most importantly, the old adage of a supervised model being only only as good as the data holds here as well. <strong>Hence, we will use credible/authoritative data on accounting knowledge and best practices from expert sources to build a knowledge base for training an accounting LLM (more to come on this).</strong></p><h3>Conclusion</h3><p>In this post, I have covered our motivations for undertaking this effort and outlined some of the many challenges we faced along the way. I would like to remind the readers to not give up hope if the journey seems daunting, but rather recalibrate the expectations about the effort required to get to your destination. If any of the topics mentioned here are of interest to you, keep an eye out on the Sage AI blog as we hope to roll out a series of deep dives and share our findings here.</p><h3>Acknowledgements</h3><p>I would be remiss if I didn’t point out that our partnership with AWS has been invaluable to our progress. We are thankful for the training/inference infrastructure of Nvidia GPUs along with the partnership credits provided by AWS for this work. Additionally, this field is still quite nascent and we would like to thank both the AWS solutions and the applied science teams for helping to address several technical hurdles in both AWS tooling and open-source LLMOps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5f49479c8ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sage-ai/building-domain-specific-llms-for-reliable-accounting-solutions-at-sage-f5f49479c8ad">Building domain-specific LLMs for reliable accounting solutions at Sage</a> was originally published in <a href="https://medium.com/sage-ai">Sage Ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Road to AGI]]></title>
            <link>https://medium.com/sage-ai/the-road-to-agi-ff9dcdb812e0?source=rss-6748d4108382------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff9dcdb812e0</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Srijith Rajamohan, Ph.D.]]></dc:creator>
            <pubDate>Tue, 02 May 2023 14:14:20 GMT</pubDate>
            <atom:updated>2023-05-02T15:53:50.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klcicqOFlaFBo2cafnU64g.png" /></figure><h3>Introduction</h3><p>This blog post aims to discuss, very succinctly, the philosophies behind the various paths of AI research leading to the holy grail of Artificial General Intelligence (AGI). The capabilities within AI can be broadly divided into three stages: Artificial Narrow Intelligence (ANI), Artificial General Intelligence (AGI), and finally, Artificial Super Intelligence (ASI) [1]. Despite the incredible recent advances in LLMs (Large Language Models), such as ChatGPT, that give the illusion of causal reasoning and intelligence, we are still firmly entrenched within the realm of ANI, with ambitions to create generalizable intelligent agents. So, what does AGI entail? The definition of AGI varies, but it is loosely defined as the ability to perform any intellectual task that a human can do. At a minimum, an agent exhibiting AGI should be able to perform reasoning and planning [2].</p><p>Can deep learning accomplish this task? In particular, can deep reinforcement learning, with its ability to plan, teach an agent to possess the required level of intelligence? If so, what would a reward system look like that incentivizes an agent to learn about the world? What is hybrid AI, and do we have the tools available to achieve it today?</p><h3>What is Intelligence?</h3><p>While human intellectual potential serves as a benchmark against which all artificial agents are measured, human-like behavior is not equivalent to intelligence. Human behavior tends to have a high degree of variance and is prone to errors and irrationality, making it difficult to assert that all human behavior is intelligent. The Turing test, although often cited and misused, is used to determine if an agent (such as ChatGPT) has achieved human-level intelligence. Furthermore, the question of whether sentience or consciousness is a necessary condition for intelligence is still debated. This topic will not be addressed in this blog post but Dr. David Chalmers explores this topic in a related talk [3], discussing whether LLMs are sentient and what it means to be sentient.</p><p>So how do we define intelligence? As mentioned above, the ability to reason is a necessary but not sufficient condition for intelligence. Human intelligence has been roughly classified into two types: crystallized intelligence and fluid intelligence [4,6]. Crystallized intelligence refers to accumulated knowledge, whereas fluid intelligence refers to the ability to process new information, apply it, and solve new problems. I hypothesize that an agent with aspirations of AGI must attain some notion of fluid intelligence. We can further break down intelligence into more tangible qualities. According to the report [5], which is not without controversy, and [2], an intelligent agent must possess the following capabilities:</p><ol><li>The ability to reason.</li><li>The ability to perform planning to accomplish a certain task.</li><li>Problem solving.</li><li>Abstract thinking.</li><li>Comprehension of complex ideas.</li><li>The ability to learn quickly and learn from experience.</li></ol><p>Planning is fundamentally what separates separates humans from other animals and other ‘intelligent’ agents. In other words, decomposing a complex problem into a sequence of steps, which often requires the capacity for abstract thinking. However, doing this well requires the ability to learn from experiences through inductive reasoning, concept formation and relationship building.</p><h3>Symbolic AI vs. Deep Learning (DL)</h3><p>The debate between symbol-based learning using propositional (think boolean logic)/higher-order logic and connectionist learning (neural networks) dates back several decades. However, recent advances in data-driven deep learning approaches have reignited this conversation in recent years. The war of words between proponents of both approaches, Dr. Yann LeCun (DL) and Dr. Gary Marcus (Symbolic AI), has been played out publicly.</p><p>Symbolic AI manipulates symbols to formulate logic and arrive at conclusions. Symbols can be a string of characters, such as a word, that has meaning embedded within it. Symbols allow us to express and exchange ideas. Chaining together symbols to communicate in this manner is called symbolic manipulation. This involves reasoning and is hence easier to formulate and interpret. For this reason, symbolic AI is also referred to as rules-based AI or an expert system. If you are interested, please see [7] for a quick summary on propositional logic needed to build symbolic reasoning systems. This is different from data-driven approaches, such as those utilized by deep learning and traditional ML. Deep learning is dependent on lots of data. However, recent advances in zero-shot and few-shot learning have helped to mitigate this issue, at least for the specific problems that the network is designed to solve.</p><p>Recently, the debate has shifted from whether symbol learning is necessary to whether symbols can be learned. In deep learning you extract patterns from data, and for supervised deep learning learn associations between inputs and outputs. In Symbolic AI, these associations are imparted to the system through rules. Dr. LeCun argues [8] that deep learning allows models to learn reasoning by being provided examples of such real-world reasoning scenarios as training data.</p><p>“<em>Since this is where Symbolic AI shines, Marcus recommends simply combining the two: Inserting a hard-coded symbolic manipulation module on top of a pattern-completion DL module. This is attractive since the two methods complement each other well, so it seems plausible a “hybrid” system with modules working in different ways would provide the best of both worlds. And it seems like common sense, since everyone working in DL agrees that symbolic manipulation is a necessary feature for creating human-like AI.</em></p><p><em>But the debate turns on whether symbolic manipulation needs to be built into the system, where the symbols and capacity for manipulating are designed by humans and installed as a module that manipulates discrete symbols and is consequently non-differentiable — and thus incompatible with DL. Underlying this is the assumption that neural networks can’t do symbolic manipulation — and, with it, a deeper assumption about how symbolic reasoning works in the brain.”</em></p><p>Dr. LeCun has been a vocal critic of autoregressive LLMs, which could explain the softening of his stance on symbol learning. He cites examples of language models such as GPT-3 and LaMDA that show some ability to engage in ‘common sense reasoning’, however, failing to do so consistently. For example, when I asked an LLM to suggest ways of implementing a hybrid AI system, the response I received was as follows:</p><p><em>The most common hybrid AI approach is the combination of rule-based AI and machine learning. Rule-based AI involves creating a set of rules and logic to solve a problem. ML, on the other hand, involves training a machine learning algorithm on a large dataset to learn patterns and make predictions.</em></p><p><em>Another approach towards hybrid AI is the combination of symbolic AI and connectionist AI. Symbolic AI involves representing knowledge using symbols and logic. Connectionist AI, on the other hand, involves creating neural network(s) that can learn from data.</em></p><p>Although they may seem like two distinct approaches to the LLM, they are essentially the same idea: a combination of a logic-based system and a machine learning/pattern learning system. This raises the question that has been repeated ad nauseam: is this intelligence or the illusion of intelligence?</p><p>However, not everyone is convinced that symbol learning needs to be a separate entity. Dr. Geoffrey Hinton argues [9] that neural networks do not need to have symbolic reasoning ingrained into them, but rather need to learn symbol manipulating behaviors [10] without an explicit symbol-learning module. And there seems to be some merit to this opinion. In [2], the improvements in reasoning and abstract thinking of GPT-4 over ChatGPT are pretty remarkable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CapL8hlLOhD-TPuJSAFLOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQRwrVIHEs_gJh2wMQABBg.png" /><figcaption>Fig 1. Reasoning and abstract thinking capabilities of ChatGPT vs. GPT-4 [2]</figcaption></figure><p>Fundamentally, the two sides seem to be at an impasse as to whether symbol learning can be learned using connectionist architectures. Even the CEO of OpenAI, which gave us ChatGPT and GPT-4, Sam Altman claims that we are at the point of diminishing returns with large models, and that we can’t scale our way to AGI [11].</p><h3>How does Intelligence arise?</h3><p>While the debate about structure and representation in learning continues, another question has garnered renewed interest: how can an intelligent agent learn from experience? This question lies at the heart of (Deep) Reinforcement Learning (RL), in which an RL agent learns the appropriate course of action to take by interacting with its environment. Each action results in a reward from the environment and the agent moving to a new state. A trajectory is defined as the sequence of states an agent traverses from start to finish. Critically, the best action at any state is the one that maximizes the return over the course of a trajectory, not the one that provides the maximum reward in that state.</p><p>Language models (LLMs), like ChatGPT, were trained using RL aided by human feedback, to help dictate the selection of tokens that make up language. The popularity of ChatGPT has led to the development of new tools such as LangChain [18], which allow us to incorporate disparate sources of knowledge to determine the ideal action given a particular state. This is not very different from how humans act. When faced with a situation where we lack sufficient knowledge, we turn to a body of knowledge to guide our decision-making. Projects such as BabyAGI [19] attempt to tackle the planning problem, which is already a step in the right direction towards achieving artificial general intelligence (AGI).</p><p>Rewards play a crucial role in how well an agent learns from experience. In fact, an entire sub-field of reward engineering is dedicated to learning how to design appropriate rewards that teach an agent the desired behavior. In fact, one could argue that RLHF (Reinforcement Learning with Human Feedback) is an extreme case of reward engineering where the rewards themselves are learned from human feedback during the training process. This leads us to a recent (controversial) paper on this topic, “Reward is Enough,” by Silver et al [12].</p><h3>Reward is enough</h3><p>In the paper “Reward is Enough” [12], the authors suggest that general algorithms, rather than problem-specific algorithms, should be formulated. These general algorithms should rely on prior expert knowledge, and all experiences and their rewards encountered along the way will result in acquired intelligence that allows one to reach various goals. This is vague enough to be indisputable but also misunderstood. As Simon Oullette [13] points out, this paper is less about the evolution of human intelligence and more about the proposed direction for future AI research.</p><p>To break down this paper, the core essence of this hypothesis is that given a particular nebulous task such as ‘get wealthy’ an agent starting from an initial state will transition through various states by making a series of decisions at each state. Initially, these decisions are likely to be less optimal but through trial and error one learns the optimal action and the learned experiences result in inductive reasoning from cause/effect and concept formation. Over time, given a new state, the agent uses the body of knowledge it has learned so that it can perform a type of ‘transfer learning’ to come up with an optimal action without having to sample and traverse many ‘trajectories’.</p><h3>Criticism of ‘Reward is enough’</h3><p>The idea of tabula rasa, or a blank slate, has received significant criticism regarding its relation to the development and evolution of human intelligence. Humans and animals are born with innate abilities necessary for survival, and are not entirely a blank slate shaped by experiences. This is a valid argument, and directly challenges the “no prior knowledge necessary” hypothesis. Another flaw with the reward hypothesis is that learning through pure exploratory sampling is not very efficient. Even with the use of efficient epsilon-greedy variants, the vastness of the space that an agent must traverse and learn through trial and error makes this problem intractable. Although reward alone could potentially lead to intelligence given infinite time and resources, it is rarely ever a pragmatic solution.</p><p>In “The Archimedean Trap: Why traditional reinforcement learning will probably not yield AGI” [14] Dr. Samuel Allen Alexander argues that scalar rewards based on real numbers are insufficient to attain AGI because most real-world scenarios follow a non-Archimedean reward structure. In other words, we cannot quantify the value of a particular state in non-infinite terms. Rewards need to be infinitesimally small (to avoid a state) or large (to attain a state) to represent the relative values of states. For example, during the course of medical treatment, the state of death must be avoided at all costs. How does one quantify this with a real-numbered reward? One could hypothesize that a finitely large value could suffice in a finite horizon RL problem, but Alexander is not convinced. He does concede that non-traditional RL techniques, such as preference-based reward systems, could potentially sidestep this deficit. Additionally, recent work in RLHF (Reinforcement Learning with Human Feedback) and the success of ChatGPT have solved such issues with reward engineering, training a model to learn a reward from relative preferences provided as feedback.</p><p>In “Scalar reward is not enough: A response to Silver, Singh, Precup and Sutton (2021)” [15] Vamplew et al. argue that a scalar reward is insufficient for learning all forms of intelligence necessary to achieve a goal. They also address a concern raised by others: while this approach could lead to the evolution of intelligence, it may still be undesirable as the sole criterion because it lacks safeguards to limit unethical behavior. Just because you can do something does not mean you should. In maximizing an objective like “get wealthy,” how can a scalar reward account for ethical considerations and de-incentivize immoral actions?</p><h3>A hybrid approach?</h3><p>Is a hybrid approach really the way forward towards achieving true AGI? There have been various advances in fusing together the techniques of symbolic learning and deep learning. Any such hybrid system should have reasoning abilities as well as the ability to assess similarity. Dr. Gary Marcus believes that combining neurosymbolic learning with the exploratory-exploitative nature of deep reinforcement learning could get us there [16].</p><p>This could potentially address the fundamental challenges of reasoning and transferable learning. The rigidity of the symbolic approach has been criticized as has been the inability to reason in deep learning. Symbolic systems suffer from an inability to deal with heuristic and fuzzy relationships, while deep learning excels at this. On the other hand, deep learning suffers from explainability and the lack of reasoning capabilities.</p><p>However, this debate is moot according to Dr. Marvin Minsky [17], who believed that AI should not be constrained by a particular type of system and true intelligence stems from a diverse set of components. It has been postulated that even the human brain consists of a series of specialized agencies that perform a set of functions really well. They do not necessarily need to cooperate to solve new challenges, but they do need to exploit each other’s expertise. For further reading on the topic of symbolic vs. connectionist approaches, you can refer to [17].</p><p>One could argue that many industrial applications, particularly those with regulatory standards, already utilize a hybrid AI approach in principle, where business rules are combined with learned models.</p><h3>What could such a hybrid system look like?</h3><p>The simplest form of neurosymbolic AI is based on propositional logic or zeroth order logic using logical connective operators. Propositional logic is also more commonly referred to as boolean logic. First-order logic extends propositional logic by allowing us to establish relationships between objects.</p><p>Scallop [20] is a framework that attempts to bridge the gap between logical/symbolic reasoning and deep learning. What distinguishes Scallop from prior symbolic reasoning packages is its focus on approximate solutions for efficiency, rather than exact probabilistic reasoning. A python binding is available so that Scallop can be imported as a module. Let’s look at an example of Scallop performing relation extraction from a passage. Concepts are encoded as rules as shown below.</p><pre># fact - Jane is mother to John<br>rel mother = {(”Jane”, “John”)}<br><br># fact - Jonah is father to Jane<br>rel father = {(”Jonah”, “Jane”)}<br><br># This is a rule<br>rel grandfather(a,b) = father(a,c) and mother(c, b)<br><br>rel person = {”Jane”, “John”, “Jonah”}<br>rel has_no_children(a) = person(a) and ~father(a, _) and ~mother(a, _)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZK7cKo5sdaLIkwHXqJzihA.png" /><figcaption>Fig 2. Relationship extraction [20]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTPd-kxfOwm8rZVmWzarcQ.png" /><figcaption>Fig. 3 Inferring relationships from text [20]</figcaption></figure><p>The possibilities are virtually endless with such a system, but is this the right path to general intelligence? We have come quite far with deep learning and specifically Generative AI, specifically in vision and language. But do we need a paradigm shift to get to AGI? Let me know what you think…</p><h3>References</h3><ol><li>Rise of the machines: artificial intelligence and the clinical laboratory</li><li><a href="https://arxiv.org/abs/2303.12712">Sparks of Artificial General Intelligence: Early experiments with GPT-4</a></li><li><a href="https://www.youtube.com/watch?v=-BcuCmf00_Y&amp;themeRefresh=1">David Chalmers “Are Large Language Models Sentient?”</a></li><li><a href="https://en.wikipedia.org/wiki/Fluid_and_crystallized_intelligence">https://en.wikipedia.org/wiki/Fluid_and_crystallized_intelligence</a></li><li>GottfredsonL. “Mainstream science on intelligence: an editorial with 52 signatories, history, and bibliography”</li><li><a href="https://psycnet.apa.org/record/1963-07991-001?doi=1">Theory of fluid and crystallized intelligence: A critical experiment</a></li><li><a href="https://www.cs.cmu.edu/~emc/15414-f12/lecture/propositional_logic.pdf">Notes on Propostitional Logic</a></li><li><a href="https://www.noemamag.com/what-ai-can-tell-us-about-intelligence/">https://www.noemamag.com/what-ai-can-tell-us-about-intelligence/</a></li><li><a href="https://www.technologyreview.com/2020/11/03/1011616/ai-godfather-geoffrey-hinton-deep-learning-will-do-everything/">AI pioneer Geoff Hinton: “Deep learning is going to be able to do everything”</a></li><li><a href="https://arxiv.org/abs/2102.03406">Symbolic Behaviour in Artificial Intelligence</a></li><li><a href="https://www.wired.com/story/openai-ceo-sam-altman-the-age-of-giant-ai-models-is-already-over/">https://www.wired.com/story/openai-ceo-sam-altman-the-age-of-giant-ai-models-is-already-over/</a></li><li><a href="https://www.sciencedirect.com/science/article/pii/S0004370221000862">Reward is enough</a></li><li><a href="https://www.linkedin.com/pulse/reward-enough-efficient-simon-ouellette/">https://www.linkedin.com/pulse/reward-enough-efficient-simon-ouellette/</a></li><li><a href="https://arxiv.org/pdf/2002.10221.pdf">The Archimedean trap: Why traditional reinforcement learning will probably not yield AGI</a></li><li><a href="https://arxiv.org/pdf/2112.15422.pdf">Scalar reward is not enough: A response to Silver, Singh, Precup and Sutton (2021)</a></li><li><a href="https://www.noemamag.com/deep-learning-alone-isnt-getting-us-to-human-like-ai/">https://www.noemamag.com/deep-learning-alone-isnt-getting-us-to-human-like-ai/</a></li><li><a href="https://web.media.mit.edu/~minsky/papers/SymbolicVs.Connectionist.html">https://web.media.mit.edu/~minsky/papers/SymbolicVs.Connectionist.html</a></li><li><a href="https://github.com/hwchase17/langchain">https://github.com/hwchase17/langchain</a></li><li><a href="https://github.com/yoheinakajima/babyagi">https://github.com/yoheinakajima/babyagi</a></li><li><a href="https://drive.google.com/file/d/17En24U05P9FG4V9LmJ4tMqrVNzHh6atx/view">https://drive.google.com/file/d/17En24U05P9FG4V9LmJ4tMqrVNzHh6atx/view</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff9dcdb812e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sage-ai/the-road-to-agi-ff9dcdb812e0">The Road to AGI</a> was originally published in <a href="https://medium.com/sage-ai">Sage Ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Bayesian Hierarchical Models in PyMC3 to Infer the Disease Parameters of COVID-19]]></title>
            <link>https://medium.com/data-science/using-bayesian-hierarchical-models-in-pymc3-to-infer-the-disease-parameters-of-covid-19-b396c8b9845?source=rss-6748d4108382------2</link>
            <guid isPermaLink="false">https://medium.com/p/b396c8b9845</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[bayesian]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pymc3]]></category>
            <dc:creator><![CDATA[Srijith Rajamohan, Ph.D.]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 00:21:55 GMT</pubDate>
            <atom:updated>2021-10-06T13:27:36.400Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we look at how to use PyMC3 to infer the disease parameters for COVID-19. PyMC3 is a popular probabilistic programming framework that is used for Bayesian modeling. Two popular methods to accomplish this are the Markov Chain Monte Carlo (<a href="https://reference.wolfram.com/language/howto/PerformAMonteCarloSimulation.html">MCMC</a>) and <a href="https://reference.wolfram.com/language/VariationalMethods/tutorial/VariationalMethods.html">Variational Inference</a> methods. The work here looks at using the currently available data for the infected cases in the United States as a time-series and attempts to model this using a compartmental probabilistic model. We want to try to infer the disease parameters and eventually estimate <em>R0</em> using MCMC sampling. We will then explore how to do the same using Bayesian hierarchical models and the benefits compared to a pooled or an unpooled model. We conclude with the limitations of this model and outline the steps for improving the inference process.</p><p>The work presented here is for illustration purposes only and real-life Bayesian modeling requires far more sophisticated tools than what is shown here. Various assumptions regarding population dynamics are made here, which may not be valid for large non-homogeneous populations. Also, interventions such as social distancing and vaccinations are not considered here.</p><p>This post will cover the following:</p><ol><li>Compartmental models for Epidemics</li><li>Where the data comes from and how it is ingested</li><li>The SIR/SIRS models for disease dynamics</li><li>Bayesian Inference for ODEs with PyMC3</li><li>Extension of the work with hierarchical models</li><li>Guidelines and debugging tips for probabilistic programming</li></ol><p>I have also launched a series of courses on Coursera covering this topic of Bayesian modeling and inference, courses 2 and 3 are particularly relevant to this post. Check them out at: <a href="https://www.coursera.org/specializations/compstats">https://www.coursera.org/specializations/compstats</a> .</p><h3>Compartmental Models for Epidemics</h3><p>For an overview of compartmental models and their behavior, please refer to this notebook in Julia <a href="https://github.com/sjster/Epidemic.">— https://github.com/sjster/Epidemic.</a></p><p>Compartmental models are a set of Ordinary Differential Equations (ODEs) for closed populations, which imply that there is no movement of the population in or out of this compartment. These aim to model disease propagation in compartments of populations that are homogeneous. As you can imagine, these assumptions may not be valid in large populations. It is also important to point out here that vital statistics such as the number of births and deaths in the population may not be included in this model. The following list mentions some of the compartmental models along with the various compartments of disease propagation, however, this is not an exhaustive list by any means.</p><ul><li>Susceptible Infected (SI)</li><li>Susceptible Infected Recovered (SIR)</li><li>Susceptible Infected Susceptible (SIS)</li><li>Susceptible Infected Recovered Susceptible (SIRS)</li><li>Susceptible Infected Recovered Dead (SIRD)</li><li>Susceptible Exposed Infected Recovered (SEIR)</li><li>Susceptible Exposed Infected Recovered Susceptible (SEIRS)</li><li>Susceptible Exposed Infected Recovered Dead (SEIRD)</li><li>Maternally-derived Immunity Susceptible Infectious Recovered (MSIR)</li><li>SIDARTHE (<a href="https://www.nature.com/articles/s41591-020-0883-7">https://www.nature.com/articles/s41591-020-0883-7</a>)</li></ul><p>The last one listed above is more recent and specifically targets COVID-19 and maybe worth a read for those interested. Real-world disease modeling often involves more than just the temporal evolution of disease stages since many of the assumptions associated with compartments are violated. To understand how the disease propagates, we would want to look at the spatial discretization and evolution of the progression of the disease through the population. An example of a framework that models this spatio-temporal evolution is GLEAM (Fig.1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*8U6Vii30df4rxsum" /></figure><p>​ Fig. 1- Real-world epidemic modeling (spatio-temporal dynamics).</p><p>Tools such as GLEAM use the population census data and the mobility patterns to understand how people move geographically. GLEAM divides the globe into spatial grids of roughly 25km x 25km. There are broadly two types of mobility: global or long-range mobility and local or short-range mobility. Long-term mobility mostly involves air travel and as such airports are considered a central hub for disease transmission. Travel by sea is also another significant factor and therefore naval ports are another type of access point. Along with the mathematical models listed above, this provides a stochastic framework that can be used to make millions of simulations to draw inferences about parameters and make forecasts.</p><h3>COVID-19 data</h3><p>The data used here is obtained from the Johns Hopkins CSSE Github page where case counts are regularly updated:</p><p><a href="https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series">CSSE GitHub</a></p><p><a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv">Confirmed cases</a></p><p><a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv">Number of deaths</a></p><p>The data is available as CSV files which can be read in through Python pandas.</p><h3>The SIR and SIRS models</h3><h4>SIR Model</h4><p>The SIR model is given by the set of three Ordinary Differential Equations (ODEs) shown below. There are three compartments in this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/0*vmg_ECDYu_7veTb1" /></figure><p>Here ‘S’, ‘I’ and ‘R’ refer to the susceptible, infected and recovered portions of the population of size ’N’ such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/0*-DveUVqJ2wP-saCW" /></figure><p>The assumption here is that once you have recovered from the disease, lifetime immunity is conferred on an individual. This is not the case for a lot of diseases and hence may not be a valid model.</p><p>λ is the rate of infection and μ is the rate of recovery from the disease. The fraction of people who recover from the infection is given by ‘f’ but for the purpose of this work, ‘f’ is set to 1 here. We end up with an Initial Value Problem (IVP) for our set of ODEs where I(0) is assumed to be known from the case counts at the beginning of the pandemic and S(0) can be estimated as N — I(0). Here we make the assumption that the entire population is susceptible. Our goal is to accomplish the following:</p><ul><li>Use Bayesian Inference to make estimates about λ and μ</li><li>Use the above parameters to estimate I(t) for any time ‘t’</li><li>Compute <em>R0</em></li></ul><p>As already pointed out, λ is the disease transmission coefficient. This depends on the number of interactions, in unit time, with infectious people. This in turn depends on the number of infectious people in the population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*ytffiSqBMYYGO_Vf" /></figure><p>The force of infection or risk at any time ‘t’ is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/37/0*q_oMfYrqwXDlX8nw" /></figure><p>Also, μ is the fraction of recovery that happens in unit time. The inverse of μ is hence the mean recovery time. The ‘basic reproduction number’ <em>R0</em> is the average number of secondary cases produced by a single primary case (Examples <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6002118/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6002118/</a>). <em>R0</em> is also defined in terms of the λ and μ as the ratio given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/0*NGbje-UfrCWId-sO" /></figure><p>The above assumes that <em>S0</em> is close to 1. When <em>R0&gt;1</em>, we have a proliferation of the disease and we have a pandemic. With the recent efforts to vaccinate the vulnerable, this has become even more relevant to understand. <strong>If we vaccinate a fraction ‘p’ of the population to get <em>(1−p)R0&lt;1</em>, we can halt the spread of the disease.</strong></p><h4>SIRS Model</h4><p>The SIRS model, shown below, makes no assumption of lifetime immunity once an infected person has recovered. Therefore, one goes from the recovered compartment to the susceptible compartment. As such, this is probably a better low-fidelity baseline model for COVID-19 where it is suggested that the acquired immunity is short-term. The only additional parameter here is γ which refers to the rate at which immunity is lost and the infected individual moves from the recovered pool to the susceptible pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*X2v31PqHURmWc5r8" /></figure><p>For this work, only the SIR model is implemented, and the SIRS model and its variants are left for future work.</p><h3>Using PyMC3 to Infer the Disease Parameters</h3><p>We can discretize the SIR model using a first-order or a second-order temporal differentiation scheme which can then be passed to PyMC3 which will march the solution forward in time using these discretized equations. The parameters λ and μ can then be fitted using the Monte Carlo sampling procedure.</p><h4>First-order scheme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*hphRZ0a5OMhvADPj" /></figure><h4>Second-order scheme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*dl5vxTEdffI7_QPV" /></figure><h4>The DifferentialEquation Method in PyMC3</h4><p>While we can provide the discretization manually with our choice of a higher-order discretization scheme, this quickly becomes cumbersome and error-prone not to mention computationally inefficient in a language like Python. Fortunately, PyMC3 has an ODE module to accomplish this. We can use the DifferentialEquation method from the ODE module which takes as input a function that returns the value of the set of ODEs as a vector, the time steps where the solution is desired, the number of states corresponding to the number of equations and the number of variables we would like to have solved. Even though this is still faster than manual discretization, this method scales poorly with problem size. The recommended best practice is to use the ‘sunode’ module (see below) in PyMC3. For example, the same problem took 5.4 mins using DifferentialEquations vs. 16s with sunode for 100 samples,100 tuning samples and 20 time points.</p><pre>self.sir_model_non_normalized = DifferentialEquation(<br>   func = self.SIR_non_normalized,<br>   times = self.time_range1:],<br>   n_states = 2,<br>   n_theta = 2,<br>   t0 = 0)</pre><pre>def SIR_non_normalized(self, y, t, p):<br>   ds = -p[0] * y[0] * y[1] / self.covid_data.N,<br>   di = p[0] * y[0] * y[1] / self.covid_data.N — p[1] * y[1]<br>   return[ds, di]</pre><p>The syntax for using the sunode module is shown below. While there are some syntactic differences, the general structure is the same as that of DifferentialEquations.</p><pre>import sunode<br>import sunode.wrappers.as_theano</pre><pre>def SIR_sunode(t, y, p):<br>  return { ‘S’: -p.lam * y.S * y.I,<br>  ‘I’: p.lam * y.S * y.I — p.mu * y.I}</pre><pre>…</pre><pre>…</pre><pre>sir_curves, _, problem, solver, _, _ =       <br>   sunode.wrappers.as_theano.solve_ivp(<br>   y0={ # Initial conditions of the ODE<br>   ‘S’: (S_init, ()),<br>   ‘I’: (I_init, ()),},<br>   params={<br>      # Parameters of the ODE, specify shape<br>     ‘lam’: (lam, ()),<br>     ‘mu’: (mu, ()),<br>     ‘_dummy’: (np.array(1.), ())} # currently, sunode throws an error, without this</pre><pre>   # RHS of the ODE<br>   rhs=SIR_sunode,<br>   # Time points of th solution<br>   tvals=times,<br>   t0=times[0],)</pre><h4>The Inference Process for an SIR Model</h4><p>In order to perform inference on the parameters we seek, we start by selecting reasonable priors for the disease parameters. Based on our understanding of the behavior of the disease phenomenon, a lognormal distribution is a reasonable prior for the disease parameters. Ideally, we want the mean parameter of this lognormal to be in the neighborhood of what we expect the desired parameters to reside. For good convergence and solutions, it is also essential that the data likelihood is appropriate (domain expertise!). It is common to pick one of the following as the likelihood.</p><ul><li>Normal distribution</li><li>Lognormal distribution</li><li>Student’s t-distribution</li></ul><p>We obtain the Susceptible (S(t)) and Infectious (I(t)) numbers from the ODE solver and then sample for values of λ and μ as shown below.</p><pre>with pm.Model() as model4:</pre><pre>   sigma = pm.HalfCauchy(‘sigma’, self.likelihood[‘sigma’], shape=1)</pre><pre>   lam = pm.Lognormal(‘lambda’, self.prior[‘lam’], self.prior[‘lambda_std’]) # 1.5, 1.5</pre><pre>   mu = pm.Lognormal(‘mu’, self.prior[‘mu’], self.prior[‘mu_std’])</pre><pre>   res, _, problem, solver, _, _ = sunode.wrappers.as_theano.solve_ivp(<br>   y0={‘S’: (self.S_init, ()), ‘I’: (self.I_init, ()),},<br>   params={‘lam’: (lam, ()), ‘mu’: (mu, ()), ‘_dummy’: (np.array(1.), ())},<br>   rhs=self.SIR_sunode,<br>   tvals=self.time_range,<br>   t0=self.time_range[0])</pre><pre>   # likelihood distribution mean, these are the predictions from the SIR model ODE solver</pre><pre>   if(likelihood[‘distribution’] == ‘lognormal’):</pre><pre>       I = pm.Lognormal(‘I’, mu=res[‘I’], sigma=sigma, observed=self.cases_obs_scaled)</pre><pre>   elif(likelihood[‘distribution’] == ‘normal’):</pre><pre>       I = pm.Normal(‘I’, mu=res[‘I’], sigma=sigma, observed=self.cases_obs_scaled)</pre><pre>   elif(likelihood[‘distribution’] == ‘students-t’):</pre><pre>       I = pm.StudentT( “I”, nu=likelihood[‘nu’], \<br>       mu=res[‘I’], <br>       sigma=sigma,<br>       observed=self.cases_obs_scaled)</pre><pre>   R0 = pm.Deterministic(‘R0’,lam/mu)</pre><pre>   trace = pm.sample(self.n_samples, tune=self.n_tune, chains=4, cores=4)</pre><pre>   data = az.from_pymc3(trace=trace)</pre><h3>The Inference Workflow with PyMC3</h3><p>Since developing a model such as this, for estimating the disease parameters using Bayesian inference, is an iterative process we would like to automate away as much as possible. It is probably a good idea to instantiate a class of model objects with various parameters and have automated runs. It is also a good idea to save the trace information, inference metrics such as R̂ (R-hat) along with other metadata information for each run. A file format such as NetCDF can be used for this although it could be as simple as using the Python built-in database module ‘shelve’. The classes for data extraction are not shown here, but their invocations are shown so that you get a sense for the data and the model parameters used here.</p><pre>covid_obj = COVID_data(‘US’, Population=328.2e6)</pre><pre>covid_obj.get_dates(data_begin=’10/1/20&#39;, data_end=’10/28/20&#39;)</pre><pre>sir_model = SIR_model_sunode(covid_obj)</pre><pre>likelihood = {‘distribution’: ‘normal’, ‘sigma’: 2}</pre><pre>prior = {‘lam’: 1.5,‘mu’: 1.5, ‘lambda_std’: 1.5, ‘mu_std’: 1.5 }</pre><pre>sir_model.run_SIR_model(n_samples=500, n_tune=500, likelihood=likelihood, prior=prior)</pre><p>These results are purely for illustration purposes and extensive experimentation is needed before meaningful results can be expected from this simulation. The case count for the United States from January to October is shown below (Fig 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wxZ7ElSC3aocMGzC" /></figure><p>Fig. 2 - Example COVID-19 case count visualization for the US</p><p>Fig. 3 shows the results of an inference run where the posterior distributions of λ, μ and <em>R0</em> are displayed. One of the advantages of performing Bayesian inference is that the distributions show the mean value estimate along with the Highest Density Interval (HDI) for quantifying uncertainty. It is a good idea to check the trace (at the very least!) to ensure sampling was done properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*lHo2DQQWjUrHMGk3" /></figure><p>​ Fig. 3 - Example results of an inference run displaying the Highest Density Interval (HDI) using PyMC3.</p><h3>Pooled, unpooled and hierarchical models</h3><p>Suppose you have information regarding the number of infections from various states in the United States. One way to use this data to infer the disease parameters of COVID-19 (e.g. <em>R0) </em>is to sum it all up to estimate a single parameter. This is called a <em>pooled model</em>. However, the problem with this approach is that fine-grained information that might be contained in these individual states or groups is lost. The other extreme would be to estimate an individual parameter <em>R0 </em>per state. This approach results in an <em>unpooled model</em>. However, considering that we are trying to estimate the parameters corresponding to the same virus, there has to be a way to perform this collectively, which brings us to the <em>hierarchical model</em>. This is particularly useful when there isn’t sufficient information in certain states to create accurate estimates. Hierarchical models allow us to share the information from other states using a shared ‘hyperprior’. Let us look at this formulation in more detail using the example for :</p><p>For a pooled model, we can draw from a single distribution with fixed parameters λ_μ, λ_σ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/0*yb39dle6bY0c0qYL" /></figure><p>For an unpooled model, we can draw λᵢ for each state from distributions with fixed parameters λ_μᵢ, λ_σᵢ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*FrN3oqUL8HdO0ppl" /></figure><p>For a hierarchical model, we have a prior that is parameterized by non-constant parameters drawn from other distributions. Here, we draw a λ value for each state, however they are connected through shared hyperprior distributions (with constant parameters) as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/0*voePPeerx6T8dTzR" /></figure><p>Check out course 3 <em>Introduction to PyMC3 for Bayesian Modeling and Inference</em> (<a href="https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats">https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats</a>) in the recently-launched Coursera specialization for more details on hierarchical models.</p><h3>COVID-19 data for hierarchical models</h3><p>Here we plot and use the case count of infections-per-day for two countries, the United States and Brazil. However, there is no limitation on either the choice or number of countries that can be used in a hierarchical model. The cases below are from Mar 1, 2020 to Jan 1, 2021. The graphs seem to follow a similar trajectory, even though the scales on the <em>y-axis</em> are different for these countries. Considering that these cases are from the same COVID-19 virus, this is reasonable. However, in a realistic scenario there are differences to account for, such as the different variants, different geographical structures and social distancing rules, healthcare infrastructure and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X6oqUgiB0TQHPB-y" /></figure><p>Fig. 4 - Plot of the number of COVID-19 cases for two countries</p><h3>Inference of parameters</h3><p>For a hierarchical model, the code snippet to perform the inference of the disease parameters is given below.</p><pre>with pm.Model() as model4:</pre><pre>   # narrow std is roughly equivalent to a constant prior parameter,  if there are issues with sampling from the prior distribution<br>   # make the variance of the mean smaller. Variance of the distribution of the variance parameter seems less relevant in this regard.</pre><pre>   nsamples = 8000 </pre><pre>   ntune = 4000</pre><pre>   Hyperprior = {“Lambda mean”: 0.75, “Lambda std”: 2, “Mu mean”: 0.75, “Mu std”: 2}</pre><pre>   Prior = {“Lambda std”: 1.0, “Mu std”: 1.0}</pre><pre>   Likelihood = {“Name”: “Normal”, “Parameters”: {“std”: 0.01}}</pre><pre>   prior_lam = pm.Lognormal(‘prior_lam’, Hyperprior[‘Lambda mean’], Hyperprior[‘Lambda std’])</pre><pre>   prior_mu = pm.Lognormal(‘prior_mu’, Hyperprior[‘Mu mean’], Hyperprior[‘Mu std’])</pre><pre>   prior_lam_std = pm.HalfNormal(‘prior_lam_std’, Prior[‘Lambda std’])</pre><pre>   prior_mu_std = pm.HalfNormal(‘prior_mu_std’, Prior[‘Mu std’])</pre><pre>   lam = pm.Lognormal(‘lambda’, prior_lam , prior_lam_std, shape=2)</pre><pre>   mu = pm.Lognormal(‘mu’, prior_mu , prior_mu_std, shape=2)</pre><pre>   # — — — — — — — — — — ODE model — — — — — — — — #</pre><pre>   res, _, problem, solver, _, _ = sunode.wrappers.as_theano.solve_ivp(<br>   y0={ ‘S’: (S_init, (2,)), ‘I’: (I_init, (2,)),},<br>   params={‘lam’: (lam, (2,)), ‘mu’: (mu, (2,)), ‘_dummy’: (np.array(1.), ())},<br>   rhs=SIR_sunode,<br>   tvals=time_range[1:],<br>   t0=time_range[0])</pre><pre>   I = pm.Normal(‘I’, mu=res[‘I’], sigma=Likelihood[‘Parameters’][‘std’], observed=cases_obs_scaled[1:])</pre><pre>   R0 = pm.Deterministic(‘R0’,lam/mu)</pre><pre>   # if you increase the variance and the distributions looks choppy, increase the tuning sample size to sample the space more effectively<br>   # also, increase the total number of samples</pre><pre>  trace = pm.sample(nsamples, tune=ntune, chains=8, cores=8)</pre><pre>  data = az.from_pymc3(trace=trace)</pre><p>The sampled posterior distributions are shown below, along with their 94% Highest Density Interval (HDI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jZZ3iUno8kg0ev7K" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OF7ZN4cS7r52W9MV" /></figure><p>Fig. 5 - The sampled posterior distributions along with their 94% Highest Density Interval (HDI).</p><p>We can also inspect the traceplots for convergence, which shows good mixing in all the variables — a good sign that the sampler has explored the space well. There is good agreement between all the traces. This behavior can be confirmed with the fairly narrow HDI intervals in the plots above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*94yljDESp_2RSh7F" /></figure><p>Fig. 6 - The traceplots and density plots for R0 and other variables</p><p>The table below summarizes the distributions of the various inferred variables and parameters, along with the sampler statistics. While estimates about the variables are essential, this table is particularly useful for informing us about the quality and efficiency of the sampler. For example, the R-hat is all close to or equal to 1.0, indicating good agreement between all the chains. The effective sample size is another critical metric. If this is small compared to the total number of samples, that is a sure sign of trouble with the sampler. Even if the R-hat values look good, be sure to inspect the effective sample size!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3l8_aWsjvwEDwBzH" /></figure><p>Fig. 7 - Table of the inferred variable distributions along with the sampling statistics</p><h3>Notes and Guidelines</h3><p>Some general guidelines for modeling and inference:</p><ul><li>Use at least 5000 samples and 1000 samples for tuning.</li><li>For the results shown above, I have used: Mean: λ= 1.5, = 1.5, Standard deviation: 2.0 for both parameters. A domain expert and his knowledge is invaluable in setting these parameters.</li><li>Sample from 3 chains at least.</li><li>Set <strong>target_accept</strong> to &gt; 0.85 (depends on the sampling algorithm).</li><li>If possible, sample in parallel with <strong>cores=n</strong>, where ’n’ is the number of cores available.</li><li>Inspect the trace for convergence.</li><li>Limited time-samples have an impact on inference accuracy, it is always better to have more good quality data.</li><li>Normalize your data, large values are generally not good for convergence</li></ul><h4>Debugging your model</h4><ul><li>Since the backend for PyMC3 is theano, the Python print statement cannot be used to inspect the value of a variable. Use <strong>theano.printing.Print(DESCRIPTIVE_STRING)(VAR)</strong> to accomplish this.</li><li>Initialize stochastic variables by passing a ‘testval’. This is very helpful to check those pesky ‘Bad Energy’ errors, which are usually due to poor choice of likelihoods or priors. Use <strong>Model.check_test_point()</strong> to verify this.</li><li>Use <strong>step = pm.Metropolis()</strong> for quick debugging, this runs much faster but results in a rougher posterior.</li><li>If the sampling is slow, check your prior and likelihood distributions.</li><li>A narrow sigma value for a prior distribution can be used to simulate a constant prior and can help debug issues with sampling from the prior distribution.</li><li>If increasing the variance results in a choppy posterior distribution, increase both the tuning sample size and the number of samples to sample the space more effectively.</li></ul><h3>Future work</h3><p>Although this yielded satisfactory estimates for our parameters, often we run into the issue of the sampler not performing effectively. For future work, there are a few ways to diagnose and improve the modeling process. These are listed, in increasing order of difficulty, below:</p><ol><li>Increase the tuning size and the number of samples drawn.</li><li>Decrease the target_accept parameter for the sampler so as to reduce the autocorrelation among the samples. Use the autocorrelation plot to confirm this.</li><li>Add more samples to the observed data, i.e. increase the sample frequency.</li><li>Use better priors and hyperpriors for the parameters.</li><li>Use an alternative parameterization of the model.</li><li>Incorporate changes such as social-distancing measures into the model.</li></ol><h4>LEARN MORE</h4><p>You can learn more about these topics at my Coursera specialization (<a href="https://www.coursera.org/specializations/compstats">https://www.coursera.org/specializations/compstats</a>) that consists of the following courses:</p><ol><li>Introduction to Bayesian Statistics (<a href="https://www.coursera.org/learn/compstatsintro?specialization=compstats">https://www.coursera.org/learn/compstatsintro?specialization=compstats</a>)</li><li>Bayesian Inference with MCMC (<a href="https://www.coursera.org/learn/mcmc?specialization=compstats">https://www.coursera.org/learn/mcmc?specialization=compstats</a>)</li><li>Introduction to PyMC3 for Bayesian Modeling and Inference (<a href="https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats">https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats</a>)</li></ol><h3>References</h3><ol><li>The work by the Priesemann Group</li></ol><p><a href="https://github.com/Priesemann-Group/covid_bayesian_mcmc">GitHub - Priesemann-Group/covid_bayesian_mcmc: Bayesian Markov Chain Monte Carlo Forecast for COVID-19</a></p><p>2. Work by Demetri Pananos on the PyMC3 website</p><p><a href="https://docs.pymc.io/notebooks/ODE_API_introduction.html">GSoC 2019: Introduction of pymc3.ode API - PyMC3 3.10.0 documentation</a></p><p>3. Sunode</p><p><a href="https://github.com/aseyboldt/sunode">GitHub - aseyboldt/sunode: Solve ODEs fast, with support for PyMC3</a></p><p>4. GLEAM</p><p><a href="http://www.gleamviz.org/">http://www.gleamviz.org</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b396c8b9845" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-bayesian-hierarchical-models-in-pymc3-to-infer-the-disease-parameters-of-covid-19-b396c8b9845">Using Bayesian Hierarchical Models in PyMC3 to Infer the Disease Parameters of COVID-19</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>