From b599b4c94969ed4d320ad355800bcf22e69371ba Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 14 Sep 2026 22:27:56 +0100 Subject: [PATCH 1/2] docs: finish the math sweep, revive tutorial 3's priors, fix self.noise_map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three fixes to HowToFit chapter 1, following #58. The math sweep started in #58 now covers the rest of the chapter: tutorials 6, 7 and the optional Bayesian formalism tutorial move 12 display blocks off `\[ \]` and 68 inline spans off `\( \)` onto `$$ $$` and `$ $`, which Jupyter and Colab actually typeset. Conversion was AST-driven over module-level docstrings only; `tutorial_5_results_and_samples.py` keeps its single `\[`, which is a LaTeX row-break inside a Python string argument, not prose. Tutorial 3's `__Priors__` block set three priors on a model that all five fits then discarded by re-calling `af.Model(Gaussian)`, so it never applied — and two of the three were wrong: `normalization` `Uniform(0, 10)` excludes the true 25.0 and `sigma` `Uniform(0, 10)` puts the true 10.0 on the boundary. The five redundant re-creations are gone, so the block now takes effect. The prior values deliberately restate the `config/priors` defaults rather than narrowing them, because narrowing breaks the tutorial. The first MLE fit is meant to fail, and `af.LBFGS()` initialises with `InitializerBall(0.49, 0.51)` — a tight ball on the centre of each prior, not a broad random draw. Under a `normalization` of `Uniform(0, 50)` that centre is exactly 25.0, the true value, and the fit that teaches "MLE gets stuck in a local maximum" succeeded 10/10 runs at log likelihood 176.1. Measured: config priors fail 10/10, the narrowed candidate succeeds 10/10, the restated defaults fail 10/10 and reproduce the baseline local maximum exactly. The prose now explains why `normalization` wants a log-uniform prior and says plainly that these lines restate the defaults so the searched space is visible in the script. Separately, `Analysis.log_likelihood_function` in tutorials 3, 4 and 5 read a module-level `noise_map` global for its noise normalization while every other line in the method used `self.`. It returns the right number inside the tutorial only because that global happens to exist; this is the class the tutorials tell readers to copy into their own code, where it raises `NameError`. Now `self.noise_map`, matching tutorials 6 and 7. Closes #59 Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG --- .../tutorial_3_non_linear_search.ipynb | 45 +++++---- .../tutorial_4_why_modeling_is_hard.ipynb | 2 +- .../tutorial_5_results_and_samples.ipynb | 2 +- .../tutorial_6_gradients.ipynb | 56 ++++++----- .../tutorial_7_the_details.ipynb | 4 +- ...tutorial_optional_bayesian_formalism.ipynb | 98 +++++++++++-------- .../tutorial_3_non_linear_search.py | 43 ++++---- .../tutorial_4_why_modeling_is_hard.py | 2 +- .../tutorial_5_results_and_samples.py | 2 +- .../tutorial_6_gradients.py | 56 ++++++----- .../tutorial_7_the_details.py | 4 +- .../tutorial_optional_bayesian_formalism.py | 98 +++++++++++-------- 12 files changed, 235 insertions(+), 177 deletions(-) diff --git a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb index 1a47b47..d9e7c17 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb @@ -417,10 +417,21 @@ "parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the \n", "model fitting process towards parameter values that are more probable based on our prior understanding.\n", "\n", - "While we are using `UniformPriors` in this tutorial due to their simplicity, **PyAutoFit** offers various other \n", - "priors like `TruncatedGaussianPrior` and `LogUniformPrior`. These priors are useful for encoding different forms of prior \n", - "information, such as normally distributed values around a mean (`TruncatedGaussianPrior`) or parameters spanning multiple \n", - "orders of magnitude (`LogUniformPrior`)." + "Two of our three parameters use a `UniformPrior`, which says every value in the range is equally likely. The\n", + "`normalization` instead uses a `LogUniformPrior`, which says every *order of magnitude* in the range is equally\n", + "likely. This is the right choice for a parameter whose plausible values span many orders of magnitude: the\n", + "brightness of a signal might be 0.001 or 1000, and we have no reason before fitting to prefer one scale over\n", + "another. A `UniformPrior` from 0 to 1000000 would put essentially all of its probability above 100, whereas a\n", + "`LogUniformPrior` gives the range 0.01 to 0.1 the same weight as the range 100 to 1000.\n", + "\n", + "**PyAutoFit** offers other priors too, for example the `TruncatedGaussianPrior`, which encodes normally distributed\n", + "values around a mean and is useful when a previous fit has already told us roughly where a parameter lies.\n", + "\n", + "The three lines below set the priors explicitly on the model. They restate the `config/priors` defaults, so the\n", + "parameter space the searches below explore is exactly the one the config file already described. We write them\n", + "out anyway so that the API for changing a prior is visible, and so that the region of parameter space every fit\n", + "in this tutorial explores is stated plainly in the script rather than hidden in a configuration file. Change a\n", + "number below and every fit that follows searches a different space." ] }, { @@ -428,8 +439,8 @@ "metadata": {}, "source": [ "model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", - "model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=10.0)\n", - "model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=10.0)" + "model.normalization = af.LogUniformPrior(lower_limit=1e-6, upper_limit=1e6)\n", + "model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)" ], "outputs": [], "execution_count": null @@ -513,7 +524,7 @@ " residual_map = self.data - model_data\n", " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", " chi_squared = sum(chi_squared_map)\n", - " noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0))\n", + " noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0))\n", " log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", "\n", " return log_likelihood\n" @@ -606,8 +617,6 @@ " \"\"\"\n", ")\n", "\n", - "model = af.Model(Gaussian)\n", - "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", "print(\"The search has finished running - you may now continue the notebook.\")" @@ -706,8 +715,9 @@ "is higher. This process is known as \"initialization,\" and it involves providing the search with an \n", "appropriate \"starting point\" in parameter space.\n", "\n", - "The starting point is defined per parameter, so we create the model first and use its parameters as the keys of \n", - "the initializer. The values below are a deliberately imperfect guess at the true solution (`centre=50.0`, \n", + "The starting point is defined per parameter, so the keys of the initializer are the parameters of the `model` we\n", + "composed above, the same model (and therefore the same priors and the same parameter space) that the failed fit\n", + "used. The values below are a deliberately imperfect guess at the true solution (`centre=50.0`,\n", "`normalization=25.0`, `sigma=10.0`), but they are close enough for the search to climb the likelihood gradient to it." ] }, @@ -715,8 +725,6 @@ "cell_type": "code", "metadata": {}, "source": [ - "model = af.Model(Gaussian)\n", - "\n", "initializer = af.InitializerParamStartPoints(\n", " {\n", " model.centre: 52.0,\n", @@ -831,8 +839,6 @@ " \"\"\"\n", ")\n", "\n", - "model = af.Model(Gaussian)\n", - "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", "print(\"The search has finished running - you may now continue the notebook.\")\n", @@ -882,15 +888,16 @@ "small \"ball\" in parameter space, requiring a defined range for each parameter from which values are randomly drawn.\n", " \n", "2. We do not specify a starting point for the sigma parameter, allowing its initial values to be drawn from its \n", - "priors. This illustrates that with MCMC, it\u2019s not necessary to know a good starting point for every parameter." + "priors. This illustrates that with MCMC, it\u2019s not necessary to know a good starting point for every parameter.\n", + "\n", + "As with the MLE initializer above, the keys are the parameters of the `model` composed at the start of the tutorial,\n", + "so the priors set in the `__Priors__` section still define the space the walkers explore." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "model = af.Model(Gaussian)\n", - "\n", "initializer = af.InitializerParamBounds(\n", " {\n", " model.centre: (54.0, 56.0),\n", @@ -987,8 +994,6 @@ " \"\"\"\n", ")\n", "\n", - "model = af.Model(Gaussian)\n", - "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", "print(\"The search has finished running - you may now continue the notebook.\")\n", diff --git a/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb b/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb index 8d28320..a49399d 100644 --- a/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb @@ -354,7 +354,7 @@ " residual_map = self.data - model_data\n", " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", " chi_squared = sum(chi_squared_map)\n", - " noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0))\n", + " noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0))\n", " log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", "\n", " return log_likelihood\n", diff --git a/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb b/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb index 00c3c34..e39cbce 100644 --- a/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb @@ -200,7 +200,7 @@ " residual_map = self.data - model_data\n", " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", " chi_squared = sum(chi_squared_map)\n", - " noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0))\n", + " noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0))\n", " log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", "\n", " return log_likelihood\n", diff --git a/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb b/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb index 8989f49..b282e2f 100644 --- a/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb @@ -386,15 +386,17 @@ "different amount. One such number per parameter gives the \"gradient\", a vector pointing in the direction the log\n", "likelihood increases fastest, whose length says how steeply.\n", "\n", - "The gradient of a function \\( f \\) with respect to parameters \\( x, y, z \\) is written:\n", + "The gradient of a function $f$ with respect to parameters $x, y, z$ is written:\n", "\n", - "\\[ \\nabla f = \\left( \\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}, \\frac{\\partial f}{\\partial z} \\right) \\]\n", + "$$\n", + "\\nabla f = \\left( \\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}, \\frac{\\partial f}{\\partial z} \\right)\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( \\nabla f \\): the gradient, a vector with one entry per parameter.\n", - "- \\( \\partial f / \\partial x \\): the \"partial derivative\" of \\( f \\) with respect to \\( x \\), how much \\( f \\)\n", - " changes when \\( x \\) changes and everything else is held fixed.\n", + "- $\\nabla f$: the gradient, a vector with one entry per parameter.\n", + "- $\\partial f / \\partial x$: the \"partial derivative\" of $f$ with respect to $x$, how much $f$\n", + " changes when $x$ changes and everything else is held fixed.\n", "\n", "The gradient is a list of slopes, one per parameter, measured at the same point. A search which knows it does not\n", "have to guess which way to move, it can simply walk uphill!\n", @@ -513,7 +515,9 @@ "Our model has three parameters, so its gradient has three entries, one per slice of the kind we just drew, ordered\n", "as the parameter names we printed earlier:\n", "\n", - "\\[ \\left( \\frac{\\partial \\log L}{\\partial centre}, \\frac{\\partial \\log L}{\\partial normalization}, \\frac{\\partial \\log L}{\\partial \\sigma} \\right) \\]\n", + "$$\n", + "\\left( \\frac{\\partial \\log L}{\\partial centre}, \\frac{\\partial \\log L}{\\partial normalization}, \\frac{\\partial \\log L}{\\partial \\sigma} \\right)\n", + "$$\n", "\n", "The five-Gaussian model of tutorial 4 has a gradient with 15 entries; a lens model in astronomy might have 50. It\n", "always has as many entries as the model has free parameters, and always belongs to one specific point. Move to a\n", @@ -522,16 +526,18 @@ "__Finite Differencing__\n", "\n", "So how do we compute a gradient? The most direct way is the one we just used for the tangent line: nudge a parameter\n", - "by a small amount \\( h \\), evaluate the log likelihood, nudge it the other way, evaluate again, and take the\n", + "by a small amount $h$, evaluate the log likelihood, nudge it the other way, evaluate again, and take the\n", "difference. This is \"finite differencing\", in the \"central difference\" form:\n", "\n", - "\\[ \\frac{\\partial f}{\\partial x} \\approx \\frac{f(x + h) - f(x - h)}{2h} \\]\n", + "$$\n", + "\\frac{\\partial f}{\\partial x} \\approx \\frac{f(x + h) - f(x - h)}{2h}\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( h \\): the step size, a small number chosen by us.\n", - "- \\( f(x + h) \\): the log likelihood with the parameter increased by \\( h \\), everything else held fixed.\n", - "- \\( f(x - h) \\): the log likelihood with the parameter decreased by \\( h \\).\n", + "- $h$: the step size, a small number chosen by us.\n", + "- $f(x + h)$: the log likelihood with the parameter increased by $h$, everything else held fixed.\n", + "- $f(x - h)$: the log likelihood with the parameter decreased by $h$.\n", "\n", "In words: measure how much the function changed over a small interval and divide by the width of that interval.\n", "Below we write this out for all three parameters, returning a list of three slopes: a gradient." @@ -608,7 +614,7 @@ "values of 50.0, 25.0 and 10.0 that is sensible in two of the three parameters: the gradient is a local instruction,\n", "under no obligation to point straight at the peak.\n", "\n", - "There is a catch. We had to choose \\( h \\), and the answer depends on that choice. Below we compute the gradient\n", + "There is a catch. We had to choose $h$, and the answer depends on that choice. Below we compute the gradient\n", "with respect to `centre` for step sizes spanning ten orders of magnitude." ] }, @@ -632,10 +638,10 @@ "source": [ "The table shows the two failure modes of finite differencing, one at each end.\n", "\n", - "When \\( h \\) is too large, the two evaluations are so far apart that the line between them is not the slope at our\n", + "When $h$ is too large, the two evaluations are so far apart that the line between them is not the slope at our\n", "point at all, it is the average slope over a wide interval. The answer is \"biased\".\n", "\n", - "When \\( h \\) is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them\n", + "When $h$ is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them\n", "to about sixteen significant figures, so subtracting them keeps mostly round-off noise, which dividing by a tiny\n", "number then amplifies. The answer becomes erratic.\n", "\n", @@ -643,8 +649,8 @@ "depends on the units of the parameter, the scale of the data and the model, so it must be found by trial and error\n", "for every new problem. That is not a comfortable position to be in!\n", "\n", - "There is a second cost. Each parameter needs two evaluations, so a gradient for a model with \\( N \\) parameters\n", - "costs \\( 2N \\) evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of\n", + "There is a second cost. Each parameter needs two evaluations, so a gradient for a model with $N$ parameters\n", + "costs $2N$ evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of\n", "computation to work out which way to take one step.\n", "\n", "This is exactly what the `LBFGS` search of tutorial 3 was doing, silently, on your behalf. It \"evaluates the\n", @@ -710,7 +716,7 @@ "source": [ "The two gradients agree to several decimal places, the sanity check that matters: autodiff computes the same\n", "quantity we computed by hand, exactly and in one pass rather than approximately and in six. Where they disagree it\n", - "is the finite-difference answer that is wrong, because it carries the error we chose when we picked \\( h \\).\n", + "is the finite-difference answer that is wrong, because it carries the error we chose when we picked $h$.\n", "\n", "JAX has a second trick. `jax.jit` compiles a function into optimised machine code the first time it is called and\n", "reuses that code on every subsequent call, so for a search calling the likelihood thousands of times a one-off\n", @@ -751,7 +757,7 @@ "We now have gradients. Let us give them to the three families of search we met in tutorial 3.\n", "\n", "We start with `LBFGS`, passing it the NumPy analysis, because `LBFGS` cannot use JAX gradients: it estimates the\n", - "gradient itself by finite differencing, exactly as we did by hand, so every iteration costs \\( 2N + 1 \\)\n", + "gradient itself by finite differencing, exactly as we did by hand, so every iteration costs $2N + 1$\n", "evaluations. It also starts from a single point, the centre of the priors. In tutorial 3 that was enough to trap it\n", "in a local maximum; with the wider priors here it does better, but a single walker walking uphill can still only\n", "find the peak it happens to be standing on." @@ -1103,14 +1109,16 @@ "For several parameters the second derivatives form a matrix called the \"Hessian\", which `jax.hessian` computes by\n", "the same autodiff machinery as `jax.grad`. The errors follow from:\n", "\n", - "\\[ C = -H^{-1}, \\qquad \\sigma_{i} = \\sqrt{C_{ii}} \\]\n", + "$$\n", + "C = -H^{-1}, \\qquad \\sigma_{i} = \\sqrt{C_{ii}}\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( H \\): the Hessian, the matrix of second derivatives of the log likelihood at the peak.\n", - "- \\( C \\): the covariance matrix, the negative inverse of the Hessian.\n", - "- \\( \\sigma_{i} \\): the 1 sigma error on parameter \\( i \\), the square root of the \\( i \\)th diagonal entry\n", - " of \\( C \\).\n", + "- $H$: the Hessian, the matrix of second derivatives of the log likelihood at the peak.\n", + "- $C$: the covariance matrix, the negative inverse of the Hessian.\n", + "- $\\sigma_{i}$: the 1 sigma error on parameter $i$, the square root of the $i$th diagonal entry\n", + " of $C$.\n", "\n", "In words: invert the curvature, flip its sign, and the square roots of its diagonal are the errors. We evaluate this\n", "at the maximum likelihood vector found by `Nautilus`." @@ -1227,7 +1235,7 @@ "point, pointing in the direction the likelihood increases fastest.\n", "\n", "2. **Finite differencing versus autodiff**: a gradient can be estimated by nudging each parameter and re-evaluating,\n", - "but this costs \\( 2N \\) evaluations and forces a step size which is biased if too large and noisy if too small.\n", + "but this costs $2N$ evaluations and forces a step size which is biased if too large and noisy if too small.\n", "Autodiff applies the chain rule to the operations the likelihood performs, giving the exact gradient for a small fixed\n", "multiple of the cost of one evaluation, whatever the number of parameters.\n", "\n", diff --git a/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb index f9c61b0..eace05a 100644 --- a/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb @@ -1168,7 +1168,9 @@ "independent. Suppose the narrow component is an instrumental effect blurred into the broad one, so the width we\n", "want for the broad component is what is left after the narrow one is removed in quadrature:\n", "\n", - "\\[ \\sigma_{\\rm halo} = \\sqrt{\\sigma_{1}^2 - \\sigma_{0}^2} \\]\n", + "$$\n", + "\\sigma_{\\rm halo} = \\sqrt{\\sigma_{1}^2 - \\sigma_{0}^2}\n", + "$$\n", "\n", "Where:\n", "\n", diff --git a/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb index ba26409..216a7eb 100644 --- a/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb @@ -42,31 +42,33 @@ "\n", "Here is the equation that every tutorial in this chapter has been solving without ever writing it down:\n", "\n", - "\\[ P(\\theta \\mid D) = \\frac{P(D \\mid \\theta)\\,P(\\theta)}{P(D)} \\]\n", + "$$\n", + "P(\\theta \\mid D) = \\frac{P(D \\mid \\theta)\\,P(\\theta)}{P(D)}\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( \\theta \\): the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`.\n", + "- $\\theta$: the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`.\n", "\n", - "- \\( D \\): the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map.\n", + "- $D$: the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map.\n", "\n", - "- \\( P(\\theta \\mid D) \\): the \"posterior\", the probability of the parameters given the data, and the quantity we\n", + "- $P(\\theta \\mid D)$: the \"posterior\", the probability of the parameters given the data, and the quantity we\n", " actually want.\n", "\n", - "- \\( P(D \\mid \\theta) \\): the \"likelihood\", the probability of the data given the parameters, computed by the\n", + "- $P(D \\mid \\theta)$: the \"likelihood\", the probability of the data given the parameters, computed by the\n", " `log_likelihood_function` of tutorial 3 before we take its logarithm.\n", "\n", - "- \\( P(\\theta) \\): the \"prior\", the probability we assign to parameter values before looking at the data, the\n", + "- $P(\\theta)$: the \"prior\", the probability we assign to parameter values before looking at the data, the\n", " `UniformPrior` and `LogUniformPrior` objects of tutorial 3.\n", "\n", - "- \\( P(D) \\): the \"evidence\", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5.\n", + "- $P(D)$: the \"evidence\", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5.\n", "\n", "In plain words: the answer we want is the goodness-of-fit multiplied by our prior beliefs, divided by a normalizing\n", "number. Every algorithm in this chapter is a strategy for evaluating the right hand side without ever computing the\n", - "integral hiding inside \\( P(D) \\).\n", + "integral hiding inside $P(D)$.\n", "\n", - "Each tutorial supplied exactly one piece. Tutorial 1 built \\( \\theta \\) and the forward model. Tutorial 2 built\n", - "\\( P(D \\mid \\theta) \\), calling it the log likelihood. Tutorial 3 built \\( P(\\theta) \\) and the searches which\n", + "Each tutorial supplied exactly one piece. Tutorial 1 built $\\theta$ and the forward model. Tutorial 2 built\n", + "$P(D \\mid \\theta)$, calling it the log likelihood. Tutorial 3 built $P(\\theta)$ and the searches which\n", "explore the product of the two. Tutorial 4 showed what goes wrong when the posterior has more than one peak,\n", "tutorial 5 read the answer back out, and tutorials 6 and 7 differentiated it and asked what the numbers mean.\n", "\n", @@ -186,12 +188,12 @@ "source": [ "__The Model__\n", "\n", - "The symbol \\( \\theta \\) is nothing more exotic than the list of numbers you passed to `instance_from_vector` in\n", + "The symbol $\\theta$ is nothing more exotic than the list of numbers you passed to `instance_from_vector` in\n", "tutorial 1. Bayes' theorem is a statement about a probability distribution over that list, and nothing else.\n", "\n", "We therefore begin as tutorial 1 did, by re-pasting the `Gaussian` class in full. Its constructor arguments are the\n", - "entries of \\( \\theta \\), and its `model_data_from` method is the forward model: the function which, given\n", - "\\( \\theta \\), predicts what the data should look like." + "entries of $\\theta$, and its `model_data_from` method is the forward model: the function which, given\n", + "$\\theta$, predicts what the data should look like." ] }, { @@ -258,7 +260,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Composing the model gives the two pieces of book-keeping which make \\( \\theta \\) concrete. The `prior_count` is the\n", + "Composing the model gives the two pieces of book-keeping which make $\\theta$ concrete. The `prior_count` is the\n", "number of dimensions the posterior is a distribution over, and `paths` gives the order of the entries in the vector." ] }, @@ -278,7 +280,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A specific \\( \\theta \\) becomes a model, and the model becomes predicted data, in the two lines below. This is the\n", + "A specific $\\theta$ becomes a model, and the model becomes predicted data, in the two lines below. This is the\n", "forward modelling of tutorial 1, and it is what lets us ask \"how probable is the data, given these parameters?\"." ] }, @@ -323,25 +325,29 @@ "We assume each data point is its predicted value plus a random draw from a Gaussian of width equal to that point's\n", "noise. The probability of the whole dataset is then a product of one Gaussian probability per data point:\n", "\n", - "\\[ P(D \\mid \\theta) = \\prod_i \\frac{1}{\\sqrt{2\\pi\\sigma_i^2}} \\exp\\left(-\\frac{(d_i - m_i)^2}{2\\sigma_i^2}\\right) \\]\n", + "$$\n", + "P(D \\mid \\theta) = \\prod_i \\frac{1}{\\sqrt{2\\pi\\sigma_i^2}} \\exp\\left(-\\frac{(d_i - m_i)^2}{2\\sigma_i^2}\\right)\n", + "$$\n", "\n", "Taking the logarithm turns that product into a sum:\n", "\n", - "\\[ \\ln P(D \\mid \\theta) = -\\frac{1}{2} \\sum_i \\frac{(d_i - m_i)^2}{\\sigma_i^2} - \\frac{1}{2} \\sum_i \\ln(2\\pi\\sigma_i^2) \\]\n", + "$$\n", + "\\ln P(D \\mid \\theta) = -\\frac{1}{2} \\sum_i \\frac{(d_i - m_i)^2}{\\sigma_i^2} - \\frac{1}{2} \\sum_i \\ln(2\\pi\\sigma_i^2)\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( d_i \\): the value of the data at point \\( i \\), the `data` array.\n", + "- $d_i$: the value of the data at point $i$, the `data` array.\n", "\n", - "- \\( m_i \\): the value of the model data at point \\( i \\), computed by `model_data_from` for this \\( \\theta \\).\n", + "- $m_i$: the value of the model data at point $i$, computed by `model_data_from` for this $\\theta$.\n", "\n", - "- \\( \\sigma_i \\): the noise at point \\( i \\), the `noise_map` array.\n", + "- $\\sigma_i$: the noise at point $i$, the `noise_map` array.\n", "\n", "Compare the second equation with tutorial 2 line by line. The first sum is the `chi_squared`, and the second is the\n", "`noise_normalization`, the log of the product of the Gaussian prefactors. Both are multiplied by -0.5, which is\n", "where the mysterious factor comes from: it is not a convention, it is the 2 in the denominator of the exponent of a\n", "Gaussian. The noise normalization really is a constant, because it depends only on the noise-map and never on\n", - "\\( \\theta \\), so it shifts every log likelihood equally and can never change which model wins.\n", + "$\\theta$, so it shifts every log likelihood equally and can never change which model wins.\n", "\n", "Below we compute the log likelihood twice: by tutorial 2's chi-squared route, and by summing the log of a Gaussian\n", "probability density at every data point using `scipy`. They are the same number." @@ -374,14 +380,14 @@ "__The Prior__\n", "\n", "The priors of tutorial 3 were introduced as a way of telling the search where to look. Formally they are\n", - "\\( P(\\theta) \\), a probability distribution over the parameters written down before we look at the data. Because our\n", + "$P(\\theta)$, a probability distribution over the parameters written down before we look at the data. Because our\n", "parameters are independent, the prior is a product of one distribution per parameter and its logarithm is a sum,\n", - "\\( \\ln P(\\theta) = \\sum_j \\ln P(\\theta_j) \\).\n", + "$\\ln P(\\theta) = \\sum_j \\ln P(\\theta_j)$.\n", "\n", "The two priors on the default `Gaussian` model have simple forms. A `UniformPrior` is constant inside its limits and\n", "zero outside them, so its log is a constant we may set to zero inside and negative infinity outside. A\n", - "`LogUniformPrior` is proportional to \\( 1 / \\theta_j \\), the statement \"every order of magnitude is equally likely\",\n", - "so its log falls off as \\( -\\ln \\theta_j \\).\n", + "`LogUniformPrior` is proportional to $1 / \\theta_j$, the statement \"every order of magnitude is equally likely\",\n", + "so its log falls off as $-\\ln \\theta_j$.\n", "\n", "**PyAutoFit** hands you those numbers directly. Below we print the priors of the model, then evaluate the log prior\n", "of each parameter inside the prior limits, and then for a `centre` of 150.0 which lies outside the `UniformPrior`\n", @@ -434,7 +440,7 @@ "The first entry of the second list is `-inf`, an infinitely improbable model. This is the formal version of tutorial\n", "3's statement that priors define the valid parameter space: a model outside the priors is not penalised, it is\n", "excluded. The middle entry is not zero, because the `LogUniformPrior` on `normalization` prefers smaller values and\n", - "\\( -\\ln(25) \\) is about -3.2.\n", + "$-\\ln(25)$ is about -3.2.\n", "\n", "Priors enter a fit a second way, and it is how nested sampling works. Every prior can be inverted: instead of asking\n", "\"how probable is this value?\", we ask \"which value sits at this fraction of the distribution?\". That inverse is the\n", @@ -472,7 +478,7 @@ "This is the key to a sentence in tutorial 3 which may have seemed arbitrary: nested sampling \"draws live points from\n", "the priors\". A search which picks unit values uniformly at random between 0 and 1 and passes them through\n", "`value_for` is drawing samples from the prior distribution itself. It is also why a nested sampling search cannot be\n", - "given a starting point: its first step is defined to be a draw from \\( P(\\theta) \\).\n", + "given a starting point: its first step is defined to be a draw from $P(\\theta)$.\n", "\n", "__The Posterior__\n", "\n", @@ -547,14 +553,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a \\( \\theta \\) the search\n", + "The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a $\\theta$ the search\n", "accepted, and each entry of `weight_list` says how much that sample counts when the posterior is summed up. Together\n", - "they approximate \\( P(\\theta \\mid D) \\): a cloud of points, denser where the posterior is higher.\n", + "they approximate $P(\\theta \\mid D)$: a cloud of points, denser where the posterior is higher.\n", "\n", "Tutorial 5 also told you, without justification, that the log posterior is the log likelihood plus the log prior.\n", "That is Bayes' theorem logged, with the evidence dropped because it is the same number for every sample:\n", "\n", - "\\[ \\ln P(\\theta \\mid D) = \\ln P(D \\mid \\theta) + \\ln P(\\theta) - \\ln P(D) \\]\n", + "$$\n", + "\\ln P(\\theta \\mid D) = \\ln P(D \\mid \\theta) + \\ln P(\\theta) - \\ln P(D)\n", + "$$\n", "\n", "Below we check the first few samples, printing the log likelihood, log prior, log posterior, and the difference\n", "between the log posterior and the sum of the first two." @@ -599,10 +607,10 @@ "There are two \"best-fit\" models hiding in a set of samples, and tutorial 5 printed both without saying they could\n", "disagree:\n", "\n", - "- The \"maximum likelihood\" model, `samples.max_log_likelihood()`, is the \\( \\theta \\) fitting the data best,\n", + "- The \"maximum likelihood\" model, `samples.max_log_likelihood()`, is the $\\theta$ fitting the data best,\n", " ignoring the priors entirely.\n", "\n", - "- The \"maximum a posteriori\" model, usually shortened to MAP, `samples.max_log_posterior()`, is the \\( \\theta \\)\n", + "- The \"maximum a posteriori\" model, usually shortened to MAP, `samples.max_log_posterior()`, is the $\\theta$\n", " which maximizes likelihood times prior.\n", "\n", "If every prior is uniform the log prior is the same constant inside the limits, so the two are the same model. They\n", @@ -638,13 +646,15 @@ "`aplt.corner_cornerpy`. That requires an operation with a formal name, \"marginalization\", which means integrating\n", "the posterior over the parameters you are not currently interested in:\n", "\n", - "\\[ P(\\theta_1 \\mid D) = \\int P(\\theta \\mid D) \\, d\\theta_2 \\, d\\theta_3 \\ldots \\]\n", + "$$\n", + "P(\\theta_1 \\mid D) = \\int P(\\theta \\mid D) \\, d\\theta_2 \\, d\\theta_3 \\ldots\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( \\theta_1 \\): the parameter we want a one-dimensional answer for, for example `centre`.\n", + "- $\\theta_1$: the parameter we want a one-dimensional answer for, for example `centre`.\n", "\n", - "- \\( \\theta_2, \\theta_3, \\ldots \\): every other parameter of the model, integrated away.\n", + "- $\\theta_2, \\theta_3, \\ldots$: every other parameter of the model, integrated away.\n", "\n", "That integral looks intimidating, and done analytically it would be. This is the greatest practical advantage of\n", "having samples: marginalizing them means ignoring the columns you do not care about and histogramming the one you\n", @@ -696,16 +706,18 @@ "source": [ "__The Evidence__\n", "\n", - "The one term of Bayes' theorem we have ignored is the denominator, \\( P(D) \\), the evidence. It is the integral of\n", + "The one term of Bayes' theorem we have ignored is the denominator, $P(D)$, the evidence. It is the integral of\n", "the numerator over the whole of parameter space:\n", "\n", - "\\[ P(D) = \\int P(D \\mid \\theta) \\, P(\\theta) \\, d\\theta \\]\n", + "$$\n", + "P(D) = \\int P(D \\mid \\theta) \\, P(\\theta) \\, d\\theta\n", + "$$\n", "\n", "Where:\n", "\n", "- The integral runs over every value of every parameter the priors allow.\n", "\n", - "Two facts about this integral explain a lot of what you have seen. First, it does not depend on \\( \\theta \\), which\n", + "Two facts about this integral explain a lot of what you have seen. First, it does not depend on $\\theta$, which\n", "is why MCMC never needs it: a walker deciding whether to move compares posteriors as a ratio and the evidence\n", "cancels. Second, it is genuinely hard, an integral over a many-dimensional space in which almost all of the volume\n", "contributes almost nothing.\n", @@ -742,14 +754,16 @@ "automatic differentiation. In this notation, what the gradient searches climb is the derivative of the log\n", "posterior:\n", "\n", - "\\[ \\nabla_\\theta \\ln P(\\theta \\mid D) = \\nabla_\\theta \\ln P(D \\mid \\theta) + \\nabla_\\theta \\ln P(\\theta) \\]\n", + "$$\n", + "\\nabla_\\theta \\ln P(\\theta \\mid D) = \\nabla_\\theta \\ln P(D \\mid \\theta) + \\nabla_\\theta \\ln P(\\theta)\n", + "$$\n", "\n", "Where:\n", "\n", - "- \\( \\nabla_\\theta \\): the vector of derivatives with respect to each parameter in turn.\n", + "- $\\nabla_\\theta$: the vector of derivatives with respect to each parameter in turn.\n", "\n", - "The evidence has vanished, and its disappearance is the point. Because \\( \\ln P(D) \\) does not depend on\n", - "\\( \\theta \\), differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which\n", + "The evidence has vanished, and its disappearance is the point. Because $\\ln P(D)$ does not depend on\n", + "$\\theta$, differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which\n", "only ever looks at slopes.\n", "\n", "This is the formal reason gradient methods scale so well. Hamiltonian Monte Carlo and its self-tuning variant NUTS,\n", diff --git a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py index cd3c4cb..ff817a7 100644 --- a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py +++ b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py @@ -309,14 +309,25 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the model fitting process towards parameter values that are more probable based on our prior understanding. -While we are using `UniformPriors` in this tutorial due to their simplicity, **PyAutoFit** offers various other -priors like `TruncatedGaussianPrior` and `LogUniformPrior`. These priors are useful for encoding different forms of prior -information, such as normally distributed values around a mean (`TruncatedGaussianPrior`) or parameters spanning multiple -orders of magnitude (`LogUniformPrior`). +Two of our three parameters use a `UniformPrior`, which says every value in the range is equally likely. The +`normalization` instead uses a `LogUniformPrior`, which says every *order of magnitude* in the range is equally +likely. This is the right choice for a parameter whose plausible values span many orders of magnitude: the +brightness of a signal might be 0.001 or 1000, and we have no reason before fitting to prefer one scale over +another. A `UniformPrior` from 0 to 1000000 would put essentially all of its probability above 100, whereas a +`LogUniformPrior` gives the range 0.01 to 0.1 the same weight as the range 100 to 1000. + +**PyAutoFit** offers other priors too, for example the `TruncatedGaussianPrior`, which encodes normally distributed +values around a mean and is useful when a previous fit has already told us roughly where a parameter lies. + +The three lines below set the priors explicitly on the model. They restate the `config/priors` defaults, so the +parameter space the searches below explore is exactly the one the config file already described. We write them +out anyway so that the API for changing a prior is visible, and so that the region of parameter space every fit +in this tutorial explores is stated plainly in the script rather than hidden in a configuration file. Change a +number below and every fit that follows searches a different space. """ model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) -model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) -model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) +model.normalization = af.LogUniformPrior(lower_limit=1e-6, upper_limit=1e6) +model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) """ __Analysis__ @@ -389,7 +400,7 @@ def log_likelihood_function(self, instance) -> float: residual_map = self.data - model_data chi_squared_map = (residual_map / self.noise_map) ** 2.0 chi_squared = sum(chi_squared_map) - noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0)) + noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0)) log_likelihood = -0.5 * (chi_squared + noise_normalization) return log_likelihood @@ -450,8 +461,6 @@ def log_likelihood_function(self, instance) -> float: """ ) -model = af.Model(Gaussian) - result = search.fit(model=model, analysis=analysis) print("The search has finished running - you may now continue the notebook.") @@ -511,12 +520,11 @@ def log_likelihood_function(self, instance) -> float: is higher. This process is known as "initialization," and it involves providing the search with an appropriate "starting point" in parameter space. -The starting point is defined per parameter, so we create the model first and use its parameters as the keys of -the initializer. The values below are a deliberately imperfect guess at the true solution (`centre=50.0`, +The starting point is defined per parameter, so the keys of the initializer are the parameters of the `model` we +composed above, the same model (and therefore the same priors and the same parameter space) that the failed fit +used. The values below are a deliberately imperfect guess at the true solution (`centre=50.0`, `normalization=25.0`, `sigma=10.0`), but they are close enough for the search to climb the likelihood gradient to it. """ -model = af.Model(Gaussian) - initializer = af.InitializerParamStartPoints( { model.centre: 52.0, @@ -609,8 +617,6 @@ def log_likelihood_function(self, instance) -> float: """ ) -model = af.Model(Gaussian) - result = search.fit(model=model, analysis=analysis) print("The search has finished running - you may now continue the notebook.") @@ -655,9 +661,10 @@ def log_likelihood_function(self, instance) -> float: 2. We do not specify a starting point for the sigma parameter, allowing its initial values to be drawn from its priors. This illustrates that with MCMC, it’s not necessary to know a good starting point for every parameter. -""" -model = af.Model(Gaussian) +As with the MLE initializer above, the keys are the parameters of the `model` composed at the start of the tutorial, +so the priors set in the `__Priors__` section still define the space the walkers explore. +""" initializer = af.InitializerParamBounds( { model.centre: (54.0, 56.0), @@ -732,8 +739,6 @@ def log_likelihood_function(self, instance) -> float: """ ) -model = af.Model(Gaussian) - result = search.fit(model=model, analysis=analysis) print("The search has finished running - you may now continue the notebook.") diff --git a/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py b/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py index 39a0b34..7e078fa 100644 --- a/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py +++ b/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py @@ -252,7 +252,7 @@ def log_likelihood_function(self, instance) -> float: residual_map = self.data - model_data chi_squared_map = (residual_map / self.noise_map) ** 2.0 chi_squared = sum(chi_squared_map) - noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0)) + noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0)) log_likelihood = -0.5 * (chi_squared + noise_normalization) return log_likelihood diff --git a/scripts/chapter_1_introduction/tutorial_5_results_and_samples.py b/scripts/chapter_1_introduction/tutorial_5_results_and_samples.py index 2f47cb5..d015f9f 100644 --- a/scripts/chapter_1_introduction/tutorial_5_results_and_samples.py +++ b/scripts/chapter_1_introduction/tutorial_5_results_and_samples.py @@ -119,7 +119,7 @@ def log_likelihood_function(self, instance): residual_map = self.data - model_data chi_squared_map = (residual_map / self.noise_map) ** 2.0 chi_squared = sum(chi_squared_map) - noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0)) + noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0)) log_likelihood = -0.5 * (chi_squared + noise_normalization) return log_likelihood diff --git a/scripts/chapter_1_introduction/tutorial_6_gradients.py b/scripts/chapter_1_introduction/tutorial_6_gradients.py index f6c7bcd..94746c3 100644 --- a/scripts/chapter_1_introduction/tutorial_6_gradients.py +++ b/scripts/chapter_1_introduction/tutorial_6_gradients.py @@ -268,15 +268,17 @@ def log_likelihood_function(self, instance) -> float: different amount. One such number per parameter gives the "gradient", a vector pointing in the direction the log likelihood increases fastest, whose length says how steeply. -The gradient of a function \( f \) with respect to parameters \( x, y, z \) is written: +The gradient of a function $f$ with respect to parameters $x, y, z$ is written: -\[ \nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right) \] +$$ +\nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right) +$$ Where: -- \( \nabla f \): the gradient, a vector with one entry per parameter. -- \( \partial f / \partial x \): the "partial derivative" of \( f \) with respect to \( x \), how much \( f \) - changes when \( x \) changes and everything else is held fixed. +- $\nabla f$: the gradient, a vector with one entry per parameter. +- $\partial f / \partial x$: the "partial derivative" of $f$ with respect to $x$, how much $f$ + changes when $x$ changes and everything else is held fixed. The gradient is a list of slopes, one per parameter, measured at the same point. A search which knows it does not have to guess which way to move, it can simply walk uphill! @@ -362,7 +364,9 @@ def log_likelihood_function(self, instance) -> float: Our model has three parameters, so its gradient has three entries, one per slice of the kind we just drew, ordered as the parameter names we printed earlier: -\[ \left( \frac{\partial \log L}{\partial centre}, \frac{\partial \log L}{\partial normalization}, \frac{\partial \log L}{\partial \sigma} \right) \] +$$ +\left( \frac{\partial \log L}{\partial centre}, \frac{\partial \log L}{\partial normalization}, \frac{\partial \log L}{\partial \sigma} \right) +$$ The five-Gaussian model of tutorial 4 has a gradient with 15 entries; a lens model in astronomy might have 50. It always has as many entries as the model has free parameters, and always belongs to one specific point. Move to a @@ -371,16 +375,18 @@ def log_likelihood_function(self, instance) -> float: __Finite Differencing__ So how do we compute a gradient? The most direct way is the one we just used for the tangent line: nudge a parameter -by a small amount \( h \), evaluate the log likelihood, nudge it the other way, evaluate again, and take the +by a small amount $h$, evaluate the log likelihood, nudge it the other way, evaluate again, and take the difference. This is "finite differencing", in the "central difference" form: -\[ \frac{\partial f}{\partial x} \approx \frac{f(x + h) - f(x - h)}{2h} \] +$$ +\frac{\partial f}{\partial x} \approx \frac{f(x + h) - f(x - h)}{2h} +$$ Where: -- \( h \): the step size, a small number chosen by us. -- \( f(x + h) \): the log likelihood with the parameter increased by \( h \), everything else held fixed. -- \( f(x - h) \): the log likelihood with the parameter decreased by \( h \). +- $h$: the step size, a small number chosen by us. +- $f(x + h)$: the log likelihood with the parameter increased by $h$, everything else held fixed. +- $f(x - h)$: the log likelihood with the parameter decreased by $h$. In words: measure how much the function changed over a small interval and divide by the width of that interval. Below we write this out for all three parameters, returning a list of three slopes: a gradient. @@ -436,7 +442,7 @@ def gradient_via_finite_difference_from(vector, h=1.0e-3): values of 50.0, 25.0 and 10.0 that is sensible in two of the three parameters: the gradient is a local instruction, under no obligation to point straight at the peak. -There is a catch. We had to choose \( h \), and the answer depends on that choice. Below we compute the gradient +There is a catch. We had to choose $h$, and the answer depends on that choice. Below we compute the gradient with respect to `centre` for step sizes spanning ten orders of magnitude. """ print("Step size h d(log likelihood) / d(centre)\n") @@ -449,10 +455,10 @@ def gradient_via_finite_difference_from(vector, h=1.0e-3): r""" The table shows the two failure modes of finite differencing, one at each end. -When \( h \) is too large, the two evaluations are so far apart that the line between them is not the slope at our +When $h$ is too large, the two evaluations are so far apart that the line between them is not the slope at our point at all, it is the average slope over a wide interval. The answer is "biased". -When \( h \) is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them +When $h$ is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them to about sixteen significant figures, so subtracting them keeps mostly round-off noise, which dividing by a tiny number then amplifies. The answer becomes erratic. @@ -460,8 +466,8 @@ def gradient_via_finite_difference_from(vector, h=1.0e-3): depends on the units of the parameter, the scale of the data and the model, so it must be found by trial and error for every new problem. That is not a comfortable position to be in! -There is a second cost. Each parameter needs two evaluations, so a gradient for a model with \( N \) parameters -costs \( 2N \) evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of +There is a second cost. Each parameter needs two evaluations, so a gradient for a model with $N$ parameters +costs $2N$ evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of computation to work out which way to take one step. This is exactly what the `LBFGS` search of tutorial 3 was doing, silently, on your behalf. It "evaluates the @@ -516,7 +522,7 @@ def log_likelihood_from_vector(vector): r""" The two gradients agree to several decimal places, the sanity check that matters: autodiff computes the same quantity we computed by hand, exactly and in one pass rather than approximately and in six. Where they disagree it -is the finite-difference answer that is wrong, because it carries the error we chose when we picked \( h \). +is the finite-difference answer that is wrong, because it carries the error we chose when we picked $h$. JAX has a second trick. `jax.jit` compiles a function into optimised machine code the first time it is called and reuses that code on every subsequent call, so for a search calling the likelihood thousands of times a one-off @@ -546,7 +552,7 @@ def log_likelihood_from_vector(vector): We now have gradients. Let us give them to the three families of search we met in tutorial 3. We start with `LBFGS`, passing it the NumPy analysis, because `LBFGS` cannot use JAX gradients: it estimates the -gradient itself by finite differencing, exactly as we did by hand, so every iteration costs \( 2N + 1 \) +gradient itself by finite differencing, exactly as we did by hand, so every iteration costs $2N + 1$ evaluations. It also starts from a single point, the centre of the priors. In tutorial 3 that was enough to trap it in a local maximum; with the wider priors here it does better, but a single walker walking uphill can still only find the peak it happens to be standing on. @@ -799,14 +805,16 @@ def log_likelihood_from_vector(vector): For several parameters the second derivatives form a matrix called the "Hessian", which `jax.hessian` computes by the same autodiff machinery as `jax.grad`. The errors follow from: -\[ C = -H^{-1}, \qquad \sigma_{i} = \sqrt{C_{ii}} \] +$$ +C = -H^{-1}, \qquad \sigma_{i} = \sqrt{C_{ii}} +$$ Where: -- \( H \): the Hessian, the matrix of second derivatives of the log likelihood at the peak. -- \( C \): the covariance matrix, the negative inverse of the Hessian. -- \( \sigma_{i} \): the 1 sigma error on parameter \( i \), the square root of the \( i \)th diagonal entry - of \( C \). +- $H$: the Hessian, the matrix of second derivatives of the log likelihood at the peak. +- $C$: the covariance matrix, the negative inverse of the Hessian. +- $\sigma_{i}$: the 1 sigma error on parameter $i$, the square root of the $i$th diagonal entry + of $C$. In words: invert the curvature, flip its sign, and the square roots of its diagonal are the errors. We evaluate this at the maximum likelihood vector found by `Nautilus`. @@ -890,7 +898,7 @@ def log_likelihood_from_vector(vector): point, pointing in the direction the likelihood increases fastest. 2. **Finite differencing versus autodiff**: a gradient can be estimated by nudging each parameter and re-evaluating, -but this costs \( 2N \) evaluations and forces a step size which is biased if too large and noisy if too small. +but this costs $2N$ evaluations and forces a step size which is biased if too large and noisy if too small. Autodiff applies the chain rule to the operations the likelihood performs, giving the exact gradient for a small fixed multiple of the cost of one evaluation, whatever the number of parameters. diff --git a/scripts/chapter_1_introduction/tutorial_7_the_details.py b/scripts/chapter_1_introduction/tutorial_7_the_details.py index e0acb92..5545883 100644 --- a/scripts/chapter_1_introduction/tutorial_7_the_details.py +++ b/scripts/chapter_1_introduction/tutorial_7_the_details.py @@ -848,7 +848,9 @@ def log_likelihood_function(self, instance) -> float: independent. Suppose the narrow component is an instrumental effect blurred into the broad one, so the width we want for the broad component is what is left after the narrow one is removed in quadrature: -\[ \sigma_{\rm halo} = \sqrt{\sigma_{1}^2 - \sigma_{0}^2} \] +$$ +\sigma_{\rm halo} = \sqrt{\sigma_{1}^2 - \sigma_{0}^2} +$$ Where: diff --git a/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py index dc1a819..5d99556 100644 --- a/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py +++ b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py @@ -37,31 +37,33 @@ Here is the equation that every tutorial in this chapter has been solving without ever writing it down: -\[ P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)} \] +$$ +P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)} +$$ Where: -- \( \theta \): the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`. +- $\theta$: the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`. -- \( D \): the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map. +- $D$: the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map. -- \( P(\theta \mid D) \): the "posterior", the probability of the parameters given the data, and the quantity we +- $P(\theta \mid D)$: the "posterior", the probability of the parameters given the data, and the quantity we actually want. -- \( P(D \mid \theta) \): the "likelihood", the probability of the data given the parameters, computed by the +- $P(D \mid \theta)$: the "likelihood", the probability of the data given the parameters, computed by the `log_likelihood_function` of tutorial 3 before we take its logarithm. -- \( P(\theta) \): the "prior", the probability we assign to parameter values before looking at the data, the +- $P(\theta)$: the "prior", the probability we assign to parameter values before looking at the data, the `UniformPrior` and `LogUniformPrior` objects of tutorial 3. -- \( P(D) \): the "evidence", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5. +- $P(D)$: the "evidence", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5. In plain words: the answer we want is the goodness-of-fit multiplied by our prior beliefs, divided by a normalizing number. Every algorithm in this chapter is a strategy for evaluating the right hand side without ever computing the -integral hiding inside \( P(D) \). +integral hiding inside $P(D)$. -Each tutorial supplied exactly one piece. Tutorial 1 built \( \theta \) and the forward model. Tutorial 2 built -\( P(D \mid \theta) \), calling it the log likelihood. Tutorial 3 built \( P(\theta) \) and the searches which +Each tutorial supplied exactly one piece. Tutorial 1 built $\theta$ and the forward model. Tutorial 2 built +$P(D \mid \theta)$, calling it the log likelihood. Tutorial 3 built $P(\theta)$ and the searches which explore the product of the two. Tutorial 4 showed what goes wrong when the posterior has more than one peak, tutorial 5 read the answer back out, and tutorials 6 and 7 differentiated it and asked what the numbers mean. @@ -110,12 +112,12 @@ r""" __The Model__ -The symbol \( \theta \) is nothing more exotic than the list of numbers you passed to `instance_from_vector` in +The symbol $\theta$ is nothing more exotic than the list of numbers you passed to `instance_from_vector` in tutorial 1. Bayes' theorem is a statement about a probability distribution over that list, and nothing else. We therefore begin as tutorial 1 did, by re-pasting the `Gaussian` class in full. Its constructor arguments are the -entries of \( \theta \), and its `model_data_from` method is the forward model: the function which, given -\( \theta \), predicts what the data should look like. +entries of $\theta$, and its `model_data_from` method is the forward model: the function which, given +$\theta$, predicts what the data should look like. """ @@ -172,7 +174,7 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: r""" -Composing the model gives the two pieces of book-keeping which make \( \theta \) concrete. The `prior_count` is the +Composing the model gives the two pieces of book-keeping which make $\theta$ concrete. The `prior_count` is the number of dimensions the posterior is a distribution over, and `paths` gives the order of the entries in the vector. """ model = af.Model(Gaussian) @@ -181,7 +183,7 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: print("Order of the parameters in theta:", model.paths) r""" -A specific \( \theta \) becomes a model, and the model becomes predicted data, in the two lines below. This is the +A specific $\theta$ becomes a model, and the model becomes predicted data, in the two lines below. This is the forward modelling of tutorial 1, and it is what lets us ask "how probable is the data, given these parameters?". """ instance = model.instance_from_vector(vector=[50.0, 25.0, 10.0]) @@ -215,25 +217,29 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: We assume each data point is its predicted value plus a random draw from a Gaussian of width equal to that point's noise. The probability of the whole dataset is then a product of one Gaussian probability per data point: -\[ P(D \mid \theta) = \prod_i \frac{1}{\sqrt{2\pi\sigma_i^2}} \exp\left(-\frac{(d_i - m_i)^2}{2\sigma_i^2}\right) \] +$$ +P(D \mid \theta) = \prod_i \frac{1}{\sqrt{2\pi\sigma_i^2}} \exp\left(-\frac{(d_i - m_i)^2}{2\sigma_i^2}\right) +$$ Taking the logarithm turns that product into a sum: -\[ \ln P(D \mid \theta) = -\frac{1}{2} \sum_i \frac{(d_i - m_i)^2}{\sigma_i^2} - \frac{1}{2} \sum_i \ln(2\pi\sigma_i^2) \] +$$ +\ln P(D \mid \theta) = -\frac{1}{2} \sum_i \frac{(d_i - m_i)^2}{\sigma_i^2} - \frac{1}{2} \sum_i \ln(2\pi\sigma_i^2) +$$ Where: -- \( d_i \): the value of the data at point \( i \), the `data` array. +- $d_i$: the value of the data at point $i$, the `data` array. -- \( m_i \): the value of the model data at point \( i \), computed by `model_data_from` for this \( \theta \). +- $m_i$: the value of the model data at point $i$, computed by `model_data_from` for this $\theta$. -- \( \sigma_i \): the noise at point \( i \), the `noise_map` array. +- $\sigma_i$: the noise at point $i$, the `noise_map` array. Compare the second equation with tutorial 2 line by line. The first sum is the `chi_squared`, and the second is the `noise_normalization`, the log of the product of the Gaussian prefactors. Both are multiplied by -0.5, which is where the mysterious factor comes from: it is not a convention, it is the 2 in the denominator of the exponent of a Gaussian. The noise normalization really is a constant, because it depends only on the noise-map and never on -\( \theta \), so it shifts every log likelihood equally and can never change which model wins. +$\theta$, so it shifts every log likelihood equally and can never change which model wins. Below we compute the log likelihood twice: by tutorial 2's chi-squared route, and by summing the log of a Gaussian probability density at every data point using `scipy`. They are the same number. @@ -255,14 +261,14 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: __The Prior__ The priors of tutorial 3 were introduced as a way of telling the search where to look. Formally they are -\( P(\theta) \), a probability distribution over the parameters written down before we look at the data. Because our +$P(\theta)$, a probability distribution over the parameters written down before we look at the data. Because our parameters are independent, the prior is a product of one distribution per parameter and its logarithm is a sum, -\( \ln P(\theta) = \sum_j \ln P(\theta_j) \). +$\ln P(\theta) = \sum_j \ln P(\theta_j)$. The two priors on the default `Gaussian` model have simple forms. A `UniformPrior` is constant inside its limits and zero outside them, so its log is a constant we may set to zero inside and negative infinity outside. A -`LogUniformPrior` is proportional to \( 1 / \theta_j \), the statement "every order of magnitude is equally likely", -so its log falls off as \( -\ln \theta_j \). +`LogUniformPrior` is proportional to $1 / \theta_j$, the statement "every order of magnitude is equally likely", +so its log falls off as $-\ln \theta_j$. **PyAutoFit** hands you those numbers directly. Below we print the priors of the model, then evaluate the log prior of each parameter inside the prior limits, and then for a `centre` of 150.0 which lies outside the `UniformPrior` @@ -293,7 +299,7 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: The first entry of the second list is `-inf`, an infinitely improbable model. This is the formal version of tutorial 3's statement that priors define the valid parameter space: a model outside the priors is not penalised, it is excluded. The middle entry is not zero, because the `LogUniformPrior` on `normalization` prefers smaller values and -\( -\ln(25) \) is about -3.2. +$-\ln(25)$ is about -3.2. Priors enter a fit a second way, and it is how nested sampling works. Every prior can be inverted: instead of asking "how probable is this value?", we ask "which value sits at this fraction of the distribution?". That inverse is the @@ -320,7 +326,7 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: This is the key to a sentence in tutorial 3 which may have seemed arbitrary: nested sampling "draws live points from the priors". A search which picks unit values uniformly at random between 0 and 1 and passes them through `value_for` is drawing samples from the prior distribution itself. It is also why a nested sampling search cannot be -given a starting point: its first step is defined to be a draw from \( P(\theta) \). +given a starting point: its first step is defined to be a draw from $P(\theta)$. __The Posterior__ @@ -384,14 +390,16 @@ def log_likelihood_function(self, instance) -> float: print("The search has finished run - you may now continue the notebook.") r""" -The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a \( \theta \) the search +The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a $\theta$ the search accepted, and each entry of `weight_list` says how much that sample counts when the posterior is summed up. Together -they approximate \( P(\theta \mid D) \): a cloud of points, denser where the posterior is higher. +they approximate $P(\theta \mid D)$: a cloud of points, denser where the posterior is higher. Tutorial 5 also told you, without justification, that the log posterior is the log likelihood plus the log prior. That is Bayes' theorem logged, with the evidence dropped because it is the same number for every sample: -\[ \ln P(\theta \mid D) = \ln P(D \mid \theta) + \ln P(\theta) - \ln P(D) \] +$$ +\ln P(\theta \mid D) = \ln P(D \mid \theta) + \ln P(\theta) - \ln P(D) +$$ Below we check the first few samples, printing the log likelihood, log prior, log posterior, and the difference between the log posterior and the sum of the first two. @@ -425,10 +433,10 @@ def log_likelihood_function(self, instance) -> float: There are two "best-fit" models hiding in a set of samples, and tutorial 5 printed both without saying they could disagree: -- The "maximum likelihood" model, `samples.max_log_likelihood()`, is the \( \theta \) fitting the data best, +- The "maximum likelihood" model, `samples.max_log_likelihood()`, is the $\theta$ fitting the data best, ignoring the priors entirely. -- The "maximum a posteriori" model, usually shortened to MAP, `samples.max_log_posterior()`, is the \( \theta \) +- The "maximum a posteriori" model, usually shortened to MAP, `samples.max_log_posterior()`, is the $\theta$ which maximizes likelihood times prior. If every prior is uniform the log prior is the same constant inside the limits, so the two are the same model. They @@ -453,13 +461,15 @@ def log_likelihood_function(self, instance) -> float: `aplt.corner_cornerpy`. That requires an operation with a formal name, "marginalization", which means integrating the posterior over the parameters you are not currently interested in: -\[ P(\theta_1 \mid D) = \int P(\theta \mid D) \, d\theta_2 \, d\theta_3 \ldots \] +$$ +P(\theta_1 \mid D) = \int P(\theta \mid D) \, d\theta_2 \, d\theta_3 \ldots +$$ Where: -- \( \theta_1 \): the parameter we want a one-dimensional answer for, for example `centre`. +- $\theta_1$: the parameter we want a one-dimensional answer for, for example `centre`. -- \( \theta_2, \theta_3, \ldots \): every other parameter of the model, integrated away. +- $\theta_2, \theta_3, \ldots$: every other parameter of the model, integrated away. That integral looks intimidating, and done analytically it would be. This is the greatest practical advantage of having samples: marginalizing them means ignoring the columns you do not care about and histogramming the one you @@ -489,16 +499,18 @@ def log_likelihood_function(self, instance) -> float: r""" __The Evidence__ -The one term of Bayes' theorem we have ignored is the denominator, \( P(D) \), the evidence. It is the integral of +The one term of Bayes' theorem we have ignored is the denominator, $P(D)$, the evidence. It is the integral of the numerator over the whole of parameter space: -\[ P(D) = \int P(D \mid \theta) \, P(\theta) \, d\theta \] +$$ +P(D) = \int P(D \mid \theta) \, P(\theta) \, d\theta +$$ Where: - The integral runs over every value of every parameter the priors allow. -Two facts about this integral explain a lot of what you have seen. First, it does not depend on \( \theta \), which +Two facts about this integral explain a lot of what you have seen. First, it does not depend on $\theta$, which is why MCMC never needs it: a walker deciding whether to move compares posteriors as a ratio and the evidence cancels. Second, it is genuinely hard, an integral over a many-dimensional space in which almost all of the volume contributes almost nothing. @@ -524,14 +536,16 @@ def log_likelihood_function(self, instance) -> float: automatic differentiation. In this notation, what the gradient searches climb is the derivative of the log posterior: -\[ \nabla_\theta \ln P(\theta \mid D) = \nabla_\theta \ln P(D \mid \theta) + \nabla_\theta \ln P(\theta) \] +$$ +\nabla_\theta \ln P(\theta \mid D) = \nabla_\theta \ln P(D \mid \theta) + \nabla_\theta \ln P(\theta) +$$ Where: -- \( \nabla_\theta \): the vector of derivatives with respect to each parameter in turn. +- $\nabla_\theta$: the vector of derivatives with respect to each parameter in turn. -The evidence has vanished, and its disappearance is the point. Because \( \ln P(D) \) does not depend on -\( \theta \), differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which +The evidence has vanished, and its disappearance is the point. Because $\ln P(D)$ does not depend on +$\theta$, differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which only ever looks at slopes. This is the formal reason gradient methods scale so well. Hamiltonian Monte Carlo and its self-tuning variant NUTS, From e5c4509ea94129724a1eca5e00a395a361b862a7 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 14 Sep 2026 23:07:59 +0100 Subject: [PATCH 2/2] docs: give tutorial 3's MCMC fits a budget that actually converges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The prose after the first, uninitialised Emcee fit asserts that "the MCMC search succeeded, finding the same high-likelihood model that the MLE search with a good starting point identified". Measured over 20 runs at the existing `nwalkers=10, nsteps=200`, it succeeded 11 times — the tutorial asserted an outcome it produced 55% of the time. Both Emcee searches move to `nwalkers=20, nsteps=500`. Walkers, not steps, were the binding constraint: 20 walkers x 300 steps (6000 evaluations) beats 10 x 500 (5000) and 10 x 200, and an ensemble of 10 is only ~3x the model dimension. The chosen budget succeeded 80/80 in a stress test at a median 9.8s, against 3.9s before. CI is unaffected — `config/build/profile_smoke.yaml` sets `PYAUTO_TEST_MODE: "2"` (skip sampler) for every script with no tutorial 3 override, and the measured test-mode runtime is unchanged at ~1.5s. Both fits get the same budget, so the only remaining difference between them is the initializer — which is what that section claims to demonstrate. The `nsteps` limitation paragraph stays and now covers `nwalkers` too, since the measurement says walkers were what mattered, with a note that a budget is only ever confirmed by running the fit more than once. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG --- .../tutorial_3_non_linear_search.ipynb | 22 ++++++++++++------- .../tutorial_3_non_linear_search.py | 22 ++++++++++++------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb index d9e7c17..21bad9a 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb @@ -828,8 +828,8 @@ "metadata": {}, "source": [ "search = af.Emcee(\n", - " nwalkers=10, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=200, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends.\n", + " nwalkers=20, # The number of walkers we'll use to sample parameter space, comfortably more than the model's 3 parameters.\n", + " nsteps=500, # The number of steps each walker takes, after which 20 * 500 = 10000 samples the non-linear search ends.\n", ")\n", "\n", "print(\n", @@ -906,8 +906,8 @@ ")\n", "\n", "search = af.Emcee(\n", - " nwalkers=10, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=200, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends.\n", + " nwalkers=20, # The number of walkers we'll use to sample parameter space, comfortably more than the model's 3 parameters.\n", + " nsteps=500, # The number of steps each walker takes, after which 20 * 500 = 10000 samples the non-linear search ends.\n", " initializer=initializer,\n", ")\n", "\n", @@ -935,10 +935,16 @@ "without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can\n", "efficiently scale to more complex models with more parameters.\n", "\n", - "The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value \n", - "is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right \n", - "number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are \n", - "used. One often ends up having to perform \"trial and error\" to verify a sufficient number of steps are used.\n", + "The main limitation of MCMC is that one has to supply the number of walkers (`nwalkers`) and the number of steps each \n", + "walker takes (`nsteps`). If either value is too low, the walkers may not explore the likelihood surface sufficiently. \n", + "It can be challenging to know the right values, especially if models of different complexity are being fitted or if \n", + "datasets of varying quality are used. One often ends up having to perform \"trial and error\" to verify that a \n", + "sufficient number of walkers and steps are used.\n", + "\n", + "The `nwalkers=20` and `nsteps=500` used in both fits above were chosen by exactly this process: they were raised from \n", + "smaller values until repeated runs of the uninitialized fit reliably converged on the correct solution. With fewer \n", + "walkers the search would sometimes finish trapped near a local maximum, in the same way the MLE search did, so a \n", + "budget that looks \"big enough\" is only ever confirmed by running the fit more than once.\n", "\n", "MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are\n", "local maxima \"peaks\" the walkers can become stuck walking around them.\n", diff --git a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py index ff817a7..da74aad 100644 --- a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py +++ b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py @@ -606,8 +606,8 @@ def log_likelihood_function(self, instance) -> float: initialized in a "ball" around the center of the model’s priors, similar to the MLE search that failed earlier. """ search = af.Emcee( - nwalkers=10, # The number of walkers we'll use to sample parameter space. - nsteps=200, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends. + nwalkers=20, # The number of walkers we'll use to sample parameter space, comfortably more than the model's 3 parameters. + nsteps=500, # The number of steps each walker takes, after which 20 * 500 = 10000 samples the non-linear search ends. ) print( @@ -673,8 +673,8 @@ def log_likelihood_function(self, instance) -> float: ) search = af.Emcee( - nwalkers=10, # The number of walkers we'll use to sample parameter space. - nsteps=200, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends. + nwalkers=20, # The number of walkers we'll use to sample parameter space, comfortably more than the model's 3 parameters. + nsteps=500, # The number of steps each walker takes, after which 20 * 500 = 10000 samples the non-linear search ends. initializer=initializer, ) @@ -696,10 +696,16 @@ def log_likelihood_function(self, instance) -> float: without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can efficiently scale to more complex models with more parameters. -The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value -is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right -number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are -used. One often ends up having to perform "trial and error" to verify a sufficient number of steps are used. +The main limitation of MCMC is that one has to supply the number of walkers (`nwalkers`) and the number of steps each +walker takes (`nsteps`). If either value is too low, the walkers may not explore the likelihood surface sufficiently. +It can be challenging to know the right values, especially if models of different complexity are being fitted or if +datasets of varying quality are used. One often ends up having to perform "trial and error" to verify that a +sufficient number of walkers and steps are used. + +The `nwalkers=20` and `nsteps=500` used in both fits above were chosen by exactly this process: they were raised from +smaller values until repeated runs of the uninitialized fit reliably converged on the correct solution. With fewer +walkers the search would sometimes finish trapped near a local maximum, in the same way the MLE search did, so a +budget that looks "big enough" is only ever confirmed by running the fit more than once. MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are local maxima "peaks" the walkers can become stuck walking around them.