<jupyter_start><jupyter_text>Maximum Likelihood and Applications in Astronomy<NAME> 2017 (based on lectures from <NAME> with material from <NAME> 2016,Ivezic [Sections 4.0, 4.1, 4.2.1-6, 4.3], Bevington, and Leighly).  Statistical InferenceStatistical *inference* is about drawing conclusions from data, specifically determining the properties of a population by data sampling.Three examples of inference are:1. What is the best estimate for a model parameter2. How confident we are about our result3. Are the data consistent with a particular model/hypothesis  Frequentist vs. Bayesian InferenceThere are two major statistical paradigms which address the statistical inference questions: the classical, or **frequentist** paradigm, and the **Bayesian** paradigm.While most of statistics and machine learning is based on the classical paradigm, Bayesian techniques are being embraced by the statistical and scientific communities at an ever-increasing pace.This week we discuss the three main types of statistical inference from the classical (frequentist) point of view.   Some Terminology* We typically study the properties of some ***population*** by measuring ***samples*** from that population. The population doesn't have to refer to different objects. E.g., we may be (re)measuring the position of an object at rest; the population is the distribution of (an infinite number of) measurements smeared by the uncertainty, and the sample are the measurement we've actually taken.* A ***statistic*** is any function of the sample. For example, the sample mean is a statistic. But also, "the value of the first measurement" is also a statistic.* To conclude something about the population from the sample, we develop ***estimators***. An estimator is a statistic, a rule for calculating an estimate of a given quantity based on observed data: thus the rule (the estimator), the quantity of interest (the estimand) and its result (the estimate) can be distinguished. Sometimes *estimator* and the *estimate* are used interchangeably. Much of frequentist statistics concerns itself with development of different estimation rules -- different estimators -- and proving their properties.* Many of these rules have been developed for efficiency and speed of the estimation and make assumptions (usually reasonable) about the properties of the population, model, and any measurement uncertainties (e.g. Gaussianity).* There are ***point*** and ***interval estimators***. The point estimators yield single-valued results (example: the position of an object), while with an interval estimator, the result would be a range of plausible values (example: confidence interval for the position of an object).* Measurements have **uncertainties** (not errors) and we need to account for these (sometimes they are unknown). Data are not variables but fixed values  Maximum Likelihood Estimation (MLE)Let's talk about maximum likelihood estimation ($\S 4.2$ in the textbook), which is relevant to both Bayesian and Frequentist approaches.  Maximum Likelihood ApproachMaximum likelihood estimation consists of the following conceptual steps:1. **Hypothesis**: Formulate a model, a *hypothesis*, about how the data are generated. For example, this could be a statement that the data are a measurement of some quantity that come with Gaussian random uncertainties (i.e., each measurement is equal to the true value, plus a deviation randomly drawn from the normal distribution). Models are typically described using a set of model parameters $\boldsymbol{\theta}$, and written as $\boldsymbol{M}(\boldsymbol{\theta})$.2. **Maximum Likelihood Estimation**: Search for the "best" model parameters $\boldsymbol{\theta}$ which maximize the ***likelihood*** $L(\boldsymbol{\theta}) \equiv p(D|M)$. This search yields the MLE *point estimates*, $\boldsymbol{\theta^0}$.3. **Quantifying Estimate Uncertainty**: Determine the confidence region for model parameters, $\boldsymbol{\theta^0}$. Such a confidence estimate can be obtained analytically (possibly with some approximations), but can also be done numerically for arbitrary models using general frequentist techniques, such as bootstrap, jackknife, and cross-validation.4. **Hypothesis Testing**: Perform hypothesis tests as needed to make other conclusions about models and point estimates. Possibly GOTO 1.While these steps represent a blueprint for the frequentist approach in general, the likelihood is just one of many possible so-called **objective functions** (also called **fitness functions**, or **cost functions**); other possibilities are explored briefly in §4.2.8 of the textbook.  Example: Measuring the Position of a QuasarLet's assume we wish to estimate the position $x$ of a quasar from a series of individual astrometric measurements.1. We adopt a model where the observed quasar does not move, and has individual measurement uncertainties 2. We derive the expression for the likelihood of there being a quasar at position $x_0$ that gives rise to our individual measurements. We find the value of $\hat x_0$ for which our observations are maximally likely.3. We determine the uncertainties (confidence intervals) on our measurement.4. We test whether what we've observed is consistent with our adopted model. For example, is it possible that the quasar was really a misidentified star with measurable proper motion?Note: in the text to come, I will use $\mu$ instead of $x_0$ to denote the true position of the quasar. This is to avoid potential confusion with the first (or zeroth) measurement of $x$.  The Likelihood Function**Write down the likelihood function for this case****Why did you choose the form you did? What assumption did you make?**  The Likelihood FunctionIf we know the distribution from which our data were drawn (or make a hypothesis about it), then we can compute the **probability** of our data being generated.For example, for the Gaussian distribution probablity of getting a specific value of $x$ is given by:$$p(x|\mu,\sigma) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right).$$<jupyter_code># Execute this cell
%matplotlib inline
import numpy as np
from scipy.stats import norm
from matplotlib import pyplot as plt

