<?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 Fraser Lewis on Medium]]></title>
        <description><![CDATA[Stories by Fraser Lewis on Medium]]></description>
        <link>https://medium.com/@fraser-lewis?source=rss-6ee15ec3d4fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yHmULf7t_IU1j-UTfUxxTQ.jpeg</url>
            <title>Stories by Fraser Lewis on Medium</title>
            <link>https://medium.com/@fraser-lewis?source=rss-6ee15ec3d4fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:31:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fraser-lewis/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 bespoke stochastic process models using Rcpp]]></title>
            <link>https://medium.com/data-science/building-bespoke-stochastic-process-models-using-rcpp-49dae153c34a?source=rss-6ee15ec3d4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/49dae153c34a</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Fraser Lewis]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 19:52:32 GMT</pubDate>
            <atom:updated>2022-01-04T22:09:55.901Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h3>Modeling Biological Systems in Time and Space</h3><h4>Advanced model building in R with Rcpp</h4><h4>The scientific literature contains a vast “zoo” of elegant mathematical models for analyzing complex biological systems. Implementing them in R or Python can lead to some interesting, or indeed unexpected, numerical challenges.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*hENiklk-DIyxGnoGliH3-Q.png" /><figcaption>Fig1. Spatial (1-D) logistic growth model estimated using Rcpp. Original application was for advantageous alleles spreading spatially across a landscape due to R. A. Fisher (in 1937) (see main text for details). Image by author.</figcaption></figure><h3>1. The Malthusian growth model (1798) and friends</h3><p>Modeling complex biological systems has a long history. An exponential population growth model was presented in 1798 (<a href="https://en.wikipedia.org/wiki/Malthusian_growth_model">Malthusian growth</a>), with many historically famous scientists adding their own models to the literature, and which of course continues today. These models cover everything from hereditary and genetic evolution — Fisher and his model for <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1207813/pdf/ge1452493.pdf">waves of advantageous alleles</a> in 1937 — to models of the spread of infectious diseases (too numerous to mention, see COVID-19 literature), through to contributions only made possible by the most recent advances in technology, e.g., genome sequencing technologies enabling the development of <a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1007917">predator-prey models of microbial populations</a> in humans.</p><p>Many of these models are mathematically elegant and form concise descriptions of highly complex processes and typically focus on a small number of key parameters or features. What is impressive is how often “classical” models (perhaps with a slight modification) are still used today in real applications. This suggests that such models continue to capture the essence of the complex biological systems which surround us today — at least as we currently understand them. For example, even models as seemingly simple as logistic growth, which dates from around 1838 (discovered by <a href="https://en.wikipedia.org/wiki/Logistic_function">Verhulst</a>), frequently appear in recent (2020) peer reviewed scientific journal articles on the spread of COVID-19.</p><p>Before we progress to the real content of this article a quick remark on the use of “Advanced model building” in the subtitle. The models used in the following examples require some bespoke numerical implementation, which arguably makes this less a beginner topic. That said, none of the coding or mathematics is advanced and all the code for running the models and generating the plots presented is self-contained and available on GitHub <a href="https://github.com/fraseriainlewis/towardsdatascience">here</a></p><h3>2. Models, software, data fitting</h3><p>The two models we consider here are typically referred to as mathematical models (as opposed to regression/statistical) but our ultimate purpose is statistical — data science —parameter estimation and prediction from real data. A useful analogy is with <a href="https://www.r-bloggers.com/2018/01/pk-pd-reserving-models/">PK/PD modeling</a> where the systematic part — the expected value of the biological system over time — is defined using a mathematical model, which is nested inside a statistical model, giving a non-linear mixed effects model formulation. The same concept applies here but we do not consider only time.</p><p>The two models we investigate describe the evolution of a biological system <strong>across</strong> <strong>two continuous dimensions</strong> — in the examples here, <strong>time <em>and</em> space</strong>, and <strong>time <em>and</em> probability</strong>. The models are defined below and are classical models from the scientific literature. Each model is expressed in terms of a partial differential equation (PDE). PDEs are used because these models describe the evolution of a dynamical system across two continuous dimensions. PDEs are widely used for this purpose, with the other major biological application being modeling across<strong> time <em>and</em> age</strong>. The latter is particularly important for any process where age is a driver, for example <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8427267/">infectious disease modeling</a>, <a href="https://alz-journals.onlinelibrary.wiley.com/doi/10.1016/j.jalz.2016.03.013">the onset of dementia</a>, <a href="https://www.sciencedirect.com/science/article/pii/S0895717797001659">demographic modeling</a> or indeed any biological growth process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Zc3zg1BWtBmwwdjIPDuaxA.png" /><figcaption>Fig 2. Stochastic logistic growth model estimated using Rcpp. Surface is the probability density for a stochastic growth process as it evolves over time from an initial point source. Image by author.</figcaption></figure><h3>2.1 Models</h3><h3>Model 1 — spatial logistic growth</h3><p>The first model — Fig1 — is an extension of classical logistic growth extended to one spatial dimension, and often referred to as the “Fisher equation”, and is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Y06LBg3BFyHru6UCsyRu9w.png" /><figcaption>The first equation defines the evolution of the process over space and time, the following three equations define the necessary boundary and initial conditions needed to solve the equation. n_0(x) is the initial starting value of the system at time 0. Image by author.</figcaption></figure><p>This model defines the growth (or spread) of some organism or population across space and time, with <em>n(x,t)</em> being the density of the organism at location x and time t. Space here is one-dimensional, so spread is along a single axis. In Fig1 the initial source is at position x=40 and the axis of spread is constrained to be from x=0 through x=100, and t=0 through 150 time units.</p><p>As per classical logistic growth, this model is non-linear and density dependent where the speed of growth depends on the population size, and has three parameters, r = rate of growth, K=carrying capacity of the population and D=diffusion coefficient. K determines the maximum height of <em>n(x,t)</em>, in Fig 1 this is K=50, and D determines how wide the spatial spread is, D=1 in Fig 1, and r=0.2.</p><h3>Model 2 — stochastic logistic growth</h3><p>The second model — Fig2 — is also an extension of classical logistic growth but rather than extended to evolve across a spatial dimension, it is instead extended to evolve stochastically over time. This model is mathematically more complex and is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*Sr8MR9Ozu84usbMwGA2vAw.png" /><figcaption>The first equation defines the model — see logistic growth — and then a Brownian motion diffusion term (dW) to add randomness. The second equation is the Fokker-Planck equation derived from the first equation, and the third and fourth equations are initial and boundary conditions, L_l and L_u, the lower and upper limits of n. The initial condition — last equation — is the Dirac delta function, this is particularly problematic (see main text). Image by author.</figcaption></figure><p>There are a number of different possible variants for a stochastic version of classical logistic growth (see <a href="https://www.tandfonline.com/doi/pdf/10.1080/07362994.2017.1386571">here</a> for a discussion) and this is one of the simpler models. The second equation is derived (easily, just dropping in terms — see <a href="https://en.wikipedia.org/wiki/Fokker%E2%80%93Planck_equation">here</a>) from the first equation and describes the evolution of <em>f(n,t)</em>=the probability distribution of the size of the population over time. This is the equation we wish to solve. The boundary conditions for this model are also more complex.</p><p>To help clarify the differences in purpose and interpretation between model 1 and model 2:</p><ul><li>Model 1 answers the question: “<strong>How many organisms are present in the population between spatial position x=10 and x=20 after 10 time units of evolution from an initial source?</strong>”</li><li>Model 2 answers the question: “<strong>What is the probability that the size of the population after 100 time units of evolution from an initial source is greater than 80?”</strong></li></ul><h3>2.2 Software —numerical work with Rcpp</h3><p>To first give a statistical/empirical context, the solution of model 1 for a given choice of parameters and initial conditions could be used as the mean trajectory in a non-linear regression model (e.g. with Gaussian errors) across space and time. The solution to the PDE for any given set of parameters is just a non-linear function of x and t. A complication is that as we can’t analytically solve this PDE, we can’t write out this (solution) function in a closed form, so it needs to be numerically computed for every set of parameter choices. For example, inside a fitting algorithm, e.g., non-linear least squares, the algorithm needs to call a function which solves the PDE every time it searches for better fitting parameter estimates.</p><p>Model 2 is already a stochastic model with a likelihood function and can (in theory) be directly fitted to available data given a suitable optimization routine (e.g., maximum likelihood estimation). An alternative is to provide the solution to the PDE — which is a probability distribution— to a Markov chain Monte Carlo (MCMC) sampling engine (e.g.,<a href="https://r-nimble.org/"> r-nimble</a>) for a Bayesian analysis. But the concept is identical to model 1; at each step of the fitting-to-data process (maximum likelihood or Bayesian) a solution is needed to the relevant PDE for any given set of parameters and initial conditions.</p><h3>Rcpp</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*KD_sROZqxpV0RS3b1evPvg.png" /><figcaption>Image by author.</figcaption></figure><p>There are a number of methodologies for numerically solving PDEs and arguably the easiest to implement is the <a href="https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html"><em>method of lines</em></a> (MOL), which is what we use here and this was implemented using <a href="https://dirk.eddelbuettel.com/code/rcpp.html#:~:text=The%20Rcpp%20package%20help%20to,matched%20to%20corresponding%20C%2B%2B%20objects.&amp;text=Each%20SEXP%20variant%20is%20automatically%20mapped%20to%20a%20dedicated%20C%2B%2B%20class.">Rcpp</a>. The MOL approach discretizes a PDE into a system of ODEs by using finite difference approximations for the spatial derivatives (in our examples the “x” and “n” dimensions respectively). The key programming task is preparing ragged 2-d vectors which will contain suitable repeating patterns of coefficients. This is not particularly taxing to setup, but it helps to write out long hand on paper first. The number of “rows” in the 2-d vectors depends on the grid size required (which is a parameter in the MOL which determines accuracy).</p><p>One aspect which needs bespoke attention is coding the boundary conditions. The boundary conditions are the first and last entries in the finite difference scheme and need to be adjusted to the type of boundary condition in the model. An excellent guide as to how to create a finite difference scheme and in particular how to calculate the terms needed for even complex boundary conditions is explained <a href="https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html">here</a>.</p><p>The last part needed in MOL is an ODE solver, ideally something fast with adaptive error control/step sizing. In these examples the <a href="https://www.boost.org/doc/libs/1_78_0/libs/numeric/odeint/doc/html/index.html">odeint</a> solver from the <a href="https://www.boost.org/">Boost library</a> was used with minimal adaptations to an existing example from the odeint documentation.</p><p>The Rcpp library was used for implementing the MOL solver, it was a good choice as there is already a boost package for Rcpp, called <a href="https://cran.r-project.org/web/packages/BH/index.html">BH</a>, and the actual coding of a finite difference scheme is straightforward even with minimal C++ knowledge. For performance reasons using a compiled language is important here, as if these models are to be fitted to data then the MOL solver may need to be called a great many times.</p><h3>2.3 Code snippets</h3><p>The full code for the models and plots is available <a href="https://github.com/fraseriainlewis/towardsdatascience">here</a> on GitHub. To give a flavor of the coding needed, below are two gists. The first illustrates one way to implement a finite difference scheme, which in effect involves rolling out a repeating set of coefficients into vectors. These vectors are then used later when defining the ODEs to be solved. This is the second gist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d7777c879a32d4136f3423e5df773f/href">https://medium.com/media/f4d7777c879a32d4136f3423e5df773f/href</a></iframe><p>The gist below numerically defines model 2 — a system of ODEs which correspond to the PDE for model 2. Note the vectors *vec_2d_* and *vec_2dh_* which are those created similar to the above gist and define the coefficients for the finite difference scheme. Of particular note is the upper boundary condition — the last line of code — which is hand coded to meet the mathematical requirements of the model definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b8695905836d6de62ff45ee77385793/href">https://medium.com/media/0b8695905836d6de62ff45ee77385793/href</a></iframe><h3>2.4 Modelling and numerical challenges</h3><p>Below are two additional plots, one each from model 1 and model 2, showing how the numerical solutions for each model evolve over time and space/probability. The solutions look smooth and intuitively reasonable — and indeed have been checked against Mathematica’s PDE solver. However, earlier attempts were not so successful and it was some work to get to these correct solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*A_EP-xkiF56UIUDuN05LnA.png" /><figcaption>Fig3. Model 1 — Fisher equation — as Fig1, but now only up to t=50 time units and r=0.1, shows early phase of population growth across distance axis. Image by author.</figcaption></figure><p>Finite difference schemes are widely used, and known to be reliable and accurate (provided a fine enough grid is used). This was also the experience here, but there were three areas of unexpected — although perhaps this should say expected, with hindsight — areas of difficulty: 1. the initial conditions; 2. the boundary conditions; and 3. understanding the actual properties of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*EV2n53NTUy82FaroKx2ouA.png" /><figcaption>Fig 4. Model 2 — Stochastic logistic growth model — as Fig 2. but different viewpoint looking ahead from time t=0. Image by author.</figcaption></figure><h4>1. Initial conditions</h4><ul><li>PDEs describe smooth functions, so the initial condition (at t=0) must be smooth across the second dimension, i.e., a smooth function across the space axis at time t=0. This means that evolving from a point source at t=0 is not strictly possible. Rather, a narrow smooth function should be used, for example a Gaussian density with very small variance. The practical challenge here is choosing this density/function. If it’s too narrow then the finite difference scheme will not give reliable results, whereas if it’s too wide then the scenario being modeled is not evolution from a point source. This is particularly problematic in model 2 as when fitting these models to data they evolve from a known initial observation — hence the <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">Dirac delta function</a> as the initial condition.</li></ul><h4>2. Boundary conditions</h4><ul><li>Numerical errors can propagate from a boundary condition resulting in unreliable results across the entire finite difference scheme. This does not affect simple boundary conditions — as in model 1, but it can certainly impact boundary conditions such as the upper boundary in model 2. For example, in model 2 the upper boundary condition was correct but the finite difference scheme gave nonsensical results. This was fixed by algebraically simplifying the boundary condition — the correctness of the expression was unchanged. This was a subtle issue as the original expression did not look numerically problematic, but seems to have been destabilizing the finite difference scheme.</li></ul><h4>3. Model properties</h4><ul><li>In Fig 2 the parameters used were alpha=0.1 and beta=100, so in the long term we expect the value of n to average around 100. This was indeed the case when the initial point source was a narrow Gaussian distribution centered at n(0)=10. However, if this same Gaussian distribution is moved to be centered at n(0)=4 then for these same parameter choices the finite difference scheme results become nonsensical. Move it a little further away from the origin, and everything is again fine. This same behavior also occurred when using Mathematica’s PDE solver. With some investigation this should not have been a surprise on reading the relevant literature. This model is bounded below by zero — the value of n(t) cannot be less than zero, which means that the lower boundary condition is <em>f(n=0,t)</em>= 0, i.e., no probability can accumulate at n=0. So in practice this model is not appropriate for modeling a small population or a population/organism in the very early phase of growth/spread, as in these cases die-out (or n approaching zero) may be a realistic possibility. Identifying in advance when this situation is likely to occur for a given set of parameters and initial conditions is the practical challenge.</li></ul><h3>3. Fitting to data and closing remarks</h3><p>The ultimate goal is to be able to fit these models to real data sets — inside an additional statistical model (non-linear mixed models etc). PDE models are clearly very rich in terms of shape and flexibility, and we have only examined two of the plethora of models across space and time, and space and probability, available in the scientific literature. It is also true that there are some numerical challenges when working with PDEs.</p><p>One of the biggest obstacles is how to robustly automate the process for solving a PDE such that it can be embedded inside a data fitting algorithm, such as maximum likelihood or MCMC. We solved the PDEs for model 1 and model 2 for just several sets of parameter values and initial conditions, which required some trial and error and some human decision making. The challenge is how to devise an algorithm to do this — which makes sensible choices when faced with unreliable results, and indeed how to first determine that the results produced are unreliable.</p><p>On the positive side, model 1 looks relatively tractable in terms of next steps, and this may be similar for other PDEs, for example for those with time and age dimensions. More complex models — particularly those describing time and probability — probabilistic evolution of processes, such as model 2 do appear rather more difficult.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49dae153c34a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-bespoke-stochastic-process-models-using-rcpp-49dae153c34a">Building bespoke stochastic process models using Rcpp</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[Variational Bayesian inference with normalizing flows: a simple example]]></title>
            <link>https://medium.com/data-science/variational-bayesian-inference-with-normalizing-flows-a-simple-example-1db109d91062?source=rss-6ee15ec3d4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1db109d91062</guid>
            <category><![CDATA[bayesian]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Fraser Lewis]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 12:38:32 GMT</pubDate>
            <atom:updated>2021-08-04T20:17:31.381Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>A basic introduction using Tensorflow Probability</h4><h3>1.0 Introduction</h3><p>Variational inference (VI) is a methodology to watch. For large or complex Bayesian modeling VI has the potential to become the go-to approach, not least because computationally VI fits naturally into the domain of machine learning. This article demonstrates how normalizing flows — which are briefly introduced — can greatly improve the performance of VI, even for very simple models. Normalizing flows are available in Tensorflow Probability (TFP) and boilerplate code has been borrowed from the TFP documentation. The combination of VI and normalizing flows creates a powerful tool for inferential modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*1Neh1PnBhweKtK8PEWhV9A.png" /><figcaption>Fig 1. Variational loss in TFP for a linear regression model with a transformed Gaussian surrogate posterior. Image by author.</figcaption></figure><h3>1.1 Why Bayesian inference?</h3><p>Bayesian modeling has become mainstream across many areas of science and technology in recent years. One of the defining characteristics of Bayesian modeling is the ability — and indeed requirement — to specify a prior belief about the model parameters to be estimated. In some applications this integration of prior knowledge is the key driver for choosing a Bayesian approach, e.g. to offset a paucity of available data. In other applications, the adoption of a Bayesian approach is more a pragmatic model design issue; with the availability of high quality Bayesian computational libraries, e.g., <a href="https://mcmc-jags.sourceforge.io/">JAGS</a>, <a href="https://mc-stan.org/">Stan</a>, <a href="https://r-nimble.org/">R-nimble</a>, <a href="https://docs.pymc.io/">PyMC3</a>, <a href="https://www.tensorflow.org/probability">Tensorflow Probability</a>, <a href="https://www.r-inla.org/home">R-INLA</a>, it is possible to quickly create bespoke probabilistic models of almost arbitrary complexity.</p><p>The flexibility of Bayesian model building brings with it additional risks and responsibilities, e.g., does the model actually make sense? What is the impact of the prior belief? Are the computational estimates robust?— and so on. For an expert perspective on the art of Bayesian model building reviewing some of the <a href="http://www2.stat.duke.edu/~berger/papers.html">articles by Prof. James Berger</a> is thoroughly recommended. The <a href="https://mc-stan.org/docs/2_27/stan-users-guide/index.html">Stan user guide</a> is also an invaluable source of examples and good practice.</p><h3>1.2 Computational challenges</h3><p>Bayesian inference is largely concerned with efficiently approximating hard-to-solve integrals. The most common approach to date being <a href="https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo">Markov chain Monte Carlo</a> (MCMC) sampling, which avoids the need to compute integrals by instead generating realizations from the posterior distribution. A wide range of different samplers are available and this is an active area of research with a large literature. The BUGS — Bayesian inference using Gibbs Sampling — project began in 1989 producing <a href="https://www.mrc-bsu.cam.ac.uk/software/bugs/">WinBUGS</a> launched in 1997. This was a first major step towards making Bayesian inference and model building accessible to non-experts, by removing the need for modelers to write their own samplers.</p><p>An alternative to MCMC sampling is to use <a href="https://rss.onlinelibrary.wiley.com/doi/10.1111/j.1467-9868.2008.00700.x">analytical approximations</a> for hard-to-solve integrals. This is the approach taken by <a href="https://www.r-inla.org/home">R-INLA</a>, which uses integrated nested Laplace approximations. This approach can be extremely fast and <a href="https://www.r-inla.org/home">R-INLA</a> is particularly popular in geospatial statistical modeling, although this approach is less generally applicable than MCMC.</p><p>Another alternative to MCMC is <a href="https://en.wikipedia.org/wiki/Variational_Bayesian_methods"><strong>Variational Inference</strong></a><strong> </strong>(VI) and the application of this approach, using Tensorflow Probability, is the focus of this article. An excellent general introduction and review on VI is available <a href="https://arxiv.org/abs/1601.00670">here</a>, with a <a href="https://mc-stan.org/">Stan</a> specific article <a href="https://arxiv.org/abs/1506.03431">here</a>. Variational inference attempts to find a (known) probability distribution which is as close to the posterior distribution as possible. Using a known distribution avoids the need to compute the hard-to-solve integrals. Variational inference does this by maximizing what’s typically referred to as the ELBO — Evidence Lower Bound — which is closely related to the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback-Leibler-divergence</a> (KL-divergence) which is a metric quantifying how similar two probabilities distributions are to each other. Maximizing the ELBO minimizes the KL-divergence between the true posterior and the surrogate distribution.</p><h3>1.3 Machine Learning</h3><p>Variational inference has become increasingly popular in recent years and is available in both <a href="https://mc-stan.org/docs/2_19/reference-manual/vi-algorithms-chapter.html">Stan</a> and <a href="https://www.tensorflow.org/probability">Tensorflow Probability</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*bXAX2sw9iytfJgPT-CAnug.png" /><figcaption>Screenshot of TPF API. Image by author.</figcaption></figure><p>The reasons for this may be manifold, but not least because <strong>VI fits naturally into machine learning (ML)</strong> in a way in which MCMC arguably does not. Variational inference requires numerical optimization as opposed to numerical integration. Machine learning modeling typically requires numerical optimization — the minimization of loss functions between some ML model and data. This means that <strong>Bayesian modeling using VI can take advantage of the latest purpose built ML frameworks, software and hardware</strong>, e.g., fast parallelization across CPUs, high performance multi-GPUs and other high performance computing infrastructure such as Google’s <a href="https://en.wikipedia.org/wiki/Tensor_Processing_Unit">TPUs</a>. This opens up the exciting possibility that, in future, VI might become the go-to computational approach for large or complex Bayesian models which are not computationally feasible using MCMC. Variational inference is therefore an area to watch.</p><h3>1.4 Bijectors and normalizing flows</h3><p>A main practical challenge in Bayesian inference using VI is in <strong>determining candidate distributions for the posterior </strong>— surrogate distributions. We require distributions which are flexible enough to closely match the true posterior distribution, while at the same time being analytically tractable so as to avoid those hard-to-solve integrals. The multivariate Gaussian distribution, typically after some transformation of variables, is arguably the most common choice. For example, the approach used in Stan (see <a href="https://arxiv.org/pdf/1506.03431.pdf">page 3 in here</a>) is to first transform all the latent variables in the model onto the real line, e.g., constrained variables such as variance parameters (which must be strictly positive) are transformed. A multivariate Gaussian distribution is then posited for these transformed variables, along with those already on the real line.</p><p>One of the known issues with using a Gaussian surrogate distribution, even after necessary transformations, is that the <strong>marginal posterior estimates of the model parameters may be under-dispersed</strong>. This is due to the Gaussian distribution not being sufficiently flexible to capture fully the shape of the true posterior distribution. A practical example of this is shown in <a href="https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions">this Tensorflow Probability tutorial</a>. The Gaussian surrogate is not a good estimate of the true posterior when compared with results from MCMC sampling, the latter being assumed the gold standard. Later in this article we see a similar issue of under-dispersion, using a different data set and a much simpler Bayesian model. So this is an issue not limited to complex models.</p><p>An alternative to positing a Gaussian surrogate is to adopt the approach used in the above mentioned Tensorflow <a href="https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions">tutorial</a>; use a <strong>trainable surrogate distribution</strong> <strong>which is derived using </strong><a href="https://arxiv.org/pdf/1908.09257.pdf"><strong>normalizing flows</strong></a><strong> (NF)</strong>, specifically, <a href="https://arxiv.org/pdf/1606.04934.pdf">inverse autoregressive flows</a> (IAF). Conceptually, normalizing flows transform a probability distribution into a different probability distribution through a series of bijection transformations. Bijectors are transformations applied to probability distributions which ensure that the transformations result in a valid probability distribution. Probability densities must integrate to unity and so if a transformation stretches or compacts a parameter then its density must be adjusted accordingly to maintain the same volume under the density. The IAF approach uses neural networks to chain together bijector transformations, these transformations have trainable parameters and so IAF effectively trains the surrogate distribution against the posterior. <strong>This may allow for a much better estimate of the posterior parameters than a Gaussian surrogate</strong>.</p><h3>2.0 Modeling</h3><p>The rest of this article is a top-line walk through of a Colab/Jupyter notebook — the full version of which is available on GitHub <a href="https://github.com/fraseriainlewis/towardsdatascience.git">here</a>. We only show enough of the code to provide an idea of the key steps. The full code is somewhat lengthy but has quite some repetition, and is a mix and match of existing Tensorflow Probability tutorials plus additional calls to the latest TFP API. The TFP API is a moving target and so the notebook uses hardcoded versions (Tensorflow=2.6.0rc0, Tensorflow Probability=0.13.0) to avoid later changes breaking the code, but also versions sufficiently recent so they include the *.experimental API functions. A Google Colab workbook with a GPU runtime was used for all the modeling.</p><h3>2.1 The data</h3><p>We use data from the classic <a href="http://www.medicine.mcgill.ca/epidemiology/Joseph/courses/common/rats.pdf">WinBUGS Rats example</a>, which is a widely used data set for demonstrating a Normal hierarchical model in Bayesian inference. The dataset comprises of observations from n=30 rats, and the weight of each rat is measured m=5 times over a period of 36 days. Here we do not use a hierarchical model (excluding priors), but rather a simple linear regression model with fixed effect intercept and slope. This might arguably not be the best approach for these data, but is chosen so as to give as simple an example as possible for demonstrating variational inference and normalized flows. It is not difficult to extend the code provided to include the necessary hierarchical structure/random effects into the likelihood function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*77XKEbsWHTLWzRqS8PJV_g.png" /><figcaption>Fig 2. Rats data from WinBUGS examples manual. Image by author.</figcaption></figure><h3>2.2 Model definition</h3><p>Below is the Bayesian model which we will use with the rats data defined in the BUGS language, and we will later also fit this model using <a href="https://mcmc-jags.sourceforge.io/">JAGS</a> (the code below is compatible with JAGS).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d792e24e00993b9ef58b496704bc66d/href">https://medium.com/media/2d792e24e00993b9ef58b496704bc66d/href</a></iframe><p>Equivalent code in Tensorflow Probability (TPF) which defines the same likelihood and priors is below (Gist 2). This uses a call to<a href="https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/JointDistributionNamedAutoBatched"> <strong>JointDistributionNamedAutoBatched</strong></a> which means the components are dictionaries. The code is quite readable but building a joint distribution using the TFP API can be somewhat complex as there are many different shape parameters. Using an “AutoBatched” call variant can help reduce complexity. See the official TFP tutorials for useful code snippets and also the API documentation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4edfd663b86287a7347d714a3dce5287/href">https://medium.com/media/4edfd663b86287a7347d714a3dce5287/href</a></iframe><p>We have defined the model to be fitted, what is needed next is to define the surrogate distribution for the posterior density of the parameters in Model 1. The VI fitting process will estimate the parameters in this surrogate so as to give the best fit given the available data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b632f77ec4c8ee83f772dcf6f9ca498e/href">https://medium.com/media/b632f77ec4c8ee83f772dcf6f9ca498e/href</a></iframe><p>The above gist shows the surrogate density definition. Each of the parameters in Model 1 is defined in the surrogate. The parameters which are range limited, e.g., tau_alpha — which is a variance parameter, and so must be strictly positive — have a <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus">softplus transformation</a> applied to a Gaussian density. This surrogate is a set of independent Gaussian densities (before any transformations).</p><h3>2.3 Model fitting</h3><p>We have defined the model and the surrogate, and so what is left is to do the fitting — minimize the negative variational evidence lower bound (ELBO). In simple terms if we look at the fitting code snippet below (Gist 4) we can see two distributions <strong>target_model1.unnormalized_log_prob </strong>and<strong> surrogate_posterior </strong>(where the former is simply the <strong>model1</strong> distribution as defined in Gist 2, with a slight adaptation to make it into <strong>target_model1, </strong>see the Jupyter workbook for details). The optimization performed here is to try to minimize the difference between these two distributions (where the difference is described by the negative of the ELBO metric).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d0d6da09937b3a109289bb1fe60a247/href">https://medium.com/media/5d0d6da09937b3a109289bb1fe60a247/href</a></iframe><p>The above gist is largely self-explanatory. Wrapping the fitting process into a <strong>tf.function</strong> substantially improved the computational time, and this was also helped by <strong>jit_compile=True</strong>. The <a href="https://www.tensorflow.org/guide/function">tf.function</a> compiles the code into a graph rather than executing in eager mode (the default in TF v2).</p><h3>2.4 Results from VI using Gaussian surrogate</h3><p>As with any numerical optimization it is important to track the progress of the model fitting process to assess convergence. Figure 3 below shows the loss function (negative ELBO) during the fitting process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*1Neh1PnBhweKtK8PEWhV9A.png" /><figcaption>Fig 3. Loss from Model 1. Image by author.</figcaption></figure><p>The loss plots show mean and median estimates of negative ELBO at each iteration. Each of these is based on 4 data points (as we chose sample_size=4) in the call to tfp.vi.fit_surrogate_posterior. The default is sample_size=1. The minimization appears to stabilize after about 30K iterations. The loss estimate is quite noisy, which is not surprising given it’s a Monte Carlo sample based estimate of the variational divergence. Increasing sample_size (e.g. from 4 to 20) appears to only have a small impact on the noise in the loss trajectory. <strong>The ELBO for this model is estimated to be ELBO=-663.5, </strong>we want to maximize this value (the plots show negative ELBO).</p><p>Marginal posterior density estimates are shown in Figure 4 for the intercept, slope and standard deviation (which are parameters alpha_i, beta_i and tau.c respectively in Gist 2). These are computed using realizations drawn from the surrogate density after the fitting process. Posterior point estimates and standard deviations are shown in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*_t-hnQnv7H6uPAGTk84RjQ.png" /><figcaption>Fig 4. Marginal posteriors for Model 1. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*8yg5MkpJlYofbIRjKjVVng.png" /><figcaption>Fig 5. Posterior point estimates from Model 1. Image by author.</figcaption></figure><h3>3.0 Bijector based multivariate Normal surrogate</h3><p>The surrogate distribution used above was created by independently defining the densities for each component (= parameters in model 1) using <strong>JointDistributionNamedAutoBatched</strong>. For more complex surrogates, e.g., a multivariate Normal allowing for covariance between model parameters, then a more flexible approach is needed using TFP’s bijector functionality. We briefly discuss this here as it’s a natural stepping stone towards the more complex method of normalizing flows.</p><p>The snippet below (Gist 5) is not complete — some essential boilerplate is missing — but shows the general idea of the method. A base distribution is defined, here a set of standard independent Normals. A covariance structure is also defined, and while the coding used here assumes a diagonal covariance matrix for simplicity (so this is not very different from the surrogate used above), a much more complex dependence structure could be used with this method. See <a href="https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions">here</a> for a more complex example of block-structured covariance using bijectors (which is outside the scope of this current article).</p><p>The last step is to chain together a series of bijector transformations to the base distribution, one of which is the covariance matrix transformation, one is for the location parameters, and one is to ensure the domains of the priors are matched (e.g., constrained to be strictly positive for some parameters). This general approach allows for the construction of multivariate Normal surrogate distributions which are constrained to the support region of the priors defined by the model. This approach is of course not limited to Gaussian distributions as other types of base distribution could be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a71f82f35ca34a588d2a10f15ac1313/href">https://medium.com/media/6a71f82f35ca34a588d2a10f15ac1313/href</a></iframe><p>The figure below is similar to Figure 3 but this time with the surrogate built using bijector transformations. The ELBO for this model is estimated to be <strong>ELBO=-663.9 which for all practical purposes is the same as the previous model given the margin of noise around the ELBO estimate</strong> (e.g., see right panel in Figure 6). This is expected given how similar the surrogate formulations are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*OZQt33Q1J_uFlX41qyKKWA.png" /><figcaption>Fig 6. Loss function for Model 1 with multivariate Normal surrogate using bijectors. Image by author.</figcaption></figure><p>The point estimates in Figure 7 are also similar to those in Figure 5 which is not unexpected, although the standard deviations are less similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*r4a9oZYJqohsmm9nNJVp4A.png" /><figcaption>Fig 7. Point estimates from multivariate Normal surrogate using bijectors. Image by author.</figcaption></figure><h3>4.0 Surrogate built using normalizing flows</h3><p>To build on Section 3.0 we now use a surrogate which is created using normalizing flows. In short, while technically rather complex, what normalizing flows allows us to do is create custom probability distributions trained to the problem at hand. To learn more about normalizing flows, which also have applications in density estimation, see the literature referenced <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/bijectors/MaskedAutoregressiveFlow">here</a>.</p><p>We again use some boilerplate code from TFP, part of which is identical to that used in Section 3.0 for the bijector based surrogate. The key difference here is that a new bijector transformation — an Inverse Autoregressive Flow (IAF) — is applied to the base distribution (again a set of Gaussians). From the TFP documentation, “Inverse Autoregressive Flows (IAFs) are normalizing flows that use neural networks to capture complex, nonlinear dependencies among components of the distribution”.</p><p>The snippet below (Gist 6) shows an example of the code used to implement IAF to build a surrogate distribution. This code borrows heavily from existing TFP tutorials. The main part of interest is in lines 8–12, particularly the number of IAF transformations to use, and the parameterization of each transformation as defined in the hidden_units parameter and choice of activation function (line 12). Different values for the number of IAF transformations, the number of hidden_units and the activation function were tried. Those below appeared to work well for the current dataset, giving reliable loss function behavior (which was not always the case and it is important to check this for each choice of these parameters).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0fc9d40b95383b845a87f820bf13c5d/href">https://medium.com/media/e0fc9d40b95383b845a87f820bf13c5d/href</a></iframe><p>To train the IAF surrogate to the data the code needed (Gist 7) follows the same form as that for the other surrogates, the only difference is the reference to the new IAF surrogate density.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d38d874e948b02582db3499385f966/href">https://medium.com/media/89d38d874e948b02582db3499385f966/href</a></iframe><p>The loss function is qualitatively similar to the previous surrogate, but note the different range and variance in the right hand panel of Figure 8. Compared with Figure 6— which is directly comparable as both use sample_size=1 to compute the loss, larger values are not stable — then we can see that the loss is rather more noisy and also that the distribution is located slightly below that in Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*0W51PGSxczXhfloX7msUuA.png" /><figcaption>Fig 8. Loss function for surrogate using normalizing flows. Image by author.</figcaption></figure><p>The ELBO for this model is estimated to be <strong>ELBO=-662.6</strong>, and given the comparison with the previous loss figures, then it seems reasonable that the ELBO should be slightly less, but the difference is very small, and in practical terms arguably negligible.</p><h3>5.0 Do normalizing flows perform better in VI?</h3><p>We have used a very simple model — a linear regression with intercept and slope —and fitted this model to data using VI, with and without a normalizing flows-based surrogate density. One metric for determining how well a surrogate density performs is the ELBO value. In a previous TFP <a href="https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions">tutorial</a> it’s shown that a surrogate density with normalizing flows has a much better (factor of 2) ELBO value. From our results above this is clearly not the case here; the ELBO for the IAF surrogate is very slightly better but this is hardly convincing evidence to support the more complex approach of normalizing flows.</p><p>To gain more insight into whether normalizing flows has actually helped with our current modeling problem we compare density estimates from the VI IAF model with those from JAGS (which uses MCMC). Markov chain Monte Carlo sampling is arguably the gold standard approach here as it does not use any surrogate density. Figure 9 shows a comparison between the results obtained from MCMC (JAGS), with those from VI using the Gaussian surrogate from Section 3.0 and the IAF surrogate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*z-f_qrZMjPwL_RXu2OA9sQ.png" /><figcaption>Fig 9. Marginal posterior densities using different methods. MCMC — green, normalizing flows — blue, transformed Gaussian — pink, constrained Gaussian using bijectors — red. Image by author.</figcaption></figure><p>It is obvious from Figure 9 that the normalizing flows model is much closer to the MCMC results than either of the Gaussians surrogates, and indeed IAF is almost identical to MCMC for the intercept and slope parameters. So for this example, which is almost the simplest possible model and data, then the use of a normalizing flows surrogate gives substantially better parameter estimates when using variational inference. The Gaussian surrogates clearly suffer from under-dispersion, which is similar to what is seen in some of the TPF tutorials (which also use Gaussian surrogates with more complex covariance structures, we used a simple diagonal matrix here). However, in contrast to the TPF tutorials, it is interesting to note that in this example if we had only used the ELBO metric we may have opted not to use the normalizing flows approach given the extra complexity involved. This shows the importance of examining density plots of the parameter estimates.</p><p>This simple example suggests that normalizing flows may provide considerable additional flexibility and reliability when using variational inference. That said, MCMC-based inference may still offer the best practical solution to many current problems, e.g., the model used here can be fitted with the code in Gist 1, plus just a few more lines to configure the sampler, and actual sampling takes only a few seconds computational time. As with any MCMC-based modeling, various diagnostic checks need to be performed but overall it is still a very efficient approach for many problems.</p><h3>6.0 Conclusion</h3><p>This article has provided a brief top-level guide on how to apply variational inference in TPF, and how to use its normalizing flows functionality to improve the modeling results. A self-contained Colab/Juptyer notebook with all the code needed to generate the results shown is available on GitHub <a href="https://github.com/fraseriainlewis/towardsdatascience.git">here</a>. Also provided in the same repository is the JAGS code/files needed to fit the same model via MCMC.</p><p>Variational inference with normalizing flows is an exciting area to watch for new methodological developments and especially for new use cases which involve real-world modeling challenges.</p><h3>About the author</h3><p>This is <a href="https://www.linkedin.com/in/fraser-lewis-819a5080/">me</a>, I work in R&amp;D Data Science at <a href="https://www.danone.com/">Danone</a> where I manage a great team of data scientists and I am also lucky enough to do some hands on modeling work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1db109d91062" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/variational-bayesian-inference-with-normalizing-flows-a-simple-example-1db109d91062">Variational Bayesian inference with normalizing flows: a simple example</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[Advanced forecasting using Bayesian diffusion modeling]]></title>
            <link>https://medium.com/data-science/advanced-forecasting-using-bayesian-diffusion-modeling-b155a3dc1d84?source=rss-6ee15ec3d4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b155a3dc1d84</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <category><![CDATA[stochastic-process]]></category>
            <category><![CDATA[deep-dives]]></category>
            <dc:creator><![CDATA[Fraser Lewis]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 10:55:18 GMT</pubDate>
            <atom:updated>2021-04-14T22:45:01.786Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/notes-from-industry">Notes from Industry</a></h4><h4><strong>Across all areas of data science there is huge demand for innovative modeling solutions aimed at forecasting and elucidating dynamic phenomena</strong>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hGuAo6SLnObQPZgICSwPtA.png" /><figcaption>Fig 1. Green, blue = raw data, pink = selected fitted values, black = forecasts from time=23 to 25, grey = 95% Bayesian posterior predictive intervals. Image by author.</figcaption></figure><p>High profile use cases of modeling and forecasting dynamic phenomena include:</p><ul><li><strong>Finance </strong>— prediction of share price movements or commodity price fluctuations</li><li><strong>Biomedical science</strong> — prediction of biological trajectories, e.g. growth, evolution, determination of drug treatment impact</li><li><strong>Epidemiology</strong> — assessing the impact of intervention strategies such as vaccination on epidemic waves of infection, e.g. covid-19</li><li><strong>Energy </strong>— predicting the output of wind or wave turbines, electricity demand forecasting</li><li><strong>Manufacturing</strong> — optimizing the output of continuous industrial processes such as evaporation in food production</li></ul><p><strong>Machine learning methods</strong>, e.g. <a href="https://en.wikipedia.org/wiki/Long_short-term_memory">LSTM networks</a> or <a href="https://en.wikipedia.org/wiki/Random_forest#:~:text=Random%20forests%20or%20random%20decision,average%20prediction%20(regression)%20of%20the">random forests</a>, have been used to tackle these and similar problems, but such approaches are not without <a href="https://towardsdatascience.com/how-not-to-use-machine-learning-for-time-series-forecasting-avoiding-the-pitfalls-19f9d7adf424">challenges</a>. This article presents a different modelling approach — <strong>Bayesian diffusion modeling </strong>— which is a white-box method capable of rich dynamic behavior using only a few parameters.<strong> </strong>This methodology is somewhat advanced, at least in a mathematical sense, as diffusion processes involve stochastic calculus, but real world application can be relatively painless using existing R/Python/Julia libraries, plus some programming knowledge, and a bit of previous exposure to Bayesian inference.</p><p>An end-to-end example is presented which demonstrates Bayesian diffusion modeling applied to an open source dataset. <a href="https://www.r-project.org/">R</a> is used, specifically the <a href="https://r-nimble.org/">R-nimble</a> library, but the modelling could equally well be implemented in Python using, e.g., <a href="https://mc-stan.org/">Stan</a> or <a href="https://www.tensorflow.org/probability/overview">Tensorflow probability</a>. <a href="https://r-nimble.org/">R-nimble</a> is a general computing framework and has an active community on <a href="https://groups.google.com/g/nimble-users">google groups</a>.</p><p>It is hoped that this short case study will stimulate interest in this rich and elegant methodology. It is not new but neither is it yet a part of many data scientists’ modeling toolbox and could be a worthy addition. For forecasting and prediction use cases in particular, because this is a continuous time methodology then dealing with irregularly spaced data is built-in, which can be rather difficult in terms of modeling serial correlation in other approaches.</p><h3>1. Bayesian diffusion modeling — building blocks</h3><p>Bayesian diffusion modeling comprises of two key building blocks:</p><p>Step 1,</p><ul><li><strong>define a stochastic process</strong> <strong>that</strong> <strong>is flexible enough to describe the dynamic phenomenon of interest </strong>— this is encapsulated in a <strong>stochastic differential equation</strong> (SDE). <strong>Many standard formulations exist.</strong></li></ul><p>Step 2,</p><ul><li><strong>estimate the parameters</strong> <strong>in the SDE(s) from step 1 from data using Markov chain Monte Carlo (MCMC) </strong>simulation,<strong> </strong>including if applicable, additional parameters needed to address complexities such as measurement error and hierarchical random effects structures.</li></ul><p>SDEs are a highly flexible and concise way to describe dynamic phenomena and are widely used in <a href="https://www.quantstart.com/articles/Stochastic-Differential-Equations/">quantitative finance</a>, with some examples in <a href="https://pubmed.ncbi.nlm.nih.gov/33490877/">medicine</a> and <a href="https://onlinelibrary.wiley.com/doi/full/10.1002/we.1988">energy</a>. The model’s parameters can be estimated from data using MCMC, which while computationally expensive, is accessible and has the considerable advantage of being almost universally applicable regardless of model complexity. <strong>Combining these two methodologies gives Bayesian diffusion modeling</strong>.</p><p>The use case example presented below is somewhat simplified, to make it as easy to follow as possible, but the same modeling steps are present in more realistic situations. The main difference being that here the model formulation has been chosen apriori, whereas in reality this should be decided by some form of model selection process to ensure the model chosen is optimally parameterized given the data available.</p><h3>2. Forecasting cancer tumor growth — case study</h3><p>This comprises three sections:</p><ol><li>the<strong> data;</strong></li><li>the<strong> model</strong> <strong>formulation</strong>;</li><li>the <strong>model fitting and forecasting</strong>.</li></ol><p>The key modeling code snippet is provided below as a gist. The full data set is available at the author’s <a href="https://github.com/fraseriainlewis/towardsdatascience">GitHub repo</a> along with the full code needed to reproduce the results and plots.</p><h3>2.1 The data</h3><p>The data comprise a single growth trajectory of a breast cancer tumor and a snippet of these data are given in the below gist. The original data are available in Zenodo <a href="https://zenodo.org/record/3574531#.YGmSJjHisuU">here</a> but as they only comprise of 15 time points over 23 days, simulation was used to generate more densely sampled data sets giving n=231 rather than n=15 over the same time period. Several different simulated datasets are used. A specific point of note about the data format is that each row is a transition — start time (Time1), stop time (Time2) with starting point (Observation1) and ending point (Observation2). This format is to match how the model likelihood will be specified (see later).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628f28208abf14f4ff00e992a548c261/href">https://medium.com/media/628f28208abf14f4ff00e992a548c261/href</a></iframe><h3>2.2 Model formulation</h3><p>Bayesian diffusion probabilistically describes how a process evolves from a given starting position, e.g. (Time1, Observation1) through to a later position (Time2, Observation2). This process is described using a stochastic differential equation (SDE). The SDE chosen for this case study is given below in equation 1. It is a stochastic form of the well known <a href="https://en.wikipedia.org/wiki/Gompertz_function">Gompertz function</a> and chosen here because Gompertz models have been used for modeling of cancer tumor growth (e.g. see this <a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1007178">publication</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*0OtOFng-CMG3NWh-vlehYQ.png" /><figcaption>Equation 1. Stochastic differential equation for a Gompertz function. Image by author.</figcaption></figure><p>In equation 1 the multiplicative factor before the dt term is called the <strong>drift</strong> and the term before the dW is called the <strong>diffusion</strong>. The dW is a Brownian motion process (or <a href="https://en.wikipedia.org/wiki/Wiener_process">Wiener process</a>, hence the “W” in dW) which continually perturbs the evolution of the process X(t) through time. Specifically considering tumor growth, then such perturbations are intuitively reasonable given the natural ebbs and flows which occur in any complex dynamical biological system, e.g. due to competition between the tumor and other organisms for essential nutrients.</p><p>In this example a Gompertz-like SDE is a reasonable choice apriori. There are a number of standard SDE models, mostly used or developed initially in a financial modeling context. For example, the <a href="https://en.wikipedia.org/wiki/Ornstein%E2%80%93Uhlenbeck_process">Ornstein-Uhlenbeck model</a> which is a mean reverting process and the <a href="https://en.wikipedia.org/wiki/Vasicek_model">Vasicek model</a> which was developed to model interest rates. In general, an SDE can have any terms for drift and diffusion including explicit dependent on time t. Polynomial forms of drift have been used in biological applications to model child growth trajectories (see <a href="https://gatesopenresearch.org/articles/4-71">here</a>). That said, a major practical caveat is that an SDE needs to have a tractable slice density (see later) and so drift and diffusion terms are typically chosen with this in mind.</p><p>A final remark on the model in equation 1 is that the diffusion process (dW) is scaled by X(t). This is a convenient way to ensure that the diffusion process cannot perturb the overall process to such an extent that this results in negative values for X(t) — which would make no biological sense here as X(t) is the size of tumor.</p><h3>2.3 Model fitting using MCMC</h3><p>To understand how to work with SDE models it is likely necessary to look at the code of a full example in some detail. A snippet of this follows in a gist, but first it is necessary to complete the specification of the model in equation 1 and determine its likelihood by:</p><ol><li>determining the <strong>slice density</strong> of the SDE (also called the transition probability density) and</li><li>define any <strong>additional complexities</strong> that are needed in the model, e.g. measurement or observation error.</li></ol><h3>2.3.1 SDE slice density derivation</h3><p>From equation 1 it is easy to derive the slice density using the <a href="https://www.wolfram.com/resources/">Wolfram Language sandbox</a> (no sign-in required) or else directly in Mathematica or in the Wolfram Engine (free for developers). See figure 2 which shows how to compute the slice density for the SDE in equation 1. This will be used in the later MCMC code in R-nimble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lU8xrB326yQ32xichBSy2w.png" /><figcaption>Fig 2. Slice density computation. Image by author.</figcaption></figure><p>The slice density defines how likely it is that the model (a stochastic process) will pass through a particular point in the future, based on what is known of the current state of the process. Hence this density function describes a probabilistic “slice” across all paths or realizations of the model between any two time points. In figure 2 an expression for the log slice density is also computed — this is what is needed in the R-nimble model specification.</p><h3>2.3.2 Additional model features in MCMC</h3><p>An optimal model for any given dataset may comprise only the SDE — drift and diffusion — part, however, it is also typical to want to include an additional random error component such as independent and identically distributed (iid) Normal errors into the model. This would account for measurement error, for example, suppose the instrument used to measure tumor volume suffers from a small but non-ignorable measurement error. This would correspond to iid Normal errors in addition to the stochastic variability present in the underlying dynamical system.</p><p>Measurement error is included in the model given in the following gist. Note that by including this form of additional random error, the dynamic phenomena being modeled is now only latently observed — what is actually observed is Y(t) = X(t) + Z(t), where X(t) is the true tumor growth and Z(t) is measurement error (say).</p><h3>2.3.3 Model formulation in R-nimble</h3><p>The gist below contains the key snippet of code that defines a Bayesian diffusion model (with measurement error) in R-nimble. The full code is available <a href="https://github.com/fraseriainlewis/towardsdatascience">here</a>. Some remarks:</p><ul><li>the full code uses the CRAN <strong>parallel</strong> library for efficiency which adds slightly more complexity (the main modeling code needs wrapped into a function)</li><li>defining<strong> </strong>a<strong> custom probability distribution</strong> is necessary for the slice density, this is straightforward — see the R-nimble manual</li><li>to generate forecasts/fitted values the input data set needs to contain dummy records with NA for the forecasts/fitted values to be estimated</li><li>As currently coded the full MCMC estimation can take 60 minutes across 8 cores (Intel Xeon 2.2 Ghz), so some patience is required (or reduce the length of the chains if only debugging).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3125c6bda9210b43477cfba6271e861f/href">https://medium.com/media/3125c6bda9210b43477cfba6271e861f/href</a></iframe><p>For completeness the R session information from a run of the full code is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*TTimS_FNDAfLHvPtwn920Q.png" /><figcaption>Fig 3. R session information. Image by author.</figcaption></figure><h3>2.3.4 Results</h3><p>A Bayesian diffusion model using the Gompertz formulation given in equation 1 (plus the addition of iid Normal errors as per the above gist) was fitted to two different data sets. Each data set comprised of n=231 data points and were different realizations from the original cancer tumor data set (see section 2.1). Figures 4 and 5 show forecasts and their associated uncertainty using the models, plus also a subset of fitted values to illustrate the model fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*YB1pwXoYmJEZTtwkQ2cTKQ.png" /><figcaption>Fig 4. Green = raw data, pink = some fitted values, black = forecasts from time=23 to 25, grey = 95% Bayesian posterior predictive intervals. Image by author.</figcaption></figure><p>The results in figure 4 look intuitively reasonable — especially for such a simple model, Gompertz has only two parameters —and the fitted values are close to the observed values. The forecasts also look plausible and behave as forecasts should where the farther into the future the forecast the greater the uncertainty around it. Note that these are <strong>Bayesian posterior predictive</strong> <strong>forecasts</strong>, i.e. from quantiles of the posterior predictive distribution, and so the uncertainty estimates surrounding the forecasts also include parameter estimation uncertainty (as opposed to making predictions conditional on a single set of parameter estimates — which is typical in non-Bayesian modeling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*A9Q7Y8-rV1iYbGmMMEsqRA.png" /><figcaption>Fig 5. Blue = raw data, pink = some fitted values, black = forecasts from time=23 to 25, grey = 95% Bayesian posterior predictive intervals. Image by author.</figcaption></figure><p>Figure 5 is similar to figure 4 in that the results, both fitted values and forecasts, look intuitively reasonable. The qualitative behavior of this trajectory is rather different from that in figure 4 — here the tumor’s growth initially increases linearly and then plateaus. The same form of stochastic Gompertz model is used here but the parameter estimates are very different reflecting the different shape of the data.</p><h3>3. Bayesian diffusion modeling — building models</h3><p>As with any modeling methodology the real skill is often in the art of how to build and parameterize a model so that it’s optimal — at least in some sense — for a specific problem or dataset. This is particularly true with Bayesian diffusion models as there is both the SDE formulation itself and then the MCMC formulation, each of which can be customized. The following two sections contain some general advice and remarks on model building with SDEs.</p><h3><strong><em>3.1 General SDE formulations</em></strong></h3><p>Section 2 demonstrated the application of a Bayesian diffusion model based on a Gompertz formulation. There are many other possibilities, for example equation 2 shows an SDE which is linear in the drift term but also has an explicit dependence on time. Figure 6 shows how to compute the log slice density for the SDE in equation 2. Again, this is a relatively simple process (as Mathematica does all the hard work here!).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*rOMA6Er-upQGdUydL_OAxg.png" /><figcaption>Equation 2. A polynomial form of SDE. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKbpxnjHBU92QZ7MqVTEtg.png" /><figcaption>Fig 6. Slice density estimation for a polynomial SDE. Image by author.</figcaption></figure><h3>3.2. Transformations and nesting</h3><p>Perturbation of a dynamic process by Brownian motion assumes that the process being modeling can both increase and decrease, which was appropriate for the above tumor example. For some dynamic phenomena, however, diffusion can realistically only happen in one direction. A good example is height, the growth in height of a child/animal/plant is a non-decreasing process — growth in height may slow or stop but the entity cannot (typically at least) become smaller. A solution to this problem is not to model the dynamic process directly with an SDE/diffusion model, but rather incorporate a diffusion model into the parameters in a model which does enforce non-decreasing behavior, e.g.,</p><ul><li>consider the growth model <strong>Y(t)= a + b X(t) + c X(t)²</strong> — a simple polynomial regression. Now, if modeling a non-decreasing process then simply include a transformation of the parameters such as</li><li><strong>Y(t)= exp(a) + exp(b) X(t) + exp(c) X(t)² </strong>— this is now a non-linear model, which is not a problem for MCMC estimation, and it forces the model to be non-decreasing no matter whether a, b and c take positive or negative values.</li></ul><p>If the process being modeled is dynamic then assuming that the parameters a, b, and c are static over time might not be realistic, or at least this possibility should be considered in the model selection process. To allow the regression parameters to fluctuate stochastically over time then these parameters, either individually or jointly, can be modeled using Bayesian diffusion, for example see equation 3,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*NlqIFedxQnKjAXBN32nB7w.png" /><figcaption>Equation 3. Simple SDE for a parameter “a” in a regression model with drift parameter omega. Image by author.</figcaption></figure><p>If it’s desired that the regression parameters are mutually correlated over time then they could be parameterized as a joint drift and diffusion process (which would involve a system of SDEs and multiple Brownian motion processes). Such approaches can provide an incredibly rich modeling framework.</p><h3>3.3 Tractability</h3><p>A practical consideration when model building is tractability. Mathematically speaking, SDEs in general are not analytically tractable, and so a formulation needs to be chosen that has a slice density available in a closed form. Strictly speaking this is not true, as it is possible to estimate the slice density numerically. Simulation can be used, and there are a number of <a href="https://cran.r-project.org/web/packages/Sim.DiffProc/vignettes/snssde.html">SDE simulation libraries</a> available for R and also <a href="https://diffeq.sciml.ai/stable/tutorials/sde_example/">Julia</a>, or else by numerically solving the <a href="https://en.wikipedia.org/wiki/Fokker%E2%80%93Planck_equation">Fokker-Planck</a> equation. But both of these approaches involve considerable effort — technically and computationally, as this would also need to be nested inside the MCMC sampling process.</p><h3>4. Final remarks</h3><p>This article has provided a brief introduction to Bayesian diffusion modeling and has hopefully demonstrated that it can be a powerful tool for tackling challenging forecasting problems. The best way to learn how to apply Bayesian diffusion models to real problems is to work through an end-to-end coding example. This can be found on GitHub <a href="https://github.com/fraseriainlewis/towardsdatascience">here</a>.</p><h3>About the author</h3><p>This is <a href="https://www.linkedin.com/in/fraser-lewis-819a5080/">me</a>, I work in R&amp;D Data Science at <a href="https://www.danone.com/">Danone</a> where I manage a great team of data scientists and I am also lucky enough to do some hands on modeling work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b155a3dc1d84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/advanced-forecasting-using-bayesian-diffusion-modeling-b155a3dc1d84">Advanced forecasting using Bayesian diffusion modeling</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[Developing a career as a data scientist in the life sciences industry]]></title>
            <link>https://medium.com/data-science/developing-a-career-as-a-data-scientist-in-the-life-sciences-industry-4025ee386895?source=rss-6ee15ec3d4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4025ee386895</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[life-sciences]]></category>
            <dc:creator><![CDATA[Fraser Lewis]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 14:26:01 GMT</pubDate>
            <atom:updated>2021-02-13T14:26:01.071Z</atom:updated>
            <content:encoded><![CDATA[<h4>Challenges and opportunities</h4><p>The role of data scientist is a relatively new addition to the research and development (R&amp;D) landscape within large life science — pharmaceutical, medical nutrition, biotechnological — companies. For early career data scientists, or established data scientists interested in a move into life sciences research, there are increasing opportunities in this field as it matures and gains recognition alongside established scientific disciplines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Afahai76IU-NpEzKWknog.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">National Cancer Institute</a> on <a href="https://unsplash.com/s/photos/laboratory?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>To be a successful data scientist in a life sciences research environment, particularly in a larger company, requires many of the same skills and experiences as in any other industry. But there are some notable differences:</p><ul><li>a greater emphasis on scientific research expertise than commercial awareness;</li><li>soft skills and the ability to build and maintain partnerships with scientific experts can be more valuable than pure business consulting skills.</li></ul><p>Surrounding this is perhaps the biggest challenge of all, being a new discipline. Doing something new is always exciting, but can bring additional demands until the new becomes the norm.</p><h3>Being the new kid on the block can be tough</h3><p>One of the biggest challenges of being a new discipline within a mature organisation is the need to establish what extra value this new discipline will bring. This is particularly true in the life sciences industry as its focus is scientific research - R&amp;D’s primary role is that of scientific discovery leading to new commercial opportunities. Life science R&amp;D departments typically boast many academically impressive CVs, PhDs abound, as do long peer-reviewed scientific publication bibliographies. Introducing a new role of data scientist into this setting can be sensitive, and indeed sometimes challenging, as many of these very smart people have been doing their own data analyses for years as an essential part of their existing work. In this sense the data scientist may, at least by some, be viewed as an interloper. This is compounded by data science and data scientist being somewhat vague terms.</p><p>In my experience, two areas worthy of specific consideration for a new data scientist are:</p><ul><li>how to effectively engage with scientific colleagues — get a foot in the door so to speak — on projects where the project or program leader is a scientist, which is a typical way of working. Previous projects did not have a data scientist and were successful so why is one now needed?</li><li>once involved in a project, how to secure an appropriate and rewarding role in the project’s activities going forward, and improve the chances of a data scientist being included as an essential part of future projects.</li></ul><p>A key learning to help with these challenges is to be very aware of the world view and perspective from scientist colleagues — put yourself in their shoes. If similar previous projects have been successful using classical statistical modelling techniques (t-tests, non-parametric, PCA, etc.) and typically conducted by the scientists themselves, then proposing new — and potentially complex — methodologies, e.g. AI, machine learning or advanced statistical modelling, unfamiliar to the scientists can simply fail to land, resulting in frustration and wasted effort all round.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VX3CmoAqxCiqYdZTdCCJ4g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tetrakiss">Arseny Togulev</a> on Unsplash</figcaption></figure><p>Introducing new data science modelling techniques into a project can require considerable care and may need to be done at a much slower pace than anticipated. This can be frustrating as identifying a clever new way to tackle an existing problem is energising and it’s natural to want to move ahead with all speed. My advice here is to be patient, it will happen but give it time. Good soft skills are key, gently educate and bring colleagues with you. The argument that some new method is better on purely technical grounds can have little traction when previous publications — which have been peer-reviewed and therefore considered to be of good scientific quality — have used the existing modelling approaches. An important point to consider is what is the use case for adopting a new approach? Is it compelling? Can you make it compelling?</p><p>Introducing a data scientist with lots of new — and powerful!— but unfamiliar modelling tools at their disposal into a team of successful scientists is a change, and change takes time, some people will embrace it, and some people will not. My advice is to focus on those who embrace change, gain their trust and they may then become an ambassador for you and for data science, helping to demonstrate the added value that a data scientist can bring to a project.</p><h3>Professional standards in data science</h3><p>Some parallels with introducing data scientists into life sciences research can be drawn with the introduction of biostatisticians into clinical trials and biomedical research. It is also not uncommon for biostatisticians to move into data science roles as more opportunities become available. Biostatistics is a very well established career path in pharmaceutical companies from entry level roles to the top of senior management.</p><p>One of the key differences, however, compared to life science R&amp;D is that clinical trials is a highly regulated area where Good clinical practice (GCP) mandates that any data analyses be conducted by a competent person. In practice, this means someone who has a formal qualification/certification in statistics. This governance framework means that biostatistics as a discipline has a reserved place alongside scientists and medical researchers. But this did not happen overnight, clinical research has a very long history. Data science and the data scientist role is still very much evolving as a discipline and job profile.</p><p>Introducing a governance framework and professional standards for data science in life sciences research has been discussed by The Royal Society in “<a href="https://royalsociety.org/blog/2020/07/what-makes-a-data-scientist-why-professional-skills-and-behaviours-are-more-important-than-ever/">What makes a data scientist? Why professional skills and behaviours are more important than ever</a>”. This is a positive step but given the huge diversity and scope of life science R&amp;D this is ambitious, but is a space well worth watching in the coming years.</p><h3>Growth and opportunities</h3><p>While it is still early days for data science in a life sciences environment it already feels like a fundamentally different career path from “mainstream” data science. Aside from the differences mentioned above, such as an emphasis on science as opposed to commercial awareness, there are also many practical differences. For example in my own day-to-day work, <a href="https://www.r-project.org/">R</a> rather than <a href="https://www.python.org/">Python</a>, is the go-to tool for most projects, Python is part of our ecosystem but a minor part. This also reflects a difference in the skills I look for in potential data scientist candidates. For example, an increasingly common aspect of CVs I receive is to list all the different technology/ML frameworks which the candidate has experience with. This might be suitable for technology sector roles but it’s not such a good pitch for life science R&amp;D roles.</p><p>What I look for in early career data scientists is research aptitude and depth of methodological understanding of modelling techniques. Experience with specific technologies or programming languages is something I view more as a commodity to be learned as needed. This may be different from other sectors or roles where it’s essential to hit the ground running with a high level of experience in a particular language or framework, e.g., as the focus is on development of new data science tools for deployment into production. For example, a forecasting model or decision support system. This is different from life sciences R&amp;D where data science activities are largely directed towards generating new research insights through partnering with scientists.</p><p>To conclude, a career as a data scientist in the life sciences industry offers challenges but also rich rewards — the potential to really shine by bringing fresh thinking and new tools to existing data and modelling problems. Providing new breakthroughs and innovations. There is a reason why Data Scientists are being hired after all. Life scientists multi-tasking as part-time data analysts is not going to change, and neither should it, but by partnering with scientist colleagues and building strong networks and relationships then data science as a career choice in life sciences has a very bright future.</p><h3>About the author</h3><p>This is <a href="https://www.linkedin.com/in/fraser-lewis-819a5080/">me</a>, my career to date has been in biomedical and life sciences research, specifically in biostatistics and data science since getting my PhD in 2000. I currently work in the Netherlands in R&amp;D Data Science at <a href="https://www.danone.com/">Danone</a>, prior to that I worked in R&amp;D Data Science at <a href="http://www.rb.com/">Reckitt Benckiser</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4025ee386895" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/developing-a-career-as-a-data-scientist-in-the-life-sciences-industry-4025ee386895">Developing a career as a data scientist in the life sciences industry</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>