Parameter estimation with Markov chain Monte Carlo¶
[1]:
import numpy as np
import scipy.stats as st
import pandas as pd
import cmdstanpy
import arviz as az
import bokeh_catplot
import bebi103
import holoviews as hv
hv.extension('bokeh')
bebi103.hv.set_defaults()
import bokeh.io
import bokeh.plotting
bokeh.io.output_notebook()
In this lesson, we will learn how to use Markov chain Monte Carlo to do parameter estimation. To get the basic idea behind MCMC, imagine for a moment that we can draw samples out of the posterior distribution. This means that the probability of choosing given values of a set of parameters is proportional to the posterior probability of that set of values. If we drew many many such samples, we could reconstruct the posterior from the samples, e.g., by making histograms. That’s a big thing to imagine: that we can draw properly weighted samples. But, it turns out that we can! That is what MCMC allows us to do.
We discussed some theory behind this seemingly miraculous capability in lecture. For this lesson, we will just use the fact that we can do the sampling to learn about posterior distributions in the context of parameter estimation.
Stan: Our MCMC engine¶
We will use Stan as our main engine for performing MCMC, and will use one of its Python interfaces, CmdStanPy. Stan is the state of the art for MCMC. Importantly, it is also a probabilistic programming language, which allows us to more easily specify Bayesian generative models. The Stan documentation will be very useful for you.
The data set¶
The data come from the Elowitz lab, published in Singer et al., Dynamic Heterogeneity and DNA Methylation in Embryonic Stem Cells, Molec. Cell, 55, 319-331, 2014, available here. In the following paragraphs, I repeat the description of the data set and EDA from last term.
In this paper, the authors investigated cell populations of embryonic stem cells using RNA single molecule fluorescence in situ hybridization (smFISH), a technique that enables them to count the number of mRNA transcripts in a cell for a given gene. They were able to measure four different genes in the same cells. So, for one experiment, they get the counts of four different genes in a collection of cells.
The authors focused on genes that code for pluripotency-associated regulators to study cell differentiation. Indeed, differing gene expression levels are a hallmark of differentiated cells. The authors do not just look at counts in a given cell at a given time. The temporal nature of gene expression is also important. While the authors do not directly look at temporal data using smFISH (since the technique requires fixing the cells), they did look at time lapse fluorescence movies of other regulators. We will not focus on these experiments here, but will discuss how the distribution of mRNA counts acquired via smFISH can serve to provide some insight about the dynamics of gene expression.
The data set we are analyzing now comes from an experiment where smFISH was performed in 279 cells for the genes rex1, rest, nanog, and prdm14. The data set may be downloaded here.
ECDFs of mRNA counts¶
We will do a quick EDA to get a feel for the data set by generating ECDFs for the mRNA counts for each of the four genes.
[2]:
# Load DataFrame
df = pd.read_csv('../data/singer_transcript_counts.csv', comment='#')
genes = ["Nanog", "Prdm14", "Rest", "Rex1"]
plots = [
bokeh_catplot.ecdf(
data=df[gene],
val=gene,
x_axis_label="mRNA count",
title=gene,
frame_height=150,
frame_width=200,
)
for gene in genes
]
bokeh.io.show(bokeh.layouts.gridplot(plots, ncols=2))
Note the difference in the \(x\)-axis scales. Clearly, prdm14 has far fewer mRNA copies than the other genes. The presence of two inflection points in the Rex1 EDCF implies bimodality.
Building a generative model¶
As we discussed in a lesson last term, we can model the transcript counts, which result from bursty gene expression, as being Negative Binomially distributed. For a given gene, the likelihood for the counts is
\begin{align} n_i \mid \alpha, b \sim \text{NegBinom}(\alpha, 1/b) \;\forall i, \end{align}
where \(\alpha\) is the burst frequency (higher \(\alpha\) means gene expression comes on more frequently) and \(b\) is the burst size, i.e., the typical number of transcripts made per burst. We have therefore identified the two parameters we need to estimate, \(\alpha\) and \(\beta\).
Because the Negative Binomial distribution is often parametrized in terms of \(\alpha\) and \(\beta= 1/b\), we can alternatively state our likelihood as
\begin{align} &\beta = 1/b,\\[1em] &n_i \mid \alpha, \beta \sim \text{NegBinom}(\alpha, \beta)\;\; \forall i. \end{align}
Given that we have a Negative Binomial likelihood, we are left to specify priors the burst size \(b\) and the burst frequency \(\alpha\). I would expect the time between bursts to be of order minutes, since that is a typical response time to signaling of a cell. This is of the same order of magnitude of an RNA lifetime, so I might then expect \(\alpha\) to be of order unity. I am not very sure about this, so I will choose a rather broad Log-Normal prior.
\begin{align} \alpha \sim \text{LogNorm}(0, 2). \end{align}
I would expect the burst size to depend on promoter strength and/or strength of transcriptional activators. I could imagine anywhere from a few to a thousand transcripts per burst. So, I will again choose a broad Log-Normal prior for \(b\).
\begin{align} b \sim \text{LogNorm}(2, 3). \end{align}
We then have the following model.
\begin{align} &\alpha \sim \text{LogNorm}(0,2), \\[1em] &b \sim \text{LogNorm}(2, 3), \\[1em] &\beta = 1/b,\\[1em] &n_i \sim \text{NegBinom}(\alpha, \beta) \;\forall i. \end{align}
Sampling the posterior¶
To draw samples out of the posterior, we need to use some new Stan syntax. Here is the Stan code we will use.
data {
int<lower=0> N;
int<lower=0> n[N];
}
parameters {
real<lower=0> alpha;
real<lower=0> b;
}
transformed parameters {
real beta_ = 1.0 / b;
}
model {
// Priors
alpha ~ lognormal(0.0, 2.0);
b ~ lognormal(2.0, 3.0);
// Likelihood
n ~ neg_binomial(alpha, beta_);
}
The
data
block contains the counts \(n\) of the mRNA transcripts. There are \(N\) cells that are measured. Mostdata
blocks look like this. There is an integer parameter that specifies the size of the data set, and then the data set is given as an array. Note that we specified a lower bound on the data (as we will do on the parameters) using the<lower=0>
syntax.The
parameters
block tell us what the parameters of the posterior are. In this case, we wish to sample out of the posterior \(g(\alpha, b \mid \mathbf{n})\), where \(mathbf{n}\) is the set of transcript counts for the gene. So, the two parameters are \(\alpha\) and \(b\). The sampler assumes that the variables listed in theparameters
block are those you wish to sample.The
transformed parameters
block allows you to do any transformation of the parameters you are sampling for convenience. In this case, Stan’s Negative Binomial distribution is parametrized by \(\beta = 1/b\), so we make the transformation of theb
tobeta_
. Notice that I have called this variablebeta_
and notbeta
. I did this becausebeta
is one of Stan’s distributions, and you should avoid naming a variable after a word that is already in the Stan language.Finally, the
model
block is where the model is specified. The syntax of the model block is almost identical to that of the hand-written model.
Now that we have specified our model, we can compile it.
[3]:
sm = cmdstanpy.CmdStanModel(stan_file='smfish.stan')
INFO:cmdstanpy:compiling c++
INFO:cmdstanpy:compiled model file: /Users/bois/Dropbox/git/bebi103_course/2020/b/content/lessons/lesson_04/smfish
Now, we just need to specify the data and let Stan’s sampler do the work! The data has to be passed in as a dictionary with keys corresponding to the variable names declared in the data
block of the Stan program. For this calculation, we will use the data set for the rest gene.
[4]:
data = dict(N=len(df), n=df["Rest"].values.astype(int))
# Sample using Stan
samples = sm.sample(
data=data,
chains=4,
sampling_iters=1000,
)
# Convert to ArviZ InferenceData instance
samples = az.from_cmdstanpy(posterior=samples)
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:start chain 2
INFO:cmdstanpy:finish chain 2
INFO:cmdstanpy:start chain 3
INFO:cmdstanpy:finish chain 1
INFO:cmdstanpy:start chain 4
INFO:cmdstanpy:finish chain 3
INFO:cmdstanpy:finish chain 4
Let’s take a quick look at the samples.
[5]:
samples.posterior
[5]:
<xarray.Dataset>
Dimensions: (chain: 4, draw: 1000)
Coordinates:
* chain (chain) int64 0 1 2 3
* draw (draw) int64 0 1 2 3 4 5 6 7 8 ... 992 993 994 995 996 997 998 999
Data variables:
alpha (chain, draw) float64 4.671 4.458 4.677 4.498 ... 4.503 4.325 4.092
b (chain, draw) float64 16.37 16.83 16.11 17.62 ... 16.23 17.76 18.37
beta_ (chain, draw) float64 0.06109 0.05942 0.06207 ... 0.0563 0.05443
Attributes:
created_at: 2020-01-25T21:09:35.155921
inference_library: cmdstanpy
inference_library_version: 0.8.0
As we have already seen, the samples are indexed by chain and draw. Parameters represented in the parameters
and transformed parameters
blocks are reported.
Plots of the samples¶
There are many ways of looking at the samples. In this case, since we have two parameters of interest, the pulse frequency and pulse size, we can plot the samples as a scatter plot to get the approximate density. For this kind of plot, HoloViews expects a Pandas data frame (or similar object). We can convert an xarray object into a data frame using the to_dataframe()
method.
[6]:
df_mcmc = samples.posterior.to_dataframe()
# Take a look
df_mcmc.head()
[6]:
alpha | b | beta_ | ||
---|---|---|---|---|
chain | draw | |||
0 | 0 | 4.67094 | 16.3686 | 0.061093 |
1 | 4.45757 | 16.8287 | 0.059422 | |
2 | 4.67678 | 16.1099 | 0.062074 | |
3 | 4.49842 | 17.6247 | 0.056739 | |
4 | 4.48813 | 17.2885 | 0.057842 |
The indexes from the xarray become indexes for the data frame and the parameter names are the columns. We can now use HoloViews to make our scatter plot. I will use transparency to help visualize the density of points.
[7]:
hv.Points(
data=df_mcmc,
kdims=[('alpha', 'α'), 'b']
).opts(
alpha=0.2,
size=2,
)
[7]:
We see very strong correlation between \(\alpha\) and \(b\). This does not necessarily mean that they depend on each other. Rather, it means that our degree of belief about their values depends on both in a correlated way. The measurements we made cannot effectively separate the effects of \(\alpha\) and \(b\) on the transcript counts.
Marginalizing the posterior¶
We can also plot the marginalized distributions. Remember that the marginalized distributions properly take into account the effects of the other variable, including the strong correlation I just mentioned. To obtain the marginalized distribution, we simply ignore the other distribution. It is convenient to look at the marginalized distributions as ECDFs.
[8]:
plots = [
bokeh_catplot.ecdf(df_mcmc, val=param, plot_height=200, plot_width=250)
for param in ["alpha", "b"]
]
bokeh.io.show(bokeh.layouts.gridplot(plots, ncols=2))
Alternatively, we can visualize the marginalized posterior PDFs as histograms. Because we have such a large number of samples, binning bias from histograms is less of a concern.
[9]:
plots = [
bokeh_catplot.histogram(df_mcmc, val=param, plot_height=200, plot_width=250)
for param in ["alpha", "b"]
]
bokeh.io.show(bokeh.layouts.gridplot(plots, ncols=2))
Analysis for all genes¶
We can do the same analysis for all genes. To do so, we input the data sets for each gene into the sampler and make our plot of the posterior. When we do the sampling, to avoid clutter on our screen, we can disable the logging that CmdStanPy sends by using the bebi103.stan.disable_logging()
context manager.
[10]:
plots = []
for gene in df.columns:
data = dict(N=len(df), n=df[gene].values.astype(int))
with bebi103.stan.disable_logging():
samples = sm.sample(data=data)
samples = az.from_cmdstanpy(posterior=samples)
df_mcmc = samples.posterior.to_dataframe()
plots.append(
hv.Points(data=df_mcmc, kdims=[("alpha", "α"), "b"], label=gene).opts(
alpha=0.05, axiswise=True, frame_height=200, frame_width=200, size=2
)
)
hv.Layout(plots).cols(2)
[10]:
Note that this single Negative Binomial model probably does not describe the Rex1 data, as can be seen from the ECDF of the measurements. Nonetheless, we can still assume the model is true and compute (i.e., sample) the posterior as if the model were true. This is always what we are doing when we perform parameter estimations. That said, we should seek more apt model for Rex1.
Display of “best fit”¶
After performing an MCMC calculation to access the posterior, we often want to visualize, for example, the ECDF of the measurements along with ECDFs predicted from the model. We will discuss methods for doing this in coming lessons when we discuss posterior predictive checks. For now, we will plot theoretical CDFs for parameter sets drawn from the posterior. First, we’ll grad the posterior samples again.
[11]:
# Re-obtain samples for rest
data = dict(N=len(df), n=df["Rest"].values.astype(int))
samples = sm.sample(
data=data,
chains=4,
sampling_iters=1000,
)
samples = az.from_cmdstanpy(posterior=samples)
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:start chain 2
INFO:cmdstanpy:finish chain 2
INFO:cmdstanpy:start chain 3
INFO:cmdstanpy:finish chain 1
INFO:cmdstanpy:start chain 4
INFO:cmdstanpy:finish chain 3
INFO:cmdstanpy:finish chain 4
And now we’ll get a plot of the ECDF.
[12]:
p = bokeh_catplot.ecdf(data=df['Rest'].values, x_axis_label='mRNA count')
We’ll generate a new CDFs for 100 sets of parameter values.
[13]:
# x-values and samples to use in plot
x = np.arange(251)
alphas = samples.posterior['alpha'].values.flatten()[::40]
betas = samples.posterior['beta_'].values.flatten()[::40]
for alpha, beta in zip(alphas, betas):
y = st.nbinom.cdf(x, alpha, beta/(1+beta))
x_plot, y_plot = bebi103.viz.cdf_to_staircase(x, y)
p.line(x_plot, y_plot, line_width=0.5, color='orange', level='underlay')
bokeh.io.show(p)
The measured CDF seems to be within reason given the model. This is not true for the Rex1 gene, however?
[14]:
# Re-obtain samples for rest
data = dict(N=len(df), n=df["Rex1"].values.astype(int))
samples = sm.sample(
data=data,
chains=4,
sampling_iters=1000,
)
samples = az.from_cmdstanpy(posterior=samples)
# Make ECDF
p = bokeh_catplot.ecdf(data=df['Rex1'].values, x_axis_label='mRNA count')
# x-values and samples to use in plot
x = np.arange(426)
alphas = samples.posterior['alpha'].values.flatten()[::40]
betas = samples.posterior['beta_'].values.flatten()[::40]
for alpha, beta in zip(alphas, betas):
y = st.nbinom.cdf(x, alpha, beta/(1+beta))
x_plot, y_plot = bebi103.viz.cdf_to_staircase(x, y)
p.line(x_plot, y_plot, line_width=0.5, color='orange', level='underlay')
bokeh.io.show(p)
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:start chain 2
INFO:cmdstanpy:finish chain 2
INFO:cmdstanpy:start chain 3
INFO:cmdstanpy:finish chain 1
INFO:cmdstanpy:start chain 4
INFO:cmdstanpy:finish chain 3
INFO:cmdstanpy:finish chain 4
The lesson here is that getting nicely identifiable parameter estimates does not mean that the model is good. Again, we will do more careful assessment of this when we do posterior predictive checks.
[15]:
bebi103.stan.clean_cmdstan()
Computing environment¶
[16]:
%load_ext watermark
%watermark -v -p numpy,scipy,pandas,cmdstanpy,arviz,bokeh,bokeh_catplot,holoviews,bebi103,jupyterlab
CPython 3.7.6
IPython 7.11.1
numpy 1.18.1
scipy 1.3.1
pandas 0.24.2
cmdstanpy 0.8.0
arviz 0.6.1
bokeh 1.4.0
bokeh_catplot 0.1.7
holoviews 1.12.7
bebi103 0.0.50
jupyterlab 1.2.5