from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=15, usetex=True)

#------------------------------------------------------------
# plot the distributions
fig, ax = plt.subplots(figsize=(10, 7.5))
dist = norm(5, 1)
x = np.linspace(0, 10, 1000)
plt.plot(x, dist.pdf(x), c='black',label=r'$\mu=5,\ \sigma=1$')

plt.xlim(0, 10)
plt.ylim(0, 0.5)

plt.xlabel('$x$')
plt.ylabel(r'$p(x|\mu=5,\sigma=1)$')
plt.title('Probability of $x$')

plt.legend()
norm?<jupyter_output><empty_output><jupyter_text>The Likelihood FunctionIf we want to know the total probability of our *entire* data set (as opposed to one measurement) then we must compute the *product* of all the individual probabilities:$$L \equiv p(\{x_i\}|M(\theta)) = \prod_{i=1}^n p(x_i|M(\theta)),$$where $M$ refers to the *model* and $\theta$ refers collectively to the $k$ parameters of the model, which can generally be multi-dimensional. In words, this is ***the probability of the data given the model parameters***. Note we're assuming the individual measurements are independent of each other.If we consider $L$ as a function of the model parameters, we refer to it as the ***likelihood of the model parameters, given the observed data***. Note that while the components of $L$ may be normalized pdfs, their product is not.  Also the product can be very small, so we often take the log of $L$. We can write this out as$$L = \prod_{i=1}^n \frac{1}{\sigma\sqrt{2\pi}} \exp\left(\frac{-(x_i-\mu)^2}{2\sigma^2}\right),$$and simplify to$$L = \left( \prod_{i=1}^n \frac{1}{\sigma\sqrt{2\pi}} \right) \exp\left( -\frac{1}{2} \sum \left[\frac{-(x_i-\mu)}{\sigma} \right]^2 \right),$$where we have written the product of the exponentials as the exponential of the sum of the arguments, which will make things easier to deal with later.That is, we have done this: $$\prod_{i=1}^n A_i \exp(-B_i) = (A_iA_{i+1}\ldots A_n) \exp[-(B_i+B_{i+1}+\ldots+B_n)]$$ **NOTE**The Likelihood function is the joint probability density of all measurements. For each measurment we have a probablity density. These probability densities have **units**. They are the reciprical of the units of the measurement (as the integrated probability does not have units but the interval over which we are integrating does). For our case our positions might be in arcsecs so the probability density is in units of 1/arcsec. This means that the probability density is the rate of change in the probability per arcsec. For the Likelihood function we have the probability density of *n* measurements so the units for the likelihood is (1/arcsec)$^n$ The argument of the exponential is just$$\exp \left(-\frac{\chi^2}{2}\right).$$That is, for our Gaussian distribution$$\chi^2 = \sum_{i=1}^n \left ( \frac{x_i-\mu}{\sigma}\right)^2.$$So, maximizing the likelihood is the same as minimizing $\chi^2$.  The Core Idea Behind Maximum Likelihood EstimatorsLet's say that we know that some data were drawn from a Gaussian distribution, but we don't know the $\theta = (\mu,\sigma)$ values of that distribution (i.e., the parameters).Then Maximum Likelihood Estimation method tells us to think of the likelihood as a ***function of the unknown model parameters***, and ***find those that maximize the value of $L$***. Those will be our Maximum Likelihood Estimators for for the true values of the model.Simple as that!  MLE applied to a Homoscedastic GaussianLet's take a look at our astrometry example, using a model where all the measurements have the same uncertainty, drawn from a normal distribution, $N(0, \sigma)$.All uncertainties being the same is known as having **homoscedastic** uncertainties which just means "uniform uncertainties".  Later we will consider the case where the measurements can have different uncertainties ($\sigma_i$) which is called **heteroscedastic**. We have an experiment with the set of measured positions $D=\{x_i\}$ in 1D with Gaussian uncertainties, and therefore:$$L \equiv p(\{x_i\}|\mu,\sigma) = \prod_{i=1}^N \frac{1}{\sigma\sqrt{2\pi}} \exp\left(\frac{-(x_i-\mu)^2}{2\sigma^2}\right).$$Note that that is $p(\{x_i\})$ not $p(x_i)$, that is the probability of the full data set, not just one measurement. If $\sigma$ is both constant and *known*, then this is a one parameter model with $k=1$ and $\theta_1=\mu$.  **Note**For multidimensional distributions, as we will see later in the course, the uncertainties come in the form of a covariance matrix where there uncertainties can be correlated. This still assumes Gaussianity$$ p(D\; | \;  \pmb \theta\;) =  \prod_{k=1}^{n} \; \frac{1}{(2\pi)^{d/2} \; |\Sigma|^{1/2}} exp \bigg[ -\frac{1}{2}(\pmb x - \pmb \mu)^t \Sigma^{-1}(\pmb x - \pmb \mu) \bigg]$$where $\Sigma$ is the covariance matrix and $d$ is the dimensionality For practical reasons, it's better to work with the natural logarithm of the likelihood.We define the *log-likelihood function* as ${\rm lnL} = \ln[L(\theta)]$.  The maximum of this function happens at the same place as the maximum of $L$. Given all that, we have:$${\rm lnL} = {\rm constant} - \sum_{i=1}^N \frac{(x_i - \mu)^2}{2\sigma^2}.$$ We then determine the maximum in the same way that we always do.  It is the parameter set for which the derivative of ${\rm lnL}$ is zero:$$\frac{d\;{\rm lnL}(\mu)}{d\mu}\Biggr\rvert_{\hat \mu} \equiv 0.$$That gives $$ \sum_{i=1}^N \frac{(x_i - \hat \mu)}{\sigma^2} = 0.$$(note: we should also check that the $2^{\rm nd}$ derivative is negative, to ensure this is the *maximum* of $L$)(also note: any constants in $\ln L$ disappear when differentiated, so constant terms can typically be ignored.) Since $\sigma = {\rm constant}$, that says $$\sum_{i=1}^N x_i = \sum_{i=1}^N \hat \mu = N \hat \mu.$$Thus we find that$$\hat \mu = \frac{1}{N}\sum_{i=1}^N x_i,$$which is just the arithmetic mean of all the measurements.  The Sample Mean is an ML EstimatorThe mean of observations drawn from a $N(\mu, \sigma=const)$ distribution is a maximum-likelihood estimator of the distribution's $\mu$ parameter.We'd intuitively guess that (and we often do), but this derivation clarifies our choice: as an estimator of the real value of $\mu$, we adopt the value $\hat \mu$ with which it's maximally likely for the measured data set to occur.It also exposes the ***assumptions*** behind this conclusion; namely homoscedasticity and gaussianity of uncertainties. For example, if our uncertainties were Cauchy-distributed the mean (or any higher moment) is not defined  Properties of ML EstimatorsAssuming the data truly are drawn from the model, ML estimators have the following useful properties:* **They are consistent estimators**; that is, they can be proven to converge to the true parameter value as the number of data points increases.* **They are asymptotically normal estimators**. The distribution of the parameter estimate, as the number of data points increases to infinity, approaches a normal distribution, centered at the MLE, with a certain spread. This spread can often be easily calculated and used as a confidence band around the estimate, as discussed below (see eq. 4.7).* **They asymptotically achieve the theoretical minimum possible variance, called the Cramér–Rao bound**. In other words, they achieve the best possible uncertainty given the data at hand; that is, no other estimator can do better in terms of efficiently using each data point to reduce the total error of the estimate (see eq. 3.33 in the textbook).  Quantifying Estimate UncertaintyLet's simulate 10 measurements ${x_i}$ drawn from a Gaussian with $\mu = 5$ and $\sigma = 1$, and compute the ML estimator for $\mu$.<jupyter_code># Execute this cell
%matplotlib inline
import numpy as np
from scipy.stats import norm
from matplotlib import pyplot as plt

from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=15, usetex=True)

#------------------------------------------------------------
np.random.seed(seed=42)
Nsamples=1
measurements = np.random.normal(5, 1, Nsamples)
mu = np.average(measurements)

#------------------------------------------------------------
# plot the distributions
fig, ax = plt.subplots(figsize=(10, 7.5))
dist = norm(mu, 1)
C = (1./(2.*np.pi))**(10./2.)
x = np.linspace(0, 10, 1000)
plt.plot(x, C* dist.pdf(x), c='black',label=r'$\hat\mu=%.2f,\ \sigma=1$' % mu)
#plt.plot([159.9,160.1],[0,0.8], ls=ls, color='k', label=r'%s $\mu=%i' % (lab, mu))
plt.axvline(x=5)

plt.xlim(0, 10)
plt.ylim(0, 0.5*C)

plt.xlabel('$\mu$')
plt.ylabel(r'$L(\{x\}|\mu,\sigma=1)$')
plt.title('Likelihood of $\mu$')

plt.legend()<jupyter_output><empty_output><jupyter_text>Quantifying Estimate UncertaintyAs you've seen on in the previous plot, our ML estimate of $\mu$ is not perfect. The uncertaintly of the estimate is captured by the likelihood function.We *define* the uncertainty on our MLEs as second (partial) derivatives of log-likelihood:$$\sigma_{jk} = \left( - \frac{d^2}{d\theta_j} \frac{\ln L}{d\theta_k} \Biggr\rvert_{\theta=\hat \theta}\right)^{-1/2}.$$Taken together, these entries (more accurately, their squares) are know as the *covariance matrix*.This is the same as the **Fisher-information matrix** used to estimate the parameter uncertainities in cosmologyThe marginal error bars for each parameter, $\theta_i$ are given by the diagonal elements, $\sigma_{ii}$. These are the "error bars" that are typically quoted with each measurement. Off diagonal elements, $\sigma_{ij}$, arise from any correlation between the parameters in the model. In our example, the uncertainly on the mean is $$\sigma_{\mu} = \left( - \frac{d^2\ln L(\mu)}{d\mu^2}\Biggr\rvert_{\hat \mu}\right)^{-1/2}$$We find$$\frac{d^2\ln L(\mu)}{d\mu^2}\Biggr\rvert_{\hat \mu} = - \sum_{i=1}^N\frac{1}{\sigma^2} = -\frac{N}{\sigma^2},$$since, again, $\sigma = {\rm constant}$.  Then $$\sigma_{\mu} = \frac{\sigma}{\sqrt{N}}.$$So, our estimator of $\mu$ is $\overline{x}\pm\frac{\sigma}{\sqrt{N}}$, which is a result that you should be familiar with.  What is $\pm \sigma$? Errors as Gaussian Approximations to the Likelihood FunctionThe result for $\sigma_{\mu}$ has been derived by expanding $\ln L$ in a Taylor series and retaining terms up to second order (essentially, $\ln L$ is approximated by a parabola, or an ellipsoidal surface in multidimensional cases, around its maximum). If this expansion is exact (as is the case for a Gaussian error distribution), then we've completely captured the error information.In general, this is not the case and the likelihood surface can significantly deviate from a smooth elliptical surface. Furthermore, it often happens in practice that the likelihood surface is multimodal. It is always a good idea to visualize the likelihood surface when in doubt (see examples in §5.6 in the textbook).  What is $\pm \sigma$? Errors as Gaussian Approximations to the Likelihood FunctionThe $(\hat \mu - \sigma_\mu, \hat \mu + \sigma_\mu)$ range gives us a **confidence interval**.In frequentist interptetation, if we repeated the same measurement a hundred times, we'd find for 68 experiments the true value was within their computed confidence intervals ($1 \sigma$ errors).  MLE applied to a Heteroscedastic GaussianNow let's look a case where the uncertainties are heteroscedastic.  For example if we are measuring the length of a rod and have $N$ measurements, $\{x_i\}$, where the uncertainty for each measurement, $\sigma_i$ is known.  Since $\sigma$ is not a constant, then following the above, we have$$\ln L = {\rm constant} - \sum_{i=1}^N \frac{(x_i - \mu)^2}{2\sigma_i^2}.$$Taking the derivative:$$\frac{d\;{\rm lnL}(\mu)}{d\mu}\Biggr\rvert_{\hat \mu} = \sum_{i=1}^N \frac{(x_i - \hat \mu)}{\sigma_i^2} = 0,$$then simplifying:$$\sum_{i=1}^N \frac{x_i}{\sigma_i^2} = \sum_{i=1}^N \frac{\hat \mu}{\sigma_i^2},$$yields a MLE solution of $$\hat \mu = \frac{\sum_i^N (x_i/\sigma_i^2)}{\sum_i^N (1/\sigma_i^2)},$$with uncertainty$$\sigma_{\mu} = \left( \sum_{i=1}^N \frac{1}{\sigma_i^2}\right)^{-1/2}.$$  Goodness of FitThe MLE approach tells us what the "best" model parameters are, but not how good the fit actually is.  If the model is wrong, "best" might not be particularly revealing!  For example, if you have $N$ points drawn from a linear distribution, you can always fit the data perfectly with an $N-1$ order polynomial.  But that won't necessarily perfectly predict future measurements (see cross validation for how to estimate the number of parameters).We can describe the **goodness of fit** as whether or not it is likely to have obtained $\ln L_0$ by randomly drawing from the data.  That means that we need to know the *distribution* of $\ln L$.    Goodness of FitFor the Gaussian case we have just described, we can write$$z_i = (x_i-\mu)/\sigma,$$ then$$\ln L = {\rm constant} - \frac{1}{2}\sum_{i=1}^N z^2 = {\rm constant} - \frac{1}{2}\chi^2.$$So **$\ln L$ is distributed as $\chi^2$ (with $N-k$ degrees of freedom).**  Goodness of FitWhat does that tell us?The expectation value for the $\chi^2$ distribution is $N − k$ and its standard deviation is $\sqrt{2(N − k)}$. We typically have $N \gg k$ (where $N$ is the number of data points, and $k$ is the number of parameters in the model). When that holds, it becomes useful to define **$\chi^2$ per degree of freedom, $\chi^2_{dof}$**, as:$$\chi^2_{dof} = \frac{1}{N-k}\sum_{i=1}^N z^2_i.$$Therefore, for a good fit we would expect that $\chi^2_{dof}\approx 1$ (the expectation value).  If $\chi^2_{dof}$ is significantly larger than 1, then it is likely that we are not using the correct model.We can also get overly high or low values of $\chi^2_{dof}$ if our uncertainties are under- or over-estimated. This is particularly interesting when we have correlated uncertainties  Goodness of Fit: An Example![Ivezic, Figure 4.1](http://www.astroml.org/_images/fig_chi2_eval_1.png)  Working with non-Gaussian Likelihoods As an example of MLE with non-Gaussian probability density we can use the same formalism above for a Poisson distribution. In this case we write the probability disrtibution as$$p(x_k|\mu) = \frac{e^{-\theta}\theta^{x_k}}{x_k!}$$with $\mu$ the average number of events and $x_k$ is the number of events observedThis distribution is particularly useful for characterizing the number of soldiers in the Prussian army killed accidentally by horse kicksWe can then write the likelihood  as$$L \equiv p(\{x_k\}|\mu) = \prod_{k=1}^{n} \frac{e^{-\mu}\mu^{x_k}}{x_k!}$$and the lnL as$$lnL = \sum_{k=1}^{n} ln \bigg( \frac{e^{-\mu}\mu^{x_k}}{x_k!} \bigg)$$$$= \sum_{k=1}^{n} -\mu + x_k \; ln(\mu) - ln({x_k!})$$<jupyter_code>from scipy.stats import poisson
import numpy as np
import seaborn as sns

# generate samples for different values of mu
kpts=np.arange(0,25)
for mu, c in zip([1,3,12], sns.color_palette()[:4]):
    randomVariates = poisson.rvs(mu, size=1000)
    plt.hist(randomVariates, normed=True, color=c, alpha=0.2, bins=range(0,26), label='$\mu=' + np.str(mu) + '$')
    plt.plot(kpts, poisson.pmf(kpts, mu), '.', color=c)

plt.legend()
plt.title("Poisson Distribution")
plt.xlabel("Number of Events")
plt.ylabel("Normed Counts");<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12198901253697704, 'fraction_numerical': 0.012396112128468799, 'mean_word_length': 4.616561181434599, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '538716', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 6204, 'n_tokens_neox': 5769, 'n_words': 2806, 'path': 'lectures/Week-2-Thu.ipynb', 'repo_name': 'dirac-institute/uw-astr598-w18', 'size': '21309'}