Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 39 additions & 28 deletions notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -417,19 +417,30 @@
"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."
]
},
{
"cell_type": "code",
"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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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.\")"
Expand Down Expand Up @@ -706,17 +715,16 @@
"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."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"model = af.Model(Gaussian)\n",
"\n",
"initializer = af.InitializerParamStartPoints(\n",
" {\n",
" model.centre: 52.0,\n",
Expand Down Expand Up @@ -820,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",
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -899,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",
Expand Down Expand Up @@ -928,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",
Expand Down Expand Up @@ -987,8 +1000,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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
56 changes: 32 additions & 24 deletions notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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."
Expand Down Expand Up @@ -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."
]
},
Expand All @@ -632,19 +638,19 @@
"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",
"Somewhere in the middle is a sweet spot, visible as the region where the answer stops changing, but its location\n",
"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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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."
Expand Down Expand Up @@ -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`."
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading