ML Club sessions
ML in Astronomy

Community session, with Cepheid · Epoch, IIT Hyderabad · Mar 22, 2023

A hands-on session on the statistics and ML libraries commonly used for astronomical data analysis, such as AstroML and AstroPy, with a few exercises. The pages below are the lecture notes.

Slide 1 of 262
1 / 262

ML in Astronomy

Community session, with Cepheid · Epoch, IIT Hyderabad · Mar 22, 2023

A hands-on session on the statistics and ML libraries commonly used for astronomical data analysis, such as AstroML and AstroPy, with a few exercises. The pages below are the lecture notes.

  1. Introduction
  2. Data Mining • Set of techniques for analyzing and describing structured data, for example finding patterns in large datasets. Examples : Density estimation, unsupervised classification, clustering, principal component analysis, locally linear embedding. Often interchanged with knowledge discovery. Traditionally deals with unsupervised learning techniques (referred to by statisticians as exploratory data analysis)
  3. Machine Learning • Umbrella term for a set of techniques for interpreting data by comparing them to models for data behavior. Examples : regression methods, supervised classification methods, maximum likelihood estimators, Bayesian methods. Also known as inference techniques, data-based statistical inferences or fitting. Emphasis has been on prediction of one variable based on the other variable, also known as supervised learning.
  4. One-stop link for course content • http://www.astroml.org • Current course website https://piazza.com/iit_hyderabad/spring2023/ep4130ph6130/info • Google classroom to be used for uploading assignments rmv2er7
  5. What is Data Science? Credit:drewconway.com Cross-disciplinary set of skills • Statistician • Computer Scientist • Domain expertise
  6. You may ask “What can a hard headed statistician offer to a starry eyed astronomer?”. The answer is “Plenty”. One normally associates statistics with large numbers, and astronomy is full of large numbers…I have every reason to believe that increased interaction between statistics and astronomy will be to the benefit of both subjects. Jayant Narlikar to C.R. Rao
  7. Trend of Programming languages in Astro literature From https://twitter.com/astrofrog/status/787007261877166080 does not include R and C (as difficult to parse texts)
  8. Statistical Data Analysis tasks in Astronomy Photometric Redshifts (Regression) Source Classification Dimensionality Reduction/Visualization Clustering N-point statistics Period Finding Transient and Outlier Detection Density Estimation Matched Filtering Source Extraction Cross-Matching
  9. Probability Axioms 𝑃(𝐴∪𝐵) = 𝑃(𝐴) + 𝑃(𝐵) −𝑃(𝐴∩𝐵) Probability for both A and B to happen = 𝑃(𝐴∩𝐵) 𝑃𝐴∩𝐵= 𝑃𝐴𝐵 ⁄ 𝑃𝐵= 𝑃𝐵𝐴 ⁄ 𝑃(𝐴) 𝑃𝐴𝐵 ⁄ is conditional probability of event A given that (on conditioned on) B has occurred Bayes Theorem P(A) > 0 Sum P(A) = 1 (for all possible outcomes) For disjoint events A1 A2, etc P(A) is a probability if it satisfies three axioms: p([1 i=1Ai) = 1 X i=1 p(Ai)
  10. If events Bi i=1…..N are disjoint and union is set of all possible outcomes then This is called “Law of Total Probability” Conditional probabilities also satisfy law of total probability. Assuming an event Ci is not mutually exclusive with A or any of the Bi then Probability rules were derived from two different sets of axioms by Cox and Kolmogorov (Jaynes ) P(A|B) = X i P(A|B \ Ci)P(Ci|B)
  11. If events Ci i=1…..N are disjoint and union is set of all possible outcomes then P(A \ B) = X i P(A \ B \ Ci) P(A \ B) = X i P(A|B \ Ci)P(B \ Ci) P(A \ B) = X i P(A|B \ Ci)P(Ci|B)P(B)
  12. P(A|B) = P(A \ B) P(B) P(A|B) = P i P(A|B \ Ci)P(Ci|B)P(B) P(B) P(A|B) = P(A|B \ Ci)P(Ci|B) P(A|B) = X i P(A|B \ Ci)P(Ci|B)
  13. Random Variables • A random variables is a variable whose value results from the measurement of a quantity subject to stochastic variations. • Independent identically distributed random variables are drawn from the same distribution and independent. Two random variables x and y are independent if and only if P(x,y) = P(x) P(y) Conditional Probability and Bayes Rule If two continuous random variables are not independent, it follows that p(x,y) = p(x|y)p(y) = p(y|x) p(x) Marginal Probability function defined as 𝑝𝑥= ∫𝑝𝑥, 𝑦𝑑𝑦 3 3 By combining above two equations we get 𝑝𝑥= ∫𝑝𝑥𝑦𝑝𝑦𝑑𝑦 3 3
  14. Code to reproduce this available from astroml.org website P(x|y=y0) are one-dimensional “slices” through the two-dimensional Image p(x,y) at given values of y0 divided by the value of marginal distribution p(y) ∫P(x) dx = 1
  15. For a discrete random variable yj with M possible values the above integral becomes a sum: p(yj|x) = p(x|yj)p(yj) M P j=1 p(x|yj)p(yj) Homework : Read about Monty Hall problem
  16. Transformations of Random Variables Any function of a random variable x y = ɸ(x) is a random variable. We can calculate p(y) from p(x) as follows : Cumulative statistics such as medians do not change their order under monotonic transformations
  17. If uncertainty in x at a given value of x0 is given by σx then we can use Taylor series expansion to Estimate the uncertainty in y at y0 = ɸ(x0 ) Sometimes this can lead to misleading results for non-linear transformations for example (in Astronomy) magnitude = -2.5log(Flux)
  18. Example :
  19. Consider G= G(x1,x2,… xn) with uncertainties 𝞂1 𝞂2....... 𝞂n Iff the errors in x1,x2 … are uncorrelated Eg. Δm = m1 – m2 𝞂2Δm = 𝞂m12 + 𝞂m22 Error Propagation (Without Covariances) σ2 G = N X i=1 ✓@G @xi ◆2 σ2 xi
  20. where Error Propagation (with Covariances) σ2 G = N X i=1 ✓@G @xi ◆2 σ2 xi + 2σ2 x1x2 @G @x1 @G @x2 + ..... Ref. Bevington’s book σ2 x1x2 = N P i=1 [(x1i −¯x1)][(x2i −¯x2)] N
  21. Descriptive Statistics An arbitrary distribution h(x) is characterized by its location parameters, scale or width parameters and “shape” parameters. When they are based on the distribution h(x) they are called population statistics. If they are based upon a finite-sized dataset, they are called sample statistics. Arithmetic mean based upon expectation value Variance
  22. Standard Deviation Skewness Kurtosis Variance, skewness., kurtosis related to kth central moment of a distribution (k=2,3,4)
  23. Kurtosis
  24. Moments From Generating Function Ref: arXiv:0712.3028 Generating Function allows you to calculate the moments of a distribution This can be written as an infinite series by expanding the exponential giving :
  25. Absolute Deviation about d Absolute deviation about the mean (d=mean(x)) is called mean deviation Mode (or most probable value in case of unimodal functions) xm P % quantiles (or p percentiles)
  26. import numpy as np x = np.random.random(100) q25,q50,q75 = np.percentile(x,[25,50,75]) All the moments are built into NumPy and SciPy. Useful functions are numpy.median, numpy.mean, numpy.var numpy.percentile, numpy.std,scipy.stats.skew, scipy.stats.kurtosis, scipy.stats.mode A useful relation between mode, median and mean valid for mildy non-gaussian distributions Mode = 3 (median) – 2(mean) Difference between third and first quartile is called interquartile range
  27. Data-Based Estimates of Descriptive Statistics If the above quantities are derived from data, they are called sample statistics (instead of population Statistics). Assume we have N given measurements xi for i=1,….....N abbreviated as {xi} For a sample of N measurements Sample arithmetic mean and standard deviation given by : i
  28. If the samples have an error 𝞂I mean and error in mean are given by: Sample Standard deviation is calculated as follows: N-1 is used so that variance is unbiased
  29. Median Absolute Deviation (wikipedia) For a normal distribution, σ = 1.482 MAD where σ is the std deviation of Gaussian distribution Uncertainty in the standard mean is given by : σ¯x = s p N For real data with outliers, calculation of s from data samples can lead to wrong estimates (if errors in each data point are equal)
  30. Alternately, you can use a rank based estimate of the standard deviation. Inter-quartile range (q75 – q25) is a more robust estimator of the scale parameter than the standard deviation. Even in absence of outliers for some distributions which do not have finite variance such as the Cauchy distribution, the median and interquartile range are the best choices for estimating the location and scale parameters. For a Gaussian, σG = 0.7413(q75 –q25) (σG can be computed with astroML library)
  31. Quantiles Source : wikipedia
  32. Some Definitions • Probability Density Function : The function h(x) quantifies the probability that a value lies between x and x+dx equal to h(x) dx and is called the probability density function (pdf). • Probability Mass function : When x is discrete, this is called probability mass function • Cumulative Distribution Function (cdf) H(x) H(x) = Z x −1 h(x0)dx0
  33. Examples of Distribution Functions Uniform Distribution P(x|μ,W) = 1/W for |x – μ| <= W/2 from scipy import stats dist = stats.uniform(0,2) # left edge at 0 and width=2 r = dist.rvs(10) # 10 random draws P = dist.pdf(1) #PDF evaluated at x=1 Look at scipy.stats page for more information
  34. Gaussian Distribution Also called Normal distribution dist = stats.norm(0,1) #mean=0, stddev=1 r = dist.rvs(10) p = dist.pdf(0)
  35. Convolution of two Gaussians is also a Gaussian function Qt: Consider convolution of two normal distributions : and What is the mean and std. deviation of the resulting Gaussian? Cumulative distribution function of a Gaussian distribution is given by : P(x|µ, σ) = 1 σ p 2⇡ Z x −1 exp ✓−(x −µ)2 2σ2 ◆ = 1 2(1 ± erf ✓|x −µ| p 2σ ◆ ) where erf = Gauss error function
  36. Gauss error function is available in scipy.special from scipy.special import erf erf(1) = 0.842 For a= μ – Mσ and b = μ + Mσ, the above integral = erf(M/√2) M=1,2,3, give values of 0.68, 0.954, 0.997 respectively for erf(M/√2) If x follows a Gaussian distribution, exp(x) follows a log-normal distribution.
  37. LogNormal Distribution Number distribution of galaxies as a function of density contrast arxiv:1605.02036
  38. Lognormal Distribution Examples Gamma-Ray Burst Duration (Soham Kulkarni arXiv:1612.08235)
  39. How to Gaussianize a distribution Perform a Box-Cox (1964) transformation on the data (arXiv:1508.00931) yλ(a) = ⇢ aλ−1 λ if λ 6= 0 log a if λ = 0 ¯yλ = N X i=1 yλ(ai) n
  40. s2 λ = N X i=1 (yλ(ai) −¯yλ)2 n Maximum likelihood estimate of the variance of the transformed data is given by We choose λ such that we maximize the log likelihood function I(λ) = −n 2 log(2⇡) −n 2 −n 2 log s2 λ + (λ −1) N X i=1 log(ai) yλ (a) will be an exact normal distribution if λ=0 or 1/λ is an even integer
  41. arxiv:1508.00931 Eccentricity distribution of exoplanets before and after Box-Cox transformation
  42. Box-Cox Transformation in Python (see also stackexchange for examples)
  43. Binomial Distribution from scipy import stats dist=stats.binom(20,0.7) r= dist.rvs(10) P = dist.pmf(8) # prob. evaluated at k=8 Binomial distribution describes the distribution of a variable that can only take discrete values If probability of success is b, distribution of a discrete variable k that measures how many times Success occurs in N trials is given by Probability Mass Function N=1 is called Bernoulli distribution
  44. Mean of a binomial distribution is given by 𝑘= Nb Standard deviation is given by : σk = [N b (1-b)]1/2 Binomial distribution can be generalized to a Multinomial distribution in case a variable has more than two discrete values.
  45. Poisson Distribution Poisson distribution special case of the binomial distribution describing the distribution of a discrete variable, when the number of trials (N) goes to infinity and probability of success (p=k/N) stays fixed. Distribution of number of success k is controlled by μ = k N and is given by Poisson distribution is ubiquitous describes independent point process: photon noise, radioactive decay, galaxy distribution for very few galaxies, point sources Mean (or expectation value) = μ Standard deviation = √μ As μ increases the Poisson distribution becomes more and more similar to Gaussian distribution
  46. As μ increases the Poisson distribution becomes more and more similar to a Gaussian distribution given by N(µ, pµ) from scipy import stats dist = stats.poisson(5) r = dist.rvs(10) p = dist.pmf(3) Difference between Mean and Median does not become 0 but becomes 1/6
  47. Examples of Poisson Distribution arXiv:1603.06522 Galaxy clusters discovered with SPT as a function of redshift 0 1 2 3 4 5 -1 -0.8 -0.6 -0.4 -0.2 0 cosΘ flux (10-13cm-2s-1sr-1) Flux of upward muons in Super-K as a function of zenith angle (1998) hep-ex/9812014
  48. Relation between Poisson, Gaussian, and Binomial Distribution Binomial Poisson Gaussian N→∞, Np=μ N→∞ μ→∞ Source: L. Lyons Data Analysis for Physical Science Students
  49. Cauchy (Lorentzian) Distribution p(x|µ, γ) = 1 ⇡γ ✓ γ2 γ2 + (x −µ)2 ◆ Exercise : Redo the above plots with μ=1 and Ɣ=4 Cauchy distribution described by location Parameters μ and scale parameter Ɣ
  50. Lorentzian line shape function
  51. from scipy import stats dist = stats.cauchy(0,1) r = dist.rvs(10) P = dist.pdf(3) # pdf evaluated at x=3 Ratio of two independent standard normal variables z = (x-μ)/σ with z drawn from a Normal Distribution with μ=0 and 𝞂=1 follows a Cauchy distribution with μ=0 and γ=1 However, ratio of two random variables drawn from two different Gaussian distributions is more complicated (follows the Hinkley distribution) Mean, variance, and higher order moments undefined for Cauchy distribution.
  52. Exponential (Laplace) Distribution from scipy import stats dist = stats.laplace(0,0.5) r = dist.rvs(10) P = dist.pdf(3) Describes time between two successive events which occur continuously and independently at constant Rate
  53. Chi-Square Distribution from scipy import stats dist = stats.chi2(5) #k=5 r = dist.rvs(10) #10 random draws P = dist.pdf(3) #evaluated at x=1 If {xi} are drawn from a Gaussian distribution and if we define follows a 𝝌2 distribution with k=N degrees of freedom
  54. Γ is incomplete Gamma function
  55. EP 4130/PH6130 Second Week
  56. Chi-Square Distribution Sometimes 𝝌2 distribution per degree of freedom is defined and is given by : Mean value of 𝝌2dof is equal to 1. As k increases 𝝌2dof tends to
  57. Student’s t distribution • For k=1, this distribution is a Cauchy distribution with μ=0 and γ=1 • Mean, Mode and Median=0 for k>1 and undefined for k=1 from scipy import stats dist=stats.t(5) #k=5 r= dist.rvs(10) # 10 random draws P = dist.pdf(4) #pdf evaluated at x=4
  58. Given a sample of N measurements {xi} drawn from a Gaussian distribution Define ¯x where and s are the sample mean and sample variance, follows Student’s t- distribution with k=N-1 degrees of freedom • Student’s t distribution based on data based estimates of mean and std. deviation, whereas Cauchy distribution based on true mean and standard deviation. • t-distribution stays the same for samples drawn from a Gaussian distribution with different values of mean and standard deviation. as long as number of samples stays the same. • Ratio of a standard normal variable and one drawn from a 𝝌2 distribution follows Student’s t-distribution. • t-distribution is used when comparing means of two samples
  59. Fisher’s F distribution from scipy import stats dist=stats.f(2,3) #d1=2,d2=3 r= dist.rvs(10) # 10 random draws P = dist.pdf(1) #pdf evaluated at x=1 p(x|d1, d2) = C(1 + d1 d2 x)−d1+d2 2 x d1 2 −1 where C is given by B is the Beta function Also known as Snedecor distribution, variance ratio Distribution, F-distribution
  60. • Fisher F distribution describes the ratio of two independent 𝝌2 variables with d1 and d2 degrees of freedom. • If x1 and x2 are two independent random variables drawn from the Cauchy distribution with Location parameter μ, then the ratio |x1-μ|/|x2-μ| follows Fisher’s F distribution with d1=d2=2.
  61. Beta Distribution from scipy import stats dist=stats.beta(0.5,1.5) #alpha=0.5, beta=1.5 r= dist.rvs(10) # 10 random draws P = dist.pdf(0.6) #pdf evaluated at x=0.6 • Mean value of beta distribution is α/(α+β) • Beta distribution is conjugate prior of the binomial distribution
  62. Gamma Distribution from scipy import stats dist=stats.gamma(1,0,2) #k=1, loc=0, theta=2 r= dist.rvs(10) # 10 random draws P = dist.pdf(1) #pdf evaluated at x=1 • Gamma Function is a conjugate prior to several distributions such as the Laplace distribution and the Poisson distribution
  63. Weibull Distribution from scipy import stats dist=stats.dweibull(1,0,2) #k=1, loc=0,lambda=2 r= dist.rvs(10) # 10 random draws P = dist.pdf(1) #pdf evaluated at x=1
  64. Weibull distribution describes good description of random failure process with variable rate, wind speeds, distribution of extreme values, and size distribution of particles., overvoltage in an Electrical system. eg: o If x is the time to failure for a device with a failure rate proportional to time tm , x follows the Weibull distribution with k=m+1 o Wind speed follows Weibull distribution with k ~2
  65. Example of Weibull Distribution 1 knot = 0.52 m/sec
  66. Typo in astroML book • Typo in Weibull distribution pdf in AstroML book. What is plotted is positive part of double Weibull distribution (dweibull). PDF of Weibull distribution (defined in class) is given by twice this value. Alternatively, use stats.weibull_min
  67. f(x, σ) = x σ2 e−x2/2σ2x ≥0 Rayleigh Distribution (not discussed in astroML) Cumulative distribution function is given by F(x, σ) = 1 −e−x2/2σ2 Equal to Chi-square distribution for two degrees of freedom Observed when overall magnitude of a vector is related to its directional Components. eg. Wind velocity in two dimensions
  68. (image slide)
  69. Example of Rayleigh Distribution in astrophysics arXiv:1506.07814 Mixture of two Rayleigh distributions
  70. Other distributions in scipy can be found at https://docs.scipy.org/doc/scipy-0.18.1/reference/stats.html Other potential distributions among these : Rice, Pareto, Power-Law,
  71. Probability distribution named after the particle physics experiment ARGUS is the reconstructed invariant mass of a decayed particle candidate in a continuum background. Argus Distribution Look up scipy.stats.argus wikipedia
  72. Landau Distribution Not in stats.scipy wikipedia No analytic formulae for pdf Mean and variance are undefined because of very long tail Python function (pyLandau) can be downloaded from the web Scipy.stats.moyal provides a good approximation to Landau distribution.
  73. 0 5 10 15 20 25 30 35 40 2 3 4 5 6 7 8 9 10 OVFLW 0.000 Eµ = 50 Gev ∆E/∆X (MeV/cm) No. of Events OVFLW 0.000 Eµ = 100 Gev ∆E/∆X (MeV/cm) No. of Events 0 5 10 15 20 25 30 35 2 3 4 5 6 7 8 9 10 0 5 10 15 20 25 2 3 4 5 6 7 8 9 10 OVFLW 0.000 Eµ = 200Gev ∆E/∆X (MeV/cm) No. of Events OVFLW 4.000 Eµ = 500Gev ∆E/∆X (MeV/cm) No. of Events 0 2 4 6 8 10 12 14 16 2 3 4 5 6 7 8 9 10 Example of Landau Distribution Simulations of Muon Energy loss in water for various mono-energetic muon samples (SD thesis)
  74. • Benford’s law is a law about frequency of leading digits • A set of numbers is said to satisfy Benford’s law if the leading digit occurs with probability given by Benford Distribution
  75. • Surface Areas of Rivers • Physical Constants • Molecular Weights • Street Addresses of people listed in American Men of Science • Heights of Tallest structures in world • Telephone Bills etc (see wikipedia) Has been Used to detect bank & election fraud and election rigging For more details, please read arxiv:2008.12271 and arXiv:1709.09823 by A. Dantuluri & SD arXiv:2207.09696 by P. Mamidipaka & SD Also a whole book on Benford’s law HW : do google search on COVID-19 & Benford’slaw Examples of Benford Law
  76. wm σ N -6 -4 -2 0 2 4 6 number of measurements 0 2 4 6 8 10 12 14 | wm σ |N -6 -4 -2 0 2 4 6 0 2 4 6 8 10 12 14 2 4 6 med σ N -6 -4 -2 0 2 4 6 number of measurements 0 2 4 6 8 10 12 14 | med σ |N -6 -4 -2 0 2 4 6 0 2 4 6 8 10 12 14 2 4 6 Fig. 1.— Histograms of the error distribution in half standard deviation bins. The top (bot- tom) row uses the weighted mean (median) of the 66 measurements as the central estimate. The left (right) column shows the signed (absolute) deviation. In the left column plots, positive (negative) Nσ represent a value that is greater (less) than the central estimate. | wm σ |N -6 -4 -2 0 2 4 6 Probability Density Funciton 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 2 4 6 | wm σ |N -6 -4 -2 0 2 4 6 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 2 4 6 | med σ |N -6 -4 -2 0 2 4 6 Probability Density Funciton 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 2 4 6 | med σ |N -6 -4 -2 0 2 4 6 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 2 4 6 Fig. 3.— Best fit Cauchy probability density functions. The top left (right) plot represents h |N | di ib i i h l f S 1 (1 6) Th b l f ( i h ) l Primordial Lithium-7 Measurements Crandall , Houston and Ratra arXiv:1409.7332
  77. Error Distributions for Hubble Constant measurements Fit to students-t distribution astro-ph/0308099
  78. Central Limit Theorem o Given an arbitrary distribution h(x) characterized by its mean μ and standard deviation 𝞂, mean of N values xi drawn from that distribution will approximately follow a Gaussian distribution with the accuracy increasing with increasing N. o h(x) must have a standard deviation and therefore its tails must fall off faster than 1/x2 for large x o Central limit theorem can can be derived using method of characteristic functions (arXiv:0712.3028) or repeated convolutions (Gregory 2005). o Central limit theorem does not apply to Cauchy distributions, as it does not have a well-defined mean and standard deviation. o Sample Mean converges to distribution mean as sample size increases. This is called weak law of Large Numbers.
  79. Illustration of Central Limit Theorem Histogram of N random variables (from uniform distribution) drawn from 0 to 1
  80. Bivariate Gaussian Distributions where 𝞀is called population correlation coefficient. For correlated variables 𝞀~ 1. For uncorrelated variables 𝞀= 0
  81. Data from Bivariate Gaussian Distributions Hess plot Ellipses centered on (μx , μy ) Angle between X-axis and ellipse major axis is given by : Correlation between x and y can be eliminated by Principal axis transformation. Correlation between two variables disappears once we rotate the vectors to P1 and P2
  82. Multivariate Gaussian Distributions import numpy as np mu=[1,2] Cov = [[1,0.2],[0.2,0.3]] np.random.multivariate_normal(mu,cov) where x is vector. C is covariance matrix. H is inverse of covariance matrix also called Hessian
  83. Data visualization techniques Simple Scatter plots For more details, see The Visual Display of Quantitative Information by Tufte
  84. Data visualization techniques If density of two points too high, no longer practical to use ordinary ‘scatter plots’. Need to switch to Contour plots. However this loses information in case of only a few points. Use contours for high density region and individual points in low density region (used extensively in SDSS)
  85. Alternatively pixelize the plotted diagram and display the counts of points in each pixel. Known as Hess-diagram For higher dimensions, see section 1.6.2 of astroML book or source code of Figure 1.11 and 1.12
  86. Box and Whisker Plots wikipedia arxiv:1707.01366 Uses quartiles to represent data. In high energy physics a variant of this called profile histogram is used.
  87. Profile Histograms (used in High energy Physics) Not inbuilt in python. Only inbuilt in ROOT programming language. However see https://stackoverflow.com/questions/23709403/plotting-profile-hitstograms-in-python
  88. How to test if two datasets are correlated? Hubble 1929 data showing Expansion of universe
  89. arXiv:1605.00379
  90. Correlation Coefficients Qt : How to quantitatively assess if two datasets {xi} and {yi} of size N are correlated Introduce three such terms : Pearson’s sample correlation coeff. , Spearman rank correlation coeff., and Kendall tau from scipy import stats x,y = np.random.random((2,100)) # two random arrays corr_coeff,p_value = stats.pearsonr(x,y) rho,p_value = stats.spearmanr(x,y) tau,p_value = stats.kendalltau(x,y) P –value indicates the probability of an uncorrelated system producing datasets that have a correlation coefficient at least as extreme as the one computed from these datasets p-value returned From the above correlation coefficients is two-sided or two-tailed p-value
  91. Pearson Correlation Coefficient -1 <= r <=1 For uncorrelated datasets r = 0 If the pairs (xi,yi) are drawn from two uncorrelated univariate Gaussian distributions (i.e. the population correlation coefficient 𝞀=0), distribution of r follows Students t-distribution with k=N-2 degrees of freedom and t given by
  92. Example: N=10 r=0.72 Probability of getting a value as large as the observed value of r which is 0.72 (by chance from a random Fluctuation) is 1% Or one-sided 99% confidence level for Student’s t-distribution with k=8 DOF is t=2.93 >>> import numpy as np >>> x=0.72*np.sqrt(8/(1-0.72*0.72)) >>> x 2.9345009253812004 >>> from scipy.stats import t >>> t.cdf(2.934,8) 0.99253 Cumulative Distribution function of t-distribution
  93. • For bivariate Gaussian distribution with a non-vanishing population correlation coefficient 𝞀, the Fisher transformation (or Fisher z-transformation) can be used to estimate the confidence interval for 𝞀from the measured value of r. The distribution of F is given by: approximately follows a Gaussian distribution with mean μ = F(𝞀) and a standard deviation given by 𝞂F = (N-3) -1/2 Advantages/Disadvantagesof Pearson Correlation Coefficient • r does not take into account errors in xi and yi • r is very sensitive to Gaussian outliers
  94. Spearman Rank Correlation Coefficient Spearman Correlation Coefficient (rs) based on the concept of ranks (sort the data in ascending order and the index i of a value xi in the sorted data is its rank Rix ) Same as Pearson correlation coefficients for the ranks. Distribution of Spearman correlation coeff. (for null hypothesis) is same as Pearson correlation coefficient Alternate definition: (Lupton 93)
  95. • Rank the two datasets. Count the number of concordant pairs, defined by (xj– xk)(yj-yk) > 0 and discordant pairs defined by (xj– xk)(yj-yk) < 0 For a perfect correlation (anti-correlation) all possible N(N-1)/2 pairs will be concordant (discordant) . Kendall’s tau is defined as : -1 ≤ 𝞽≤ 1 • When N> 10 distribution of Kendall tau in case of no-correlation (null hypothesis) can be approximated as a Gaussian distribution with μ=0 and width given by Kendall Tau Correlation Coefficient
  96. • True distributions of Spearman and Pearson correlation coefficient harder to represent analytically in case of a true correlation for a general case • For a bi-variate Gaussian distribution with true correlation coefficient 𝞀expectation value for Kendall’s tau is given by (arXiv:1011.2009) . • Kendall’s co-relation coefficient approaches normality faster than Spearman’s correlation coefficient • Usually, a bootstrap method is used to place confidence estimates on the measured values
  97. Advantages of Kendall tau over Spearman r correlation coeff. • Kendall tau correlation coefficient approaches normality faster than Spearman correlation coefficient • Kendall tau offers a more unbiased estimate of population value while Spearman correlation coeff. does not. (Lupton 1993) • Efficiency of Kendall tau relative to Pearson correlation coefficient for a bi-variate Gaussian greater than 90% and much greater than non-Gaussian distributions.
  98. Distribution of correlation coefficient 2000 bootstrap resamples of 1000 datapoints drawn from a bivariate Gaussian with 𝞀=0.6 without and with (1%) outliers Pearson correlation coefficient not robust against outliers. Spearman and Kendall correlation coefficient have variance which is robust to outliers
  99. Random Number Generation Distributions in scipy.stats.distributions have a method called rvs which generates pseudo—random sample from the distribution. Also numpy.random implements samplers for a number of distributions (look up numpy.random documentation) (behind the scenes, scipy calls numpy) Select 5 random integers between 5 and 10: >>> import numpy as np >>> np.random.random_integers(0,10,5) array([10, 4, 0, 8, 2]) Numerical simulations of measurement processes are called Monte Carlo simulations and the resulting samples are called Monte Carlo or mock samples. See discussion in Numerical Recipes on how to generate random number distributions
  100. Parameter Estimation to bivariate Gaussian distribution • For 1-D Gaussian mean and standard deviation can be estimated from sample mean and sample variance . This can be extended to 2-D • Correlation coefficient (𝞀) can be estimated using Pearson’s sample correlation coefficient. Principal axes can be found with α estimated using However this doesn’t work in case of outliers. 𝞂x and 𝞂y can estimated from interquartile range (or MAD).
  101. u = p 2 ✓x σx + y σy ◆ v = p 2 ✓x σx −y σy ◆ ⇢= Vu −Vw Vu + Vw Robust estimate of r Ref : Shevlyakov and Smirnov, Austrian Journal of Statistics, 40, 147-156 (2011)
  102. From astroML.stats import fit_bivariate_normal (mu_r,sigma1_r,sigma2_r,alpha_r) = fit_bivariate_normal(x,y,robust=True) Python Code for robust estimate of bivariate dist params
  103. An example of computing the components of a bivariate Gaussian using a sample with 1000 data values (points), with two levels of contamination. The core of the distribution is a bivariate Gaussian with The “contaminating” subsample contributes 5% (left) and 15% (right) of points centered on the same , and with . Ellipses show the 1- and 3-sigma contours. The solid lines correspond to the input distribution. The thin dotted lines show the nonrobust estimate, and the dashed lines show the robust estimate of the best-fit distribution parameters (see Section 3.5.3 for details).
  104. EP 4130/PH6130 Second and Third Week
  105. Frequentist Parameter Estimation Numerical Recipes 1992 edition Chapter 15 Bevington arXiv: 0712.3028 by L. Verde AstroMl treatment of the above subject will be discussed later using more “formal’’ notations • Estimate best fit parameters of a model (function) given data and associated errors. • Error estimates on the parameters. • Statistical Measure of Goodness of fit.
  106. Maximum likelihood Estimation • Maximize the probability of data given the parameters or the likelihood of the data given the parameters . This form of parameter estimation is called maximum likelihood estimation Consider data points yi with measurement errors σi which is independent and has a Gaussian distribution around the true model (or the function) To get maximum likelihood estimate dP/d𝛳= 0
  107. Least-Squares Minimization Best-fit parameters are obtained by minimizing chi-square For models that are linear in theta, probability distribution of 𝝌2 is chi-square PDF with ν= N-M degrees of freedom, where N is the number of data points and M is the number of free parameters. A rule of thumb : 𝝌2 ~ ν for a good fit (sometimes called “chi by eye”) < 𝝌2> = ν and its standard deviation = sqrt(ν) Reduced chi-square = 𝝌2 / ν
  108. Chi-Square G.O.F (Numerical Recipes Notation) Probability that observed for a correct model is less than a particular value Is given by the cdf of the chi-square probability distribution where Γ is the incomplete gamma function. (Refer to Numerical Recipes Chap 6 & 15 for notation) is the probability that the observed should exceed a particular value by chance Q is a quantitative measure of goodness of fit of a model is sometimes called chi-square GOF. This is called p-value
  109. Chi-Square Probability and Goodness of Fit Chi-square probability or Chi-square likelihood for chi-square=Q and DOF by k is given by p-value or chi-square goodness of fit Probability of finding 𝝌2 min as high as the one we got or higher if hypothesis is correct and is called p-value Chi-square c.d.f given in terms of P(n/2,c2/2) (regularized Gamma function) P(a, x) = 1 Γ(a) Z x 0 e−tta−1dt
  110. How to calculate p-value from chi-square ( c2) and Degrees of freedom (n) in python OR stats.chi2(ν).sf(𝝌2) Chi-square likelihood in Python stats.chi2(ν).pdf(𝝌2) Chi-Square Probability and GOF in Python
  111. If p-value is a very small o Model is wrong and can be rejected. o Errors are really smaller than stated. o Measurement errors are not Gaussianly distributed. If p-value is a very large or close to 1 o Errors maybe overestimated o Data are correlated and correlations are ignored in the fit o Distribution is more compact than a Gaussian distributed. But this is almost never the case.
  112. Astroml figure 4.1 No of sigmas = (reduced 𝝌-1)/(Error in Reduced 𝝌) Error in Reduced 𝝌= 1/√2(N-1)
  113. Confidence Intervals A confidence region (or confidence interval) is a region of M-dimensional space that contains a certain percentage (fraction) of the total probability distribution. For eg. 99% confidence region implies that there is 99 % chance that the true parameter value falls within this region around the measured value. (Note that Bayesians use a different definition) Usually in Physics/Astrophysics literature what is plotted in papers is 68.3%, 95.4% and 99.7% Confidence level. These are obtained by contours of constant Δ𝝌2 around the minimum 𝝌2 There is formal mathematical relation between Δ𝝌2 , confidence intervals and standard errors.
  114. Confidence Intervals (single parameter) arXiv: 1009.2755
  115. • Prev. equation does not uniquely define a C.I. in case of an asymmetric distribution. C.I. (single parameter, asymmetric distribution)
  116. Example of asymmetric likelihood
  117. Confidence Intervals in > 1 dimension One sigma contour of a 2-d gaussian marks a 39.4% confidence region.
  118. 68% confidence interval on a2 68% confidence interval on a1 68% confidence region on a1 and a2 jointly bias a(i)1 − a(0)1 (s) Usually people plot the joint confidence region on both parameters of interest Ref: Numerical Recipes 1992 ed . Chapter 15
  119. Cookbook for Confidence Intervals Numerical Recipes (1992) Sect 15.6 o Assume μ is the number of free parameters for which you want to plot the joint confidence interval and p% is the confidence limit desired . o Δ𝝌2 is distributed as a chi-square distribution with μ degrees of freedom. Δ𝝌2 = 𝝌2 - 𝝌2min Calculate Δ𝝌2 such that chi-square probability for μ free parameters is less than p. P(𝝌2 < Δ𝝌2 , μ ) = p% ⌫ p 1 2 3 4 5 6 68.3% 1.00 2.30 3.53 4.72 5.89 7.04 90% 2.71 4.61 6.25 7.78 9.24 10.6 95.4% 4.00 6.17 8.02 9.70 11.3 12.8 99% 6.63 9.21 11.3 13.3 15.1 16.8 99.73% 9.00 11.8 14.2 16.3 18.2 20.1 99.99% 15.1 18.4 21.1 23.5 25.7 27.8 Δ𝝌2 tables as a function of number of free parameters (p) and confidence level (%) Numerical recipes Sect 15.6
  120. Delta chi-square Intervals in python >>> stats.chi2(2).cdf(2.3) 0.68336323062094673 Inverse of cdf in scipy is ppf >>> stats.chi2(2).ppf(0.6833) 2.2996006508750853
  121. C B A Z ′ Z C′ ∆χ2 = 6.63 ∆χ2 = 2.71 ∆χ2 = 1.00 ∆χ2 = 2.30 A′ B′ Figure 15.6.4. Confidence region ellipses corresponding to values of chi-square larger than the fitted minimum. The solid curves, with ∆χ2 = 1.00, 2.71,6.63 project onto one-dimensional intervals AA0, BB0, CC0. These intervals — not the ellipses themselves — contain 68.3%, 90%, and 99% of normally distributed data. The ellipse that contains 68.3% of normally distributed data is shown dashed, and has ∆χ2 = 2.30. For additional numerical values, see accompanying table. Ref: Numerical Recipes 1992 ed . Chapter 15
  122. How to calculate projected 1-D errors Numerical Recipes (1992) Sect 15.6 For one variable This gives relation between formal standard error 𝞂11 = sqrt(C11) and confidence interval (da1) [C] = covariance matrix = Inverse of Fisher Information matrix or Inverse of curvature matrix (to be defined later) 68% confidence interval 1 𝞂 95% confidence interval 2 𝞂 99% confidence interval 3 𝞂 Note that this is valid only for 1 dimensions
  123. 10 -1 1 10 10 2 -1 -0.5 0 0.5 1 10 -1 1 10 -1 -0.5 0 0.5 1 e-like µ-like FC PC (U-D)/(U+D) Momentum (GeV/c) ( )/( ) χ2 = ! cosΘ,p (NDATA −NMC)2/σ2 + ! j ϵ2 j/σ2 j, hep-ex/9807003 Best-fit 𝝌2 = 65.2 for 67 DOF
  124. νµ - ντ Kamiokande Super-Kamiokande 68% 90% 99% sin22θ ∆m2 (eV2) 0 0.2 0.4 0.6 0.8 1 10 -4 10 -3 10 -2 10 -1 1 FIG. 2. The 68%, 90% and 99% confidence inter- vals are shown for sin2 2θ and ∆m2 for νµ ↔ντ two-neutrino oscillations based on 33.0 kiloton-years of Super–Kamiokande data. The 90% confidence in- terval obtained by the Kamiokande experiment is also shown. Δ𝝌2 intervals of 2.6,5.0, and 9.6 Correspond to 68%,90% and 99% confidence intervals hep-ex/9807003 2015 Physics Nobel Prize
  125. 68.3%, 95.4% and 99.7% confidence levels arXiv:1105.3470 χ2 stat = ! SNe [µB(α, β, δ, MB) −µ(z; Ωm, Ωw, w)]2 σ2 lc + σ2 ext + σ2 sample . 2011 Physics Nobel Prize
  126. Generalization of chi-square for Poisson data o In case of bins with very low counts (or Poisson data) for comparing models with data we use : In astrophysical literature ONLY, C is called Cash statistics or C-stat. Based on C , one can calculate goodness of fit of a model in the same way as for a Gaussian distribution. Also this can be used for model comparison as ΔC between two models of parameters also has a 𝝌2 distribution with DOF = no of free parameters Cash ApJ 229, 939 (1979) Baker and Cousins, NIM 221, 437 (1984)
  127. Derivation of Cash statistics o Obtained from likelihood ratio test. Ref. Baker and Cousins, NIM 221, 437 (1984) Define where n = observed data and y= expected model where asymptotically obeys chi-square distribution (Wilk’s theorem) and evaluates to the definition of Cash statistics on previous slide λ = Lp(y, n) Lp(n, n) Lp(y, n) = Y i exp(−yi)yn i /n! Lp(n, n) = Y i exp(−ni)nni i /ni! χ2 = −2 ln λ
  128. 1979ApJ...228..939C
  129. Recent exposition on Cash statistic arXiv:1912.05444
  130. Relation between Cash statistic and c2 arXiv:1912.05444
  131. FIG. 3: Comparison of the Far Detector spectrum with pre- dictions for no oscillations for both analysis methods and for oscillations with the best-fit parameters from the Beam Ma- trix extrapolation method. The estimated NC background is also shown. The last energy bin contains events between 18-30 GeV. χ2 = ! nbins (2(ei −oi) + 2oi ln(oi/ei)) + ! nsys ∆s2 j σ2sj Example of usage of Cash statistics hep-ex/0607088
  132. Disconnect in usage of nomenclature The jargon “Cash statistics” is used only in Astrophysics and NOT in particle physics hep-ex/0607088 (Particle Physics) arXiv:1512.01244 (Astrophysics)
  133. ) 23 θ (2 2 sin 0.2 0.4 0.6 0.8 1.0 ) 4 /c 2 | (eV 32 2 m ∆| 1.5 2.0 2.5 3.0 3.5 4.0 -3 10 × MINOS Best Fit MINOS 90% C.L. MINOS 68% C.L. K2K 90% C.L. SK 90% C.L. SK (L/E) 90% C.L. ) 23 θ (2 2 sin 0.2 0.4 0.6 0.8 1.0 ) 4 /c 2 | (eV 32 2 m ∆| 1.5 2.0 2.5 3.0 3.5 4.0 -3 10 × hep-ex/0607088 (based on minimization of Cash statistics)
  134. 𝝌2 including covariances Y = 2 664 y1 y2 · · · yN 3 775 , A = 2 664 1 x1 1 x2 · · · 1 xN 3 775 , C = 2 664 σ2 y1 0 · · · 0 0 σ2 y2 · · · 0 · · · 0 0 · · · σ2 yN 3 775 χ2 = N X i=1 [yi −f(xi)]2 σ2 yi ⌘[Y −A X] > C−1 [Y −A X] (Definition of C above includes no-correlations in errors and hence off-diagonal elements are 0. Also A above is only true for a straight line fit of the form y=Ax+c) Y = A X More details in arXiv:1008.4686
  135. MLE in case of Truncated/Censored Data • Truncation : when S(x) = 0 for x> xmax or x< xmin • Censoring : Measurement of an existing source only resulted in upper limits MLE in case of truncation becomes : where the normalization constant C is given by:
  136. • There is no uniform method to deal with this. Multiple methods used (BCES, ODR, etc) Some references: physics/051182 by Guido D’agostini astro-ph/9605002 by Akritas and Bershady arXiv:0705.2774 Also other techniques such as Orthogonal Distance Regression Simplest recipe as follows: If σx and σy denote the error in X (independent) and Y (dependent) variables, then total error σt is given by Chi-square for errors in X-variable σt = s σ2y + ✓@f @x ◆2 σ2x σt can be plugged in the expression for 𝝌2 in the denominator
  137. Classical Statistical Inference (astroML) • Point Estimation : Best estimate for a model parameter based on available data • Confidence Estimation : How confident should we be in our point estimate • Hypothesis Testing : Are data consistent with a given hypothesis or model? Two types of statistical paradigms to address the statistical inference questions : classical or Frequentist paradigm and the Bayesian paradigm.
  138. Likelihood Function • Starting point of both MLE and Bayesian estimation is likelihood of the data. The data likelihood represents a quantitative description of our measuring process also called P(D|M) where M stands for the model and 𝛳is model parameter vector • Although the interpretation of L is the probability of the data given the model, L is not a true properly normalized PDF. Likelihood of a single data point is a pdf. But the product of such functions is no longer normalized to 1. • Likelihood is a function of both the data and the model. Best-fit Model parameters which maximize P(D|M) are called point estimates.
  139. Frequentist Bayesian Probabilities refer to relative frequencies of events Refer to degree of subjective belief, not limiting frequency Parameters are fixed unknown constants. Probability statements about parameters are meaningless Probability statements can be made about things other than data including the model parameters and models themselves. Frequentists consider model parameters to be fixed and data to be random Bayesians consider data to be fixed and model parameters to be random Confidence intervals should have well-defined long run frequency properties. 95% c.i. should bracket the true value of the parameter with a limiting frequency of at least 95%. Inferences about a parameter are made by producing its probability. Distribution quantifies amount of uncertainty of our knowledge about the parameter. These are called credible intervals. Bayesian data analysis often computationally intensive compared to frequentist analysis
  140. Maximum Likelihood Estimators • They are consistent estimators; they converge to the true parameter values as the number of data points increases. • They are asymptotically normal estimators. The distribution of the parameter estimate, as the number of data points increase to infinity approaches a normal distribution centered on MLE with a certain spread. • They asymptotically achieve the theoretical minimum possible variance called Cramer- Rao bound (they achieve best possible error given the data at hand)
  141. MLE Confidence Intervals • We first compute the error matrix or Fisher information matrix. • Inverse of the Fisher information matrix gives a lower bound on the variance of any unbiased estimator of 𝛳. This is called Cramer-Rao bound. • Diagonal elements of σ correspond to marginal parameters for 𝛳. IF non-diagonal elements are 0, inferred values of parameters are uncorrelated.
  142. To estimate a parameter we have various tools such as maximum likelihood, least squares, etc. Usually one also needs to know the variance (or the full sampling distribution) of the estimator – this can be more difficult. Often use asymptotic properties, e.g., sampling distribution of ML estimators becomes Gaussian in large sample limit; std. dev. from curvature of log-likelihood at maximum. The jackknife and bootstrap are examples of “resampling” methods used to estimate the sampling distribution of statistics. In HEP we often do this implicitly by using Toy MC to determine sampling properties of statistics (e.g., Brazil plot for 1σ, 2σ bands of limits). Jackknife, bootstrap, etc. Glenn Cowan Lecture notes
  143. The Bootstrap (Efron, 1979) Idea is to produce a set of “bootstrapped” data samples of same size as the original (real) one by sampling from some distribution that approximates the true (unknown) one. By evaluating a statistic (such as an estimator for a parameter θ) with the bootstrapped-samples, properties of its sampling distribution (often its variance) can be estimated. If the data consist of n events, one way to produce the bootstrapped samples is to randomly select from the original sample n events with replacement (the non-parametric bootstrap). That is, some events might get used multiple times, others might not get used at all. In other cases could generate the bootstrapped samples from a parametric MC model, using parameter values estimated from real data in the MC (parametric bootstrap). Glenn Cowan lecture notes
  144. The Bootstrap (cont.) Call the data sample x = (x1,... xn), observed data are xobs, and the bootstrapped samples are x1*, x2*, ... Idea is to use the distribution of as an approximation for the distribution of In the first quantity everything is known from the observed data plus bootstrapped samples, so we can use its distribution to estimate bias, variance, etc. of the estimator θ. ˆ Glenn Cowan lecture notes
  145. Bootstrap Resampling • Bootstrap and Jackknife methods rely on resampling of the dataset {xi} (instead of generating them from probability distributions). • We do not know h(x) [parent distribution of data] and the best we can do is computations relying on various estimates of h(x), based upon the data (called f(x)). Bootstrapping is based upon the approximation f(x) maximizes the probability of obtaining h(x) and is the MLE of h(x). Therefore, f(x) can be used as a proxy for h(x). Basic idea of bootstrap is to draw new samples from the measured dataset itself. Drawing these ``bootstrap’’ resamples can be done with replacement , i.e. same data point can occur multiple times in our data sample. (Non-parametric bootstrap). For more details see Efron (1979); Lupton (1993); G.J. Babu lecture notes in PSU school
  146. The bootstrap uncertainty estimates for the sample standard deviation (dashed line; see eq. 3.32) and (solid line; see eq. 3.36). The sample consists of N = 1000 values drawn from a Gaussian distribution with and . The bootstrap estimates are based on 10,000 samples. The thin lines show Gaussians with the widths determined as (eq. 3.35) for and (eq. 3.37) for . σG = 0.7413(q75 –q25) Formulae for Standard error for σ and σG provided In astroML book Example of Bootstrap Resampling
  147. Invented by Quenouille (1949) and Tukey (1958). Suppose data sample consists of n events: x = (x1,... xn). We have an estimator θ(x) for a parameter θ. Idea is to produce pseudo data samples xi = (x1,..., xi1, xi+1,... xn) by leaving out the ith event. ˆ The Jackknife See, e.g., Notes on Jackknife and Bootstrap by G. J. Babu: www.iiap.res.in/astrostat/School10/LecFiles/ JBabu_JackknifeBootstrap_notes.pdf Glenn Cowan lecture notes
  148. Bias-corrected Jackknife estimate of α is given by: Assume α is the jackknife estimate of the sample (with one data point removed) and αN is the value estimated from the full dataset. Standard error for a jackknife estimator is given by: (1) (2)
  149. o Confidence Limits for α can be computed using Student’s t-distribution with t defined as : with N-1 degrees of freedom. o Jackknife standard error is more reliable than jackknife bias correction. o Jackknife bias correction completely fails for any robust statistics (median, quantiles, rank-based statistics. Qt: Should one use bootstrap or jacknife? For smooth statistics they produce similar results. Bootstrap better for calculating confidence intervals In Machine learning , cross-validation and aggregating are closely related to jackknife and bootstrap
  150. The jackknife uncertainty estimates for the width of a Gaussian distribution. This example uses the same data as figure 4.3. The upper panel shows a histogram of the widths determined using the sample standard deviation, and using the interquartile range. The lower panel shows the corrected jackknife estimates (eqs. 4.33 and 4.35) for the two methods. The gray lines show the theoretical results, given by eq. 3.35 for and eq. 3.37 for . The result for matches the theoretical result almost exactly, but note the failure of the jackknife to correctly estimate (see the text for a discussion of this result). Computed using (1) and (2) Expected distribution for 𝞂G Pdf from jacknife mean and sigma for sigma)G Pdf from jacknife mean and sigma for sigma
  151. Jackknife & Bootstrap Functions in AstroML from astroML.resample import jackknife [mean,stddev,raw_distribution] = jackknife(data,user_statistic,kwargs,return_raw_distribution,pass_indices) Example: mu1,sigma_mu1,mu1_raw = jackknife(data,np.std,kwargs=dict(axis=1,ddof=1),return_raw_distrbution=True ) astroML.resample.bootstrap(data,n_bootstraps,user_statistic,kwargs,pass_indi ces,random_state) Example: mu2_bootstrap = bootstrap(data,n,sigmaG,kwargs=dict(axis=1)) Lookup astroML.resample.jacknife and astroML.resample.bootstrap for full documentation
  152. Jackknife and Bootstrap Notes by G. Jogesh Babu Center for Astrostatistics The Pennsylvania State University
  153. 1 Introduction It is often relatively simple to devise a statistic that measures the property of in- terest, but is almost always difficult or impossible to determine the distribution of that statistic. The classical statistical methods concentrated mainly on the statis- tical properties of the estimators that have a simple closed form and which can be analyzed mathematically. Except for a few important but simple statistics, these methods involve often unrealistic model assumptions. These limitations have been overcome in the last two decades of the 20th Century with advances in electronic computers. A class of computationally intensive procedures known as resampling methods provide inference on a wide range of statistics under very general condi- tions. Resampling methods involve constructing hypothetical ‘populations’ derived from the observations, each of which can be analyzed in the same way to see how the statistics depend on plausible random variations in the observations. Resam- pling the original data preserves whatever distributions are truly present, including selection effects such as truncation and censoring. Perhaps the half-sample method is the oldest resampling method, where one re- peatedly chooses at random half of the data points, and estimates the statistic for each resample. The inference on the parameter can be based on the histogram of the resampled statistics. It was used by Mahalanobis in 1946 under the name interpen- etrating samples. An important varia
  154. Jackknife estimator θJ of θ is given by θJ = ˆθn −biasJ = 1 n n X i=1 ¡ nˆθn −(n −1)ˆθn,−i ¢ . (2) Such a bias corrected estimator hopefully reduces the over all bias. The summands above θn,i = ˆθn −(n −1)ˆθn,−i, i = 1, . . . , n are called pseudo-values. 2.1 Bias Reduction Jackknifing, indeed, helps in reducing bias of an estimator in many cases. Suppose the expected value of the estimator ˆθn is of the form E(ˆθn) = θ + a n + b n2 , then clearly, E(ˆθn,i) = θ − b n(n −1). Consequently, the bias of the jackknife estimator is E(θJ) −θ = O(n−2), which is of lower order than the bias of ˆθn. 2.2 Estimation of variance In the case of the sample mean ˆθn = ¯Xn, it is easy to check that the pseudo-values are simply, θn,iˆθn −(n −1)ˆθn,−i = Xi, i = 1, . . . , n. This provides motivation for the jackknife estimator of variance of ˆθn, varJ(ˆθn) = 1 n(n −1) n X i=1 (θn,i −θJ)(θn,i −θJ)′ = n −1 n n X i=1 (ˆθn,−i −¯θn)(ˆθn,−i −¯θn)′, (3) where ¯θn = 1 n Pn i=1 ˆθn,−i. For most statistics, jackknife estimator of variance is consistent, i.e., V arJ(ˆθn)/V ar(ˆθn) →1, as n →∞almost surely. This holds in particular for a smooth functional model. To describe this, let the statistic of interest ˆθn based on n data points be defined by H( ¯Zn), where ¯Zn is the sample mean of multivariate random variables Z1, . . . , Zn and H is continuously differentiable in a neighborhood of E( ¯Zn). Many commonly occurring statistics, including: Sample Means, Sample Variances, Central and Non- central t-stati
  155. Variation, Maximum Likelihood Estimators, Least Squares Estimators, Correlation Coefficients, Regression Coefficients, Smooth transforms of these statistics, fall un- der this model. However, consistency does not always hold; for example the jackknife method fails for non-smooth statistics, such as the sample median. If ˆθn denotes the sample median in the univariate case, then in general, V arJ(ˆθn)/V ar(ˆθn) → µ1 2χ2 2 ¶2 in distribution, where χ2 2 denotes a chi-square random variable with 2 degrees of freedom (see Efron 1982, §3.4). So in this case, the jackknife method does not lead to a consistent estimator of the variance. However, a resampling method called bootstrap discussed in the next section, would lead to a consistent estimator. 3 Bootstrap The importance of the bootstrap emerged during the 1980s when mathematical study demonstrated that it gives nearly optimal estimate of the distribution of many statistics under a wide range of circumstances. In several cases, the method yields better results than those obtained by the classical normal approximation theory. However, one should caution that bootstrap is not the solution for all problems. The theory developed in 1980s and 1990s, show that bootstrap fails in some ‘non- smooth’ situations. Hence, caution should be used and should resist the temptation to use the method inappropriately. Many of these methods work well in the case of smooth functional model. 3.1 Description of the bootstrap method Let X = (X1, . . . , X
  156. For statistics with asymmetrical distributions, such as that of ˆρn, the classical theory suggests variable transformations. In this case, Fisher’s Z-transformation Z given by Z = p (n −3) 2 µ ln µ1 + ˆρn 1 −ˆρn ¶ −ln µ1 + ρ 1 −ρ ¶¶ gives a better normal approximation. is approximately normally distributed. This approximation corrects skewness and is better than the normal approximation of √n(ˆρn −ρ). The bootstrap method, when properly used, avoids such individual transformations by taking into account the skewness of the sampling distribution. It automatically corrects for skewness. The bootstrap method presumes that if ˆFn is a good approximation to the unknown population distribution F, then the behavior of the samples from ˆFn closely resemble that of the original data. Here ˆFn can be the empirical distribution function (EDF, or a smoothed EDF) of the data X1, . . . , Xn, or a parametric estimator of the function F. Once ˆFn is provided, datasets X∗= (X∗ 1, . . . , X∗ n) are resampled from ˆFn and the statistic Tn(X∗) is computed for each resample. Under very general conditions (see Babu & Singh (1984)), it can be shown that the difference between the sampling distribution Gn of Tn(X)−T(F) and the ‘bootstrap distribution’ Gb [ie the distribution of Tn(X∗) −T( ˆFn)] is negligible. Gb can be used to draw inferences about the parameter T(F) in place of the unknown Gn. In principle, Bootstrap distribution (Histogram) Gb is completely known, as it is constructed entirely from
  157. Table 1: Statistics and their bootstrap versions Statistic Bootstrap Version Mean, ¯Xn ¯X∗ n Variance, 1 n Pn i=1(Xi −¯Xn)2 1 n Pn i=1(X∗ i −¯X∗ n)2 Ratio estimator, ¯Xn/ ¯Yn ¯X∗ n/ ¯Y ∗ n Correlation coefficient, Pn i=1(XiYi−¯ Xn ¯Yn) q ( Pn i=1(Xi−¯ Xn)2)( Pn i=1(Yi−¯Yn)2) Pn i=1(X∗ i Y ∗ i −¯ X∗ n ¯Y ∗ n ) q ( Pn i=1(X∗ i −¯ X∗n)2)( Pn i=1(Y ∗ i −¯Y ∗ n )2) possible to obtain confidence intervals or approximate confidence intervals for µ, if P(( ¯X −µ)/σ < x) does not depend on µ and σ. Unless the limiting distribution is free from the unknown parameters, once can not invert it to get confidence intervals. It is thus important to focus on pivotal or approximately pivotal quantities in order to get reliable confidence intervals for the parameter of interest. A function Tn(X; F) is pivotal, if its distribution is free from the unknown pa- rameters of F. In case, Xi ∼N(µ, σ2), then Tn(X; F) = √n( ¯X −µ)/sn is pivotal. In non-normal case, it is approximately pivotal. To obtain bootstrap confidence interval for µ, we compute √n( ¯X∗(j) −¯X)/sn for N bootstrap samples, arrange the values in increasing order h1 < h2 < · · · < hN. One can then read offfrom the histogram (say) the 90% confidence interval of the parameter. That is, the 90% confidence interval for µ is given by ¯X −hm sn √n ≤µ < ¯X −hk sn √n, where k = [0.5N] and m = [0.95N]. Babu & Singh (1983) have shown that N(log n)2 bootstrap iterations would be sufficient. It is important to note that even when σ is known the bootstrap ver
  158. coefficient ρ. The sample correlation coefficient ˆρn based on the data (Xi, Yi), i = 1, . . . , n, can be expressed as ˆρn = H(¯Zn), and ρ∗= H(¯Z∗ n), where Zi = (XiYi, X2 i , Y 2 i , Xi, Yi), Z∗ i = (X∗ i Y ∗ i , X∗2 i , Y ∗2 i , X∗ i , Y ∗ i ) and H(a1, a2, a3, a4, a5) = (a1 −a4a5) p ((a2 −a2 4)(a3 −a2 5)) . Note that H is a differentiable function. In general, if the standard deviation of Tn(X; F) is not known (which is often the case), the function may be divided by a good estimator of the standard deviation of the statistic. This makes it an ‘approximate pivotal’ quantity. Such a correction by a special type of estimator of standard deviation for the smooth function model refers to Studentization, as it is similar to the Student’s t-statistic. The empirical distribution of the data is used to estimate the standard deviation of the statistic in a special way, making it an ‘approximate pivotal’ quantity. For the smooth function model, a good estimator of the variance of √nH(¯Zn) is given by ˆσ2 = ℓT (¯Zn)Σnℓ(¯Zn), where ℓ(x) denotes the vector of first order partial derivatives of H at x, T denotes transpose, and Σn denotes the variance-covariance matrix computed from the {Zi}. That is, Σn = 1 n n X i=1 (Zi −¯Zn)(Zi −¯Zn)T . (4) This leads to Studentization or approximate pivotal function tn = √n(H(¯Zn) −H(E(Z1))/ˆσ (5) Its bootstrap version is t∗ n = √n(H(¯Z∗ n) −H(¯Zn))/ q ℓT (¯Z∗n)Σ∗nℓ(¯Z∗n), (6) where Σ∗ n denotes the variance-covariance matrix computed from the bootstrap s
  159. The ‘error’ terms are so small that √n|P(tn ≤x) −P∗(t∗ n ≤x)| →0. The theory above is applicable in very general set up that includes the statis- tics: Sample Means, Sample Variances, Central and Non-central t-statistics (with possibly non-normal populations), Sample Coefficient of Variation, Maximum Like- lihood Estimators, Least Squares Estimators, Correlation Coefficients, Regression Coefficients, and Smooth transforms of these statistics. Thus the sampling distribution of several commonly occurring statistics are closer to the corresponding bootstrap distribution than the normal distribution. These conditional approximations are suggestive of the unconditional ones, though one cannot be derived from the other by elementary methods. Babu & Bose (1988) provide theoretical justification for the accuracy of the bootstrap confidence inter- vals both in terms of the actual coverage probability achieved and also the limits of the confidence interval. In spite of these positive results, one should use caution in using bootstrap methods. It is not a ‘cure all’ solution. There are cases where bootstrap method fails. These include, non-smooth statistics such as ˆθ = max1≤i≤n Xi (see Bickel & Freedman (1981)), heavy tailed distributions, ˆθ = ¯X and EX2 1 = ∞(see Babu (1984) and Athreya (1987)), and asymptotically non-linear statistics such as, ˆθ−θ = H(¯Zn) −H(E(Z1) when ∂H(E(Z1)) = 0. In the last case the limiting distribution is like that of linear combinations of Chi-squares, but here a m
  160. However the variances of these estimators are different for a random and fixed de- signs, though the difference is very small for large n. We shall concentrate on the fixed design case here. The variance of the slope ˆβ is given by var(ˆβ) = n X i=1 (Xi −¯Xn)2σ2 i /S2 XX, (11) and depends on the individual error deviations σi, which may or may not be known. Knowledge of var(ˆβ) provides the confidence intervals for β. Several resampling methods are available in the literature to estimate the sampling distribution and var(ˆβ). We consider three bootstrap procedures: a) the classical bootstrap, b) weighted bootstrap, c) the paired bootstrap. The classical bootstrap Let ˆei denote the residual of the i-th element of ˆei = Yi −ˆα −ˆβXi and define ˜ei to be ˜ei = ˆei −1 n n X j=1 ˆej. (12) A bootstrap sample is obtained by randomly drawing e∗ 1, . . . , e∗ n with replacement from ˜e1, . . . , ˜en. The bootstrap estimators β∗and α∗of the slope and the intercept are given by β∗−ˆβ = SXe∗/SXX and α∗−ˆα = (ˆβ −β∗) ¯Xn + ¯e∗ n. (13) To estimate the sampling distribution and variance, the procedure is repeated N times to obtain β∗ 1, . . . , β∗ N where N ∼n(log n)2. (14) The histogram of these β∗s give a good approximation to the sampling distribution of ˆβ and the estimate of the variance ˆβ is given by varBoot = 1 N N X j=1 (β∗ j −ˆβ)2. (15) This variance estimator is the best among all the three methods proposed here, if the residuals are homoscedastic; i.e. if the variances of the residua
  161. sample ( ˜X1, ˜Y1), . . ., ( ˜Xn, ˜Yn) is drawn from (X1, Y1), . . ., (Xn, Yn) and the paired bootstrap estimators of slope and intercept are constructed as ˜β = Pn i=1( ˜Xi −¯˜X)( ˜Yi −¯˜Y ) Pn i=1( ˜Xi −¯˜X)2 , and ˜α = ¯˜Y −˜β ¯˜X The variance is obtained by repeating the resampling scheme N times and applying equation (15). Figure 1 provides a simple FORTRAN code for jackknife and paired bootstrap resampling. C PAIRED BOOTSTRAP RESAMPLING NSIM = INT(N * ALOG(FLOAT(N))**2) DO 20 ISIM = 1,NSIM DO 10 I = 1,N J = INT(RANDOM * N + 1.0) XBOOT(I) = X(J) 10 YBOOT(I) = Y(J) 20 CONTINUE C JACKKNIFE RESAMPLING DO 40 NSIM = 1,N D0 30 I = 1,N-1 IF(I.LT.NSIM) XJACK(I) = X(I) YJACK(I) = Y(I) ELSE XJACK(I) = X(I+1) YJACK(I) = Y(I+1) ENDELSE 30 CONTINUE 40 CONTINUE Figure 1: FORTRAN code illustrating the paired bootstrap and jackknife resam- pling for a two dimensional dataset (xi, yi), i = 1, . . . , N. The bootstrap methodology, mathematics and second order properties are re- viewed in Babu & Rao (1993). A detailed account of second order asymptotics can be found in Hall (1992). A less mathematical overview of the bootstrap is presented in Efron and Tibshirani (1993). The book by Zoubir & Iskander (2004) serves as a handbook on ‘bootstrap’ for engineers, to analyze complicated data with little or no model assumptions. Bootstrap has found many applications in engineering field including, artificial neural networks, biomedical engineering, environmental en- gineering, image processing, and
  162. References [1] Athreya, K. B. (1987). Bootstrap of the mean in the infinite variance case. Ann. Statist., 15, no. 2, 724-731. [2] Babu, G. J. (1984). Bootstrapping statistics with linear combinations of chi- squares as weak limit. Sankhya, Series A, 46, 85-93. [3] Babu, G. J. (1986). A note on bootstrapping the variance of the sample quantile. Ann. Inst. Statist. Math., 38, Part A, 439-443. [4] Babu, G. J., and Bose, A. (1988). Bootstrap confidence intervals. Statistics and Probability Letters, 7, 151-160. [5] Babu, G. J., and Rao, C. R. (1993). Bootstrap methodology. In Handbook of Statistics, Vol. 9 “Computational Statistics.” C. R. Rao (Ed.), Elsevier Science Publishers B. V., Amsterdam, 627-659. [6] Babu, G. J., and Singh, K. (1983). Inference on means using the bootstrap. Annals of Statistics, 11, 999-1003. [7] Babu, G. J., and Singh, K. (1984a). On one term Edgeworth correction by Efron’s Bootstrap. Sankhya, Series A, 46, 219-232. [8] Babu, G. J., and Singh, K. (1984b). Asymptotic representations related to jackknifing and bootstrapping L-statistics. Sankhy¯a, Series A, 46, 195-206. [9] Bickel, P. J., and Freedman, D. A. Some asymptotic theory for the bootstrap. Ann. Statist., 9, no. 6, 1196–1217. [10] Efron, B. (1979). Bootstrap methods: another look at the jackknife. Ann. Statist., 7, no. 1, 1-26. [11] Efron, B. (1982). The jackknife, the bootstrap and other resampling plans. CBMS-NSF Regional Conference Series in Applied Mathematics, 38. Society for Industrial and Appli
  163. Goodness-of-Fit using bootstrap Notes by G. Jogesh Babu Center for Astrostatistics The Pennsylvania State University
  164. 1 The Problem of Model Selection and Fitting The aim of model fitting is to provide most parsimonious ‘best’ fit of a parametric model to data. It might be a simple, heuristic model to phenomenological relation- ships between observed properties in a sample of astronomical objects. Examples include characterizing the Fundamental Plane of elliptical galaxies or the power law index of solar flare energies. Perhaps more important are complex nonlinear models based on our astrophysical understanding of the observed phenomenon. Here, if the model family truly represents the underlying phenomenon, the fitted parame- ters give insights into sizes, masses, compositions, temperatures, geometries, and evolution of astronomical objects. Examples of astrophysical modeling include: • Interpreting the spectrum of an accreting black hole such as a quasar. Is it a nonthermal power law, a sum of featureless blackbodies, and/or a thermal gas with atomic emission and absorption lines? • Interpreting the radial velocity variations of a large sample of solar-like stars. This can lead to discovery of orbiting systems such as binary stars and exo- planets, giving insights into star and planet formation. • Interpreting the spatial fluctuations in the cosmic microwave background ra- diation. What are the best fit combinations of baryonic, Dark Matter and Dark Energy components? Are Big Bang models with quintessence or cosmic strings excluded? The mathematical procedures used to link data with astrophysical
  165. pre-main sequence stars in the Orion Nebula region for 13 days (Getman et al. 2005). But it could easily be an optical spectrum of a high-redshift starburst galaxy, or a millimeter spectrum of a collapsing molecular cloud core, or the spectrum of a gamma-ray burst at the birth of a black hole. The histogram in Figure 1a shows the best-fit astrophysical model assuming a plausible emission mechanism: a single-temperature thermal plasma with solar abundances of elements. This model M has three free parameters – plasma temper- ature, line-of-sight absorption, and normalization – which we denote by the vector θ. The astrophysical model has been convolved with complicated functions represent- ing the sensitivity of the telescope and detector. The model is fitted by minimizing χ2(θ) = P[Fi −Mi(θ)]2/σ2 i with an iterative procedure. Confidence intervals on best-fit parameter values are obtained using a χ2 min-plus-constant criterion. These procedures are familiar in the astronomical community (e.g. Bevington 1969). There are important limitations to χ2 minimization for use in modern astro- nomical model selection and fitting. It fails when the errors are non-Gaussian (e.g. small-N problems with Poissonian errors). It does not provide clear procedures for adjudicating between models with different numbers of parameters (e.g. one- vs. two-temperature models) or between different acceptable models (e.g. local minima in χ2(θ) space). It can be difficult to obtain confidence intervals on parameters
  166. Figure 1: An example of astrophysical model fitting using a spectrum with 264 pho- tons from the Chandra X-ray Observatory. (a) Best-fit thermal model (histogram) to differential binned data (separated points with error bars)obtained by minimum-χ2. Here the absorption parameter has value AV ∼1 mag. Data-minus-residuals appear in the bottom plot. (b) Thermal model (smooth curve) obtained by minimizing the K-S statistic to the integral EDF (step function). The resulting parameters very similar to the χ2 fit. G. Jogesh Babu
  167. Figure 1: Continued. (c) An example of the correct model family but incorrect parameter value: thermal model with absorption set at AV = 10 mag. (d) An example of an incorrect model family: best-fit powerlaw model with absorption AV ∼1 mag. G. Jogesh Babu
  168. with other parameters, whether the statistical treatment involves binned histograms or EDFs, and whether 67% (1σ equivalent), 90% or 99.7% (3σ equivalent) values should be reported. The statistician must decide which statistic to use, whether normal approximations are valid, and how extraneous model parameters should be treated. Finally, Figure 1d treats a broader scientific question: Are the data consistent with different families of astrophysical models, irrespective of the best-fit parameter values within a family? We illustrate this here by obtaining the best-fit model using a nonthermal power law X-ray spectrum rather than a thermal plasma X-ray spectrum. Among statisticians, these are called ‘non-nested’ models. Even decisions between nested models can be tricky; for example, should the dataset in Figure 1 be modeled with thermal models with arbitrary elemental abundances, or is the assumption of solar abundances adequate? 3 Inference for Statistics Based on the EDF Figure 2a shows a hypothetical EDF, the cumulative frequency distribution function of the data. The three commonly used statistics, for inference on F, based on EDF mentioned above are: Kolmogorov-Smirnov (K-S): sup x |Fn(x) −F(x)| Cram´er-von Mises (C-vM): Z (Fn(x) −F(x))2 dF(x), and Anderson - Darling (A-D): Z (Fn(x) −F(x))2 F(x)(1 −F(x)) dF(x). Here Fn is the EDF, F is the model distribution function, and “sup” means the supremum. The K-S statistic is most sensitive to large-scale differences in location (i.e.
  169. The power of these statistics is that they are distribution-free as long as F is continuous. That is, the probability distribution of these statistics is free from F. Consequently, the confidence bands for the ‘unknown’ distribution F can be obtained from standard tables of K-S, C-vM or A-D probabilities which depend only on the number of data points and the chosen significance level. A typical confidence band based on Kolmogorov-Smirnov test resembles Figure 2b. But all these statistics are no longer distribution-free under two important and common situations: when the data are multivariate, or when the model parameters are estimated using the data. We address these situations here. 3.1 Failure of the multivariate case Let (X1, Y1) be a data point from a bivariate distribution F on the unit square. Simpson (1951) shows that if F1 denotes the EDF of (X1, Y1), then P ¡ |F1(x, y) −F(x, y)| < .72, for all x, y ¢ ( > 0.065 if F(x, y) = xy2 < 0.058 if F(x, y) = xy(x + y)/2. Thus, the distribution of the K-S statistic varies with the unknown F and hence is not distribution-free when two or more dimensions are present. The K-S statistic still is a measure of “distance” between the data and model, but probabilities can not be assigned to a given value of the statistic without detailed calculation for each case under consideration. Several methodological studies in the astronomical literature discuss two-dimensional K-S tests. The results may be unreliable to degrees that can not readily
  170. We now outline the mathematics underlying bootstrap calculations. Let {F(.; θ) : θ ∈Θ} be a family of continuous distributions parametrized by θ. We want to test whether the univariate dataset X1, . . . , Xn comes from F = F(.; θ) for some θ = θ0. The K-S, C-vM and A-D statistics (and a few other goodness-of-fit tests) are con- tinuous functionals of the process, Yn(x; ˆθn) = √n ¡ Fn(x) −F(x; ˆθn) ¢ . Here Fn denotes the EDF of X1, . . . , Xn, ˆθn = θn(X1, . . . , Xn) is an estimator of θ derived from the dataset, and F(x; ˆθn) is the model being tested. For a simple example, if {F(.; θ) : θ ∈Θ} denotes the Gaussian family with θ = (µ, σ2), then ˆθn can be taken as ( ¯Xn, s2 n) where ¯Xn is the sample mean and s2 n is the sample variance based on the data X1, . . . , Xn. In the astrophysical example considered in §2, F is the family of thermal models with three parameters. In the case of evaluating goodness-of-fit for a model where the parameters have been estimated from the data, the bootstrap can be computed in two different ways: the parametric bootstrap and the nonparametric bootstrap. The parametric bootstrap may be familiar to the astronomer as a well-established technique of creating fake datasets realizing the parametric model by Monte Carlo methods (e.g. Press et al. 1997). The actual values in the dataset under consideration are not used. The nonparametric bootstrap, in contrast, is a particular Monte Carlo realizations of the observed EDF using a “random selection wit
  171. is operationally easy to perform but requires an additional step of bias correction Bn(x) = √n(Fn(x) −F(x; ˆθn)). The sample process Yn and the bias corrected nonparametric process Y N n converge to the same Gaussian process Y . That is, Ln = √n supx |Fn(x) −F(x; ˆθn)| and J∗ n = supx |√n ¡ F ∗ n(x) −F(x; ˆθ∗ n) ¢ −Bn(x)| have the same limiting distribution. The critical values of the distribution of Ln can then be derived as in the case of parametric bootstrap. For detailed understanding of the regularity conditions under which these results hold see Babu and Rao (2004). 5 Confidence Limits Under Misspecification of Model Family We now address the more advanced problem of comparing best-fit models derived for non-nested model families; e.g. the powerlaw vs. thermal model fits in Figure 1. Essentially, we are asking ‘How far away’ is the unknown distribution underlying the observed dataset from the hypothesized family of models? Let the original dataset X1, . . . , Xn come from an unknown distribution H. H may or may not belong to the family {F(.; θ) : θ ∈Θ}. Let F(., θ0) be the specific model in the family that is ‘closest’ to H where proximity is based on the Kullback- Leibler information, R log ¡ h(x)/f(x; θ) ¢ dH(x) ≥0, which arises naturally due to maximum likelihood arguments and has advantageous properties. Here h and f are the densities (i.e. derivatives) of H and F. If the maximum likelihood estimator ˆθn →θ0, then Un(x; ˆθn) = √n ¡ Fn(x) − F(x; ˆθn) ¢ −√n ¡ H(x) −F(x; θ0
  172. [3] Babu, G. J., and Rao, C. R. (2003). Confidence limits to the distance of the true distribution from a misspecified family by bootstrap. J. Statistical Planning and Inference, 115, no. 2, 471-478. [4] Babu, G. J., and Rao, C. R. (2004). Goodness-of-fit tests when parameters are estimated. Sankhy¯a, 66, no. 1, 63-74. [5] Bevington, P. R. (1969). Data reduction and error analysis for the physical sciences. McGraw-Hill. [6] Getman, K. V., and 23 others (2005). Chandra Orion Ultradeep Project: Ob- servations and source lists. Astrophys. J. Suppl., 160, 319-352. [7] Lilliefors, H. W. (1969). On the Kolmogorov-Smirnov Test for the Exponential Distribution with Mean Unknown. Journal of the American Statistical Associ- ation, 64, No. 325, 387-389 [8] Press, W. H. et al. (1997). Numerical recipes in C: The art of scientific com- puting. Cambridge Univ. Press. [9] Simpson, P. B. (1951). Note on the estimation of a bivariate distribution func- tion. Ann. Math. Stat., 22, 476–478. G. Jogesh Babu
  173. Linear Algebra Solution to Straight line fit As an example of a more realistic data-driven analysis, let’s consider a simple three-parameter linear model which fits a straight-line to data with unknown errors. The parameters will be the the y-intercept a, the slope b, and the (unknown) normal scatter s about the line. For data D = {xi,yi}, the model is ˆy(xi|a,b) = a +bxi, and the likelihood is the product of the Gaussian distribution for each point: L (D|a,b,s) = (2ps2)−N/2 N ’ i=1 exp −[yi −ˆy(xi|a,b)]2 2s2 " . arXiv:1411.5018 Jake Van Der Plas Frequentism and Bayesianism : A Python Driven Primer
  174. algebra. If we define the parameter vector, q = [a b]T; the response vector, Y = [y1 y2 y3 ··· yN]T; and the design matrix, X =  1 1 1 ··· 1 x1 x2 x3 ··· xN "T , it can be shown that the maximum likelihood solution is ˆq = (XTX)−1(XTY). The confidence interval around this value is an ellipse in parameter space defined by the following matrix: S ˆq ⌘ s2 a sab sab s2 b " = s2(MTM)−1. Here s is our unknown error term; it can be estimated based on the variance of the residuals about the fit. The off-diagonal elements of S ˆq are the correlated uncertainty between the estimates. In code, the computation looks like this:
  175. import numpy as np import matplotlib.pyplot as plt from scipy import stats from scipy import ndimage np.random.seed(42) theta_true = (25, 0.5) xdata = 100 * np.random.random(20) ydata = theta_true[0] + theta_true[1] * xdata ydata = np.random.normal(ydata, 10) # Compute the frequentist version X = np.vstack([np.ones_like(xdata), xdata]).T theta_freq = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, ydata)) y_model = np.dot(X, theta_freq) sigma_y = np.std(ydata - y_model) Sigma_freq = sigma_y ** 2 * np.linalg.inv(np.dot(X.T, X)) Code by Jake Van der Plas Full source code available at https://tinyurl.com/y9hhded4
  176. def get_principal(Sigma): # See Ivezic, Connolly, VanderPlas, and Gray, section 3.5.2 sigma_x2 = Sigma[0, 0] sigma_y2 = Sigma[1, 1] sigma_xy = Sigma[0, 1] alpha = 0.5 * np.arctan2(2 * sigma_xy, sigma_x2 - sigma_y2) tmp1 = 0.5 * (sigma_x2 + sigma_y2) tmp2 = np.sqrt(0.25 * (sigma_x2 - sigma_y2) ** 2 + sigma_xy ** 2) return np.sqrt(tmp1 + tmp2), np.sqrt(tmp1 - tmp2), alpha
  177. print("Frequentist Version") print(" theta = {0}".format(theta_freq)) print(" sigma_y = {0}".format(sigma_y)) print(" Sigma = {0}".format(Sigma_freq)) from matplotlib.patches import Ellipse fig, ax = plt.subplots(figsize=(6, 6)) sigma1, sigma2, alpha = get_principal(Sigma_freq) for nsigma in [1, 2]: ax.add_patch(Ellipse(theta_freq, 2 * nsigma * sigma1, 2 * nsigma * sigma2, angle=np.degrees(alpha), lw=2, ec='k', fc='none')) ax.plot([0, 0], [0, 0], '-k', lw=2) ax.set_xlim(10, 40) ax.set_ylim(0.2, 0.7) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\beta$') plt.show()
  178. (image slide)
  179. Model Comparison Week 4+5
  180. Introduction to Model Comparison Qt : Given a dataset: 1) how do we decide which among (two or more) models fit the data best 2) How do we quantify the significance of goodness of fit of the best model compared to disfavored model? Multiple methods to address the above questions : o Frequentist model comparison tests (based on difference in chi-square or log-likelihood ratio) o Bayesian methods (to be discussed later) o Information criterion based methods
  181. Frequentist Model Comparison http://jakevdp.github.io/blog/2015/08/07/frequentism-and-bayesianism-5-model-selection/ arXiv:1607.03549 by Louis Lyons (Sect 13) Astro-ph/0701113 arXiv:1901.07726 Kerscher & Weller arXiv:1607.03845 (SD) A simple application to test if measurements of Newton’s Constant show sinusoidal dependence with time as proposed by some authors. arXiv: 1706.01202 (ShaliniGanguly + SD) Statistical Significance of spectral lag transition in GRB160625B arXiv:1906.05726 Aditi Krishak, Aisha Dantuluri, SD model comparison of annual modulation in DM experiments arXiv:2003.10127 Aditi Krishak, SD model comparison for modified gravity in Eot-wash
  182. • Calculate best fit 𝝌2 for each model • Calculate 𝝌2 for each model and the one with larger value of 𝝌2 GOF (or 𝝌2 pdf) is the preferred value. • Use the fact that if the two models are nested Δ𝝌2 between the two models has a 𝝌2 distribution with DOF = difference in number of free parameters between model 2 and model 1. • Consider the model with fewer free parameters as the null hypothesis calculate the p-value that simply by chance we would see the more complicated model. • p-value = 1-chi-square CDF for DOF=difference in no of free parameters and 𝝌2 = Δ𝝌2 (between the two models) In Python use p-value = 1-stats.chi2(n).cdf(Dc2) Frequentist Model Comparison Summary
  183. Significance from p-value Often define significance Z as the number of standard deviations that a Gaussian variable would fluctuate in one direction to give the same p-value. TMath::Prob TMath::NormQuantile Glenn Cowan lecture Notes Significance also known as Z-score In Python : Use stats.norm.isf(p-value)
  184. Model Comparison Tests of G variation arXiv:1607.03845
  185. Model Comparison Tests of G variation yi = A sin[φ0 + 2⇡(ti/P)] + µG, H1. Data is consistent with a constant offset + measured uncertainties H2. Same as H1, but an additional unknown systematic offset. H3. Data is described by above equation (showing sinusoidal variation) H4. Same as H3, but an additional unknown systematic offset. Hypothesis µ σsys A P(yrs) φ0 DOF χ2/DOF P(χ2,⌫) H1 6.766 ⇥10−11 - - - - 11 28.04 6.8 ⇥10−60 H2 6.674 ⇥10−11 10−14 - - - 10 1.27 0.059 H3 6.674 ⇥10−11 - 1.64 ⇥10−14 5.9 −0.07 8 2.93 0.0011 H4 6.571 ⇥10−11 10−12 1.9 ⇥10−14 7.57 0.0011 7 1.71 0.032
  186. Shalini Ganguly , SD (arXiv:1706.01202)
  187. Information Criterion based tests Akaike Information Criterion : based on Kullbeck-Leibler information entropy Bayesian Information Criterion : based on Bayesian evidence arXiv:1207.5875 Shi, Huang and Lu astro-ph/0701113 Liddle BIC ≡−2 ln Lmax + k ln N , AIC ≡−2 ln Lmax + 2k , AICc = AIC + 2k(k + 1) N −k −1 . N = no of data points K = no of free parameters
  188. Strength of Evidence Tests for AIC/BIC For the AIC, Burnham & Anderson (2003) featured the following “strength of evidence” in the form of ∆AIC = AICi −AICmin: ∆AIC Level of Empirical Support For Model i 0 −2 Substantial 4 −7 Considerably Less > 10 Essentially None For the BIC, Robert & Adrian (1995) featured the fol- lowing “strength of evidence”, where ∆BIC = BICi − BICmin: ∆BIC Evidence against Model i 0 −2 Not Worth More Than A Bare Mention 2 −6 Positive 6 −10 Strong > 10 Very Strong arXiv:1207. 5875 by Shi et al
  189. Other Advanced Model-Comparison Tests • Deviance Information Criterion • Takeuchi Information Criterion • WAIC • F-test • Likelihood ratio tests • Cross-validation • Bayesian Methods : Bayes Factor, Posterior Odds Ratio For more advanced details see the following note by Louis Lyons https://www-cdf.fnal.gov/physics/statistics/notes/H0H1.pdf For more examples of model comparison in Cosmology/Astrophysics, see Liddle : astro-ph/0701113 Liddle, Mukherjee, Parkinson : astro-ph/0608184 Kerscher and Weller arXiv:1901.07726
  190. Comparison of Distributions Week 4
  191. Some quotes from astrophysicists o “Understanding data better is always an unsolved problem in Astrophysics” Bill Press, astro-ph/9604126 o “We identify the probability of the data given the parameters as the likelihood of the parameters given the data. This identification is entirely based on intuition. It has no formal mathematical basis in and of itself; as we already remarked, statistics is not a branch of mathematics.” Bill Press, Numerical Recipes 1992 edition, Chapter 15 on maximum likelihood estimation. o You may ask “What can a hard headed statistician offer to a starry eyed astronomer?”. The answer is “Plenty”. One normally associates statistics with large numbers, and astronomy is full of large numbers…I have every reason to believe that increased interaction between statistics and astronomy will be to the benefit of both subjects. Jayant Narlikar to C.R. Rao
  192. Introduction • Two samples are drawn from the same distribution or whether two sets of measurements imply a difference in measured quantity. • A sample is consistent as been drawn from a known distribution. • Two sets of measurements with different measurement errors are drawn have the same mean. Use data to compute an approximate statistic and compare the data-based value to its expected distribution. The expected distribution is evaluated by assuming that the null hypothesis is true. We now discuss various non-parametric methods for comparing distributions.
  193. • K-S test compares cumulative distribution function of two samples. • Consider two samples {x1i} where i=1,….N1 and {x2i} where i=1,….N2 Sort the sample and divide the rank of xi by the sample size to get F(xi) F(x) is a step function that increases by 1/N at each data point 0 ≤ F(x) ≤ 1. K-S test is based on the maximum distance of the cumulative distribution function F1(x1) and F2(x2). D = max | F1(x1) - F2(x2) | Kolmogorov-Smirnov (K-S) tests Source: wikipedia
  194. −2 0 2 4 0.0 0.2 0.4 0.6 0.8 1.0 x Fn(x) Jessica Cisewski notes at 2016 PSU astrostatistics summer school Example of 2-sample KS test
  195. Null Hypothesis of KS-test Qt : How often would the value D computed from the data arise by chance if the two samples were drawn from the same distribution (null hypothesis in this case). The probability of obtaining by chance a value D larger than the observed value is given by the function D
  196. • Qt : Is the measured f(x) consistent with a known reference distribution function h(x) This is called “one-sample” K-S test and is special case of “two-sample” K-S test discussed previously. In this case N2=∞ A small value of Qks indicates that it is unlikely at given confidence level α that the data summarized by f(x) are drawn from h(x). K-S test is sensitive to the location, scale and shape of the underlying distribution. It is insensitive to reparametrization of the data points. K-S tests for histograms can be found in arXiv:0804.0380 One-Sample K-S test
  197. • Lookup kstest, ks_2samp, ksone in scipy.stats import numpy as np from scipy import stats vals = np.random.normal(loc=0,scale=1,size=1000) stats.kstest(vals,”norm”) 0.025, 0.529 D-value = 0.025 p-value = 0.529 K-S test in Python
  198. • See https://asaip.psu.edu/Articles/beware-the-kolmogorov-smirnov-test Other non-parametric tests: Anderson-Darling test Cramer-Von Mises Test Watson Test Gini Coefficient (based on cumulative distribution function) : measures the deviation of a given cumulative distribution function from that expected for a normal distribution. Critic of usage of K-S test in astrophysics
  199. Examples of KS test usage in astrophysics • Too many examples (homework assignment for you all)
  200. • Simple variant of K-S test to treat distributions defined on a circle. It is based on the statistic D* = max{F1(x1) – F2(x2)} + max{F2(x1) – F1(x2)} For distributions on a circle D* is invariant to location of origin. Good test for comparing longitude distribution of two astronomical samples. Null hypothesis probability calculated in the same way as K-S test. Kuiper test
  201. Example of Kuiper Test usage 0 20 40 60 80 100 0 π/2 π 3π/2 2π e-like φ number of events 0 20 40 60 80 100 0 π/2 π 3π/2 2π µ-like φ number of events East-West asymmetry of atmospheric neutrino flux in Super-Kamiokande astro-ph/9901139
  202. A quantitative comparison between the data and Monte Carlo was performed using a Kuiper test [8,9]. This test calculates a binning and starting-point free probability that observed data are the result of an assumed distribution. The Kuiper statistic V is defined as: V = max 0<φ<2π[SN(φ) −P(φ)] + max 0<φ<2π[P(φ) −SN(φ)], where φ is the azimuthal angle, SN(φ) is a cumulative probability function from data and P(φ) is the one from Monte Carlo. The significance is obtained from the statistic V ∗= V (√n + 0.155 + 0.24/√n), and defined as Prob = 2 ∞ ! j=1 (4j2V ∗2 −1) exp(−2j2V ∗2), where n is number of events. From this test, the probability that the azimuthal distribution of the data originated from a flat parent distribution was 0.0008% (20%) for e-like (µ-like) events. The azimuthal distribution of e-like events is inconsistent with a flat distribution at more than 99% CL. Also, the probabilities that the data match the Monte Carlo in shape with the flux of Ref. [3] were 42% for e-like events and 92% for µ-like events. For a Monte Carlo with neutrino 2 2 3 2
  203. Anderson-Darling Test for Gaussianity. Qt: Is the shape of measured f(x) consistent with a Gaussian distribution? Aim is to predict distribution of test statistic when null hypothesis is true. Where Fi is the ith value of the cumulative distribution function of zi defined as :
  204. Anderson-Darling test in SciPy This is also coded in statsmodels Lookup statsmodels.stats.diagnostic.normal_ad
  205. From scipy import stats X = np.random.normal(0,1,size=1000) A,crit,sig = stats.anderson(X,’norm’) Anderson-Darling Test for Gaussianity A-D test in scipy.stats can also be used to test for exponential, logistic, Gumbel distribution Note that there is also a k-sample -sample A-D test called anderson_ksamp in scipy
  206. Shapiro-Wilk test. Lookup stats.shapiro in scipy . A value of W close to 1 indicates that distribution is entirely gaussian Ri is the rank of the sample and ai is the expected values of the order statistics for random variables sampled from the normal distribution
  207. Outliers in Gaussian Distributions • Compare sample standard deviation and σG • For a Gaussian distribution when N > 100, s/σG follows a Gaussian distribution with μ~1 and 𝞂= 0.92/√𝑁 • Difference between mean and median drawn from a Gaussian distribution follows a Gaussian distribution with μ~0 and σ~0.76/ 𝑁 $ Define Z1 = 1.3 |μ –q50 | 𝑁 $ /s and obey Gaussian distribution with mean = Z1 and std. deviation = Z2
  208. • For data which depart from Gaussian distributions : A-D test (A2) >1 K-S test (D) > 1/sqrt(N) Shapiro-Wilk’s test (W) < 1 Z1, Z2 > (many times) 𝞂 • For an example from astrophysics (dynamical state of galaxy groups) see arXiv:0908.0938 Cheat-Sheet of Tests for Gaussianity
  209. Normal Distribution Combination of two normal distributions Astroml figure 4.7
  210. • In case our empirical distributions fail tests for Gaussianity, but if there is no strong motivation for choosing a specific alternative distribution. • Model Non-Gaussian distribution by Gram-Charlier series Modeling Non-Gaussianity where Hk(z) are Hermite polynomials, which form an orthonormal set and RC Boston 1971, IEEE
  211. Mann-Whitney Test/U Test/Wilcoxon rank sum tests o Used to check if two datasets are drawn from distributions with different location parameters (or different means). (In case the two datasets are drawn from Gaussian distributions, you can use t-test). o Calculation of U is obtained from the ranks of the two samples after concatenating them (will skip details of calculation. consult wikipedia) >>> import numpy as np >>> from scipy import stats >>> x,y=np.random.normal(0,1,size=(2,1000)) >>> stats.mannwhitneyu(x,y) (See also stats.ranksums) MannwhitneyuResult(statistic=488708.0, p-value=0.19094553275490711) U-test expected result is close to the expected N1N2/2 if they are drawn from the same distribution with Same mean. See https://data.library.virginia.edu/the-wilcoxon-rank-sum-test/ for an illustrative example
  212. Wilcoxon signed-rank test Special case of comparing the means of two data sets is when the data sets have the same size (N1 = N2 = N) and data points are paired. Non-parametric test used to compare means of two distributions is the Wilcoxon signed-rank test. This test cannot be used when data points are not equal o Calculate yi = x1i –x2i and exclude all values with yi=0 o Order the new sample by |yi| resulting in the rank Ri for each pair o Each pair is assigned Φi=1 if x1i> x2i and 0 otherwise. o Calculate W+ as follows All ranks with yi> 0 are summed Similarly calculate W- and Wilcoxian signed rank test (T) is smaller of the two.
  213. p-value of Wilcoxon signed-rank test For value of n > 20 , behaviour of T can be approximated by Gaussian distribution where :
  214. Wilcoxon signed-rank test in scipy >>> import numpy as np >>> from scipy import stats >>> x,y = np.random.normal(0,1,size=(2,1000)) >>> T,p= stats.wilcoxon(x,y) >>> T,p # T is the value of smaller value of W+ and W- (243583.0, 0.46552103910817078)
  215. 19 12 I was wondering what the theoretical difference is between the Wilcoxon Rank-Sum Test and the Wilcoxon Signed- Rank Test using paired observations. I know that the Wilcoxon Rank-Sum Test allows for different amount of observations in two different samples, whereas the Signed-Rank test for paired samples does not allow that, however they both seem to test the same in my opinion. Can someone give me some more background / theoretical information when one should use the Wilcoxon Rank-Sum Test and when one should use the Wilcoxon Signed-Rank Test using paired observations? More details available in http://tinyurl.com/j37sts5 Difference between Wilcoxon signed-rank test and Wilcoxon rank-sum test
  216. • If two datasets are drawn from Gaussian distributions with different means, but same sigma and sigma is known , you can calculate p-value of the difference in means using error propagation. • If we do not know sigma, calculate and where follows Student’s t-distribution. DOF = N1+N2-2 For large samples, this asymptotes to the case of distributions with known sigma (or Gaussian distribution) If the two datasets are drawn from two underlying distributions with different variances, then appropriate test is called Welch’s t-test. Parametric Methods for comparing distributions (t-test)
  217. • Different variants of t-test in Python called ttest_rel, ttest_ind, and ttest_1samp See documentation for details. >>> import numpy as np >>> from scipy import stats >>> x, y = np.random.normal(size=(2,1000)) >>> t,p = stats.ttest_ind(x,y) >>> t,p (0.93039549523650522, 0.35227874770046763) t-test in Python
  218. Comparison of Gaussian variances using F- test • F test is used to compare variances of two unspecified distributions. The null hypothesis is that variances of the two samples are equal and the statistics is based on the ratio of the sample variances F = s12/s22 follows Fisher F distribution with d1 = N1-1 and d2=N2-1 >>> import numpy as np >>> from scipy import stats >>> x, y = np.random.normal(size=(2,10000)) >>> F,p = stats.f_oneway(x,y) • p • 0.85157563615482457 • F • 0.035010462229159989
  219. Efficacy of these tests In astrophysics a comparative study of these tests for detecting non-gaussianity was done in https://arxiv.org/abs/0908.0938
  220. Choosing histogram bin width • Three different rules for choosing bin width: ØScott Rule Ø Freedman rule Ø Knuth Rule from astroML.plotting import hist hist(x,bins=‘freedman’) # can also choose knuth or scott
  221. Gaussian Mixture Model
  222. Introduction • For a recent review , see M. Kuhn and E. Feigelsen arXiv:1711.11101 Likelihood of a datum xi for a Gaussian mixture model is given by: Log likelihood given by : p(xi|✓) = M X j=1 ↵jN(µjσj) M X j=1 ↵j = 1 ln L = N X i=1 ln " M X i=1 ↵jN(µj, σj) #
  223. GMM (Contd) • Maximization of can be trivially done using Expectation-Maximization Algorithm (Dempster, Laird, Rubin 1977) • The optimum number of components can be computed using model comparison techniques. • Generalization of GMM to account for errors is known as `` Extreme Deconvolution’’ in astrophysics literature (arXiv:0905.2979). For an application of this see arXiv:2206.02751 • GMM can be generalized to other mixture models, but you cannot use E-M algorithm for maximization (also other variants , eg. Dirichlet mixture models) Routines available in R to do mixture models of t-distributions etc (see arXiv:1910.08968) lnL
  224. GMM in Python >>> import numpy as np >>> from sklearn.mixture import GaussianMixture (GMM deprecated after v0.17) >>> X=np.random.normal(size=(100,1)) >>> model=GaussianMixture(2) >>> model.fit(X) GaussianMixture(covariance_type='diag', init_params='wmc', min_covar=0.001, n_components=2, n_init=1, n_iter=100, params='wmc', random_state=None, thresh=None, tol=0.001, verbose=0) >>> model.means_ array([[-0.44802848],[ 0.53396065]]) More detailed documentation in sklearn
  225. Example from AstroML (Fig. 4.2)
  226. Example from Astro Literature Soham Kulkarni & SD (arXiv:1612.08235)
  227. Bayesian Analysis Weeks 5+6
  228. Introduction to Bayesian Analysis • This is a huge subject with potential for year-long course. Tom Loredo arxiv:1208.3036
  229. (image slide)
  230. Bayesian Literature in Astronomy Sanjib Sharma seminar @ IITH Jan 2020
  231. Books on Bayesian Analysis (Physicist Pov) • Data Analysis – A Bayesian tutorial by D.S. Sivia and John Skilling • Bayesian Logical Data Analysis for Physical Sciences • Online book by E.T. Jaynes (Probability Theory, Logic of Science) • Bayesian Methods in Cosmology by Michael Hobson et al
  232. Arxiv resources on Bayesian Analysis • https://arxiv.org/abs/0803.4089Roberto Trotta • https://arxiv.org/abs/1701.01467 Trotta (Bayesian methods in Cosmology) • https://arxiv.org/abs/1301.1273 Louis Lyons (particle physics) • https://arxiv.org/abs/1302.1721Andrew Liddle • https://arxiv.org/abs/0911.3105 Licia Verde (Statistical Methodsin Cosmology) • https://arxiv.org/abs/1208.3036Tom Loredo (Bayesian Astrostatistics) • https://arxiv.org/abs/1012.3589Glenn Cowan(particle physics) • https://arxiv.org/abs/1411.5018 J Vanderplas(PracticalIntroduction) (Easy to read ) • https://arxiv.org/abs/1809.02293Eric Thrane & Colm Talbot(forGW astronomy) • https://arxiv.org/abs/2302.04703Practicalguide for Bayesian Inference in Astronomy Also lectures on Bayesian statistics in PSU summer school Jake Van der Plas blog article
  233. • First introduced by Rev. Thomas Bayes (1702-1761) who wrote an article on how to combine an initial belief with new data to arrive at an improved belief • Probability statements can be made for model parameters and models themselves. • Both Classical (and frequentist) statistics use data likelihood. In frequentist statistics, likelihood function is used to find model parameters with the highest data likelihood. But likelihood function cannot be interpreted as PDF for the model parameters. • Bayesian statistics extends the concept of data likelihood function by adding extra (or prior) information to the analysis and assigning pdfs to all model parameters and the models themselves. Introduction to Bayesian Statistics
  234. Imagine you arrive at a bus stop (with no knowledge of the bus schedule) and the next bus arrives t minutes later. Q: What is the mean time 𝞽between two successive buses , if the buses keep a regular schedule? Ans: Wait time is distributed uniformly in the interval 0 ≤ t ≤ 𝞽and average wait time= 𝞽/2, or 𝞽= 2t Limitations of Max. Likelihood Estimates
  235. Max Likelihood Estimates Probability that you shall wait t minutes (likelihood of the data) is given by the uniform distribution Because there is only a single data point, the data likelihood is simple equal to this probability. Maximum of p(t|𝞽) occurs for 𝞽= t (or when 𝞽is smallest) Expectation value of 𝞽or its median value diverges Problem is solved when we introduce priors.
  236. Essence of Bayesian idea Bayes theorem quantifies the rule for combining initial belief with new data to arrive at improved belief and “improved belief” is the product of “initial belief” and the probability that “initial belief” generated the observed data.
  237. where model M includes k model parameters 𝛳p . (note that M and 𝛳are used interchangeably) o P(M, 𝛳|D,I) is the posterior pdf for model M and some prior information I . o P(D| M, 𝛳) is the likelihood of the data given some model M and some fixed value of parameters 𝛳 o P(M, 𝛳|I) is the a priori joint probability for model M and its parameters 𝛳in the absence of any of the data used to compute the likelihood and is often simply called the prior Prior can be expanded as follows Usually for parameter estimation problems, we only need to specify P(𝛳|M,I)
  238. o P(D/I ) is probability of the data or the prior predictive probability for D. Provides normalization for the posterior pdf and is not explicitly computed when estimating model parameters. Instead P(M, 𝛳|D,I) for a given model is renormalized so that its integral over all model parameters is unity. Integral of the prior P(𝛳|M,I) over all parameters should also be equal to unity. For parameter estimation, calculation of posterior pdf done with an arbitrary normalization One exception is model comparison where correct normalization of numerator in Bayes’s formulae is important.
  239. Why is Bayesian Interpretation Controversial • P(M, 𝛳|D,I) is not a probability in the strict sense (compared to the likelihood in frequentist statistics) . We accept that P(M, 𝛳|D,I) corresponds to the state of our knowledge (or degree of belief) about a model and its parameters given data D and prior information I . This introduces the notion of probability for models and model parameters.
  240. Bus-Stop Example • Assume prior is proportion to 1/ 𝞽. Posterior probability density function is given by : Note that the extra t is added so that integral of posterior is unity. C = t
  241. Median value of 𝞽for is given by 2t (in agreement with expectation) Also p% quantiles are equal to (1- t/ 𝞽p ) For more on the bus-stop example see http://jakevdp.github.io/blog/2018/09/13/waiting-time- paradox/
  242. Notation : Replace M(𝛳) with M whenever the absence of explicit dependence on 𝛳is not confusing. o Construction of the Data likelihood P (D | M) o Choice of the prior incorporating previous information that might exist, but is not used in computing the likelihood. P(𝛳|M,I) o Determination of posterior pdf using Bayes theorem. P (M | D) This step is computationally intensive for multi-dimensional posterior problems. Also P(D | I) is not explicitly stated because P(M | D) can be properly normalized by renormalizing the product P(D | M) P(M) o Best model parameters are found by maximizing P (M | D) which yield maximum aposteriori estimate. This point estimate is the natural analog to maximum likelihood estimation (MLE) from classical statistics. Summary of Bayesian Statistical Inference
  243. o Uncertainty in parameter estimates is obtained via credible regions (Bayesian counterpart to frequentist confidence region). Obtained by integrating the posterior. Various numerical methods can be used to simulate samples from the posterior. o Hypothesis testing as needed to make conclusions about model or parameter estimates. Bayesian approach can be thought of as formalizing the process of continually refining our state of the knowledge about the world, beginning with no data and then updating that by multiplying by the likelihood once the data is observed to obtain the posterior.
  244. Alternately calculate the Bayesian posterior means as follows : For a vector of parameters 𝛳(i.e. one particular value) is obtained from by the process of marginalization , i.e. by integrating over all the other unknown parameters and then renormalization Although there is no natural way to marginalize over nuisance parameters in frequentist statistic, However , profile likelihood is used (particle physics literature) Posterior estimates and Marginalization
  245. Consider posterior pdf P (M ,𝛳1, 𝛳2,…... 𝛳k) . Suppose we are only interested in 𝛳1 . In order to obtain the posterior pdf for 𝛳1 we integrate over all the uninteresting (or nuisance) parameters. This integration procedure is called the process of marginalization and the resulting pdf is called marginal posterior pdf Marginalization of Parameters
  246. Convergence of Posterior with More data
  247. Bayesian Priors • Prior incorporates all other knowledge that might exist, but is used when computing the likelihood. Data may chronologically proceed the information in the prior Examples of priors include knowledge from prior measurements of the same type as data at hand or different measurements that constrain the same quantity whose posterior pdf we are trying to constrain with new data. We may know the mass of an elementary particle from previous measurements with uncertainty.. Priors that incorporate information based on other measurements are called informative priors
  248. Priors Assigned by Formal Rules • When no information is available except for the data been analyzed then such priors are called non-informative priors. Consider a flat prior p(𝛳) ∝constant since -> this is not a pdf This is considered an improper prior. Not a problem as long as the resulting posterior is a well-defined pdf. Principle of indifference : A set of mutually exclusive possibilities need to be assigned equal probabilities. For a fair die prior = 1/6 Principle of consistency: Prior for a location parameter should not change with translation of coordinate system and yields a flat prior. Prior for scale parameter should not depend on choice of units eg if scale parameter is 𝞂 and rescaling by a constant factor gives Solution to this is (Jeffreys prior) P(σ|I) / σ−1
  249. Principle of Maximum Entropy • Entropy measures the information content of a pdf. Entropy for a pdf defined by N discrete values is given by : This is also called Shannon’s entropy. This can be generalized to a continuous distribution (Sivia 2006) where the ``Lebesgue measure’’ m(x) ensures that entropy is invariant under change of variables. (Sivia 06)
  250. • By maximizing entropy over a suitable set of pdfs, we find the distribution that is least informative (given the constraints) • Power of the principle comes from a straightforward ability to add additional information about the prior distribution, such as the mean value and the variance. Principle of Maximum Entropy (contd)
  251. Example : Consider a 6-faced die where we need to assign 6 prior probabilities. From principle of indifference prior probability is 1/6. But suppose we know the mean value (for a large number of rolls) then we need to adjust the prior probabilities to be consistent with this information. Maximize
  252. • where mi is the values of pi when no additional information is known (in this case 1/6). Solution is given by l0 and l1 can be obtained from the constraint equations. Generalizes to Poisson distribution if no of discrete events is infinite with mean μ For the continuous case maximum entropy solution for the prior is given by : obtained by assuming a flat distribution on m(𝛳) (when no constraint on mean value) and assuming we know the expectation value of
  253. Kullback-Leibler Divergence and analogously for continuous case KL divergence is sometimes called KL distance between the two pdfs. But it is NOT the metric distance since value is not the same when p(x) and m(x) are switched. In Bayesian statistics KL divergence can be used to measure the information gain When moving the prior distribution to posterior distribution. KL divergence also used in information theory.
  254. • If posterior probability has the same functional form as likelihood for a given prior, these priors are called conjugate priors. and represent a convenient way for generalizing computations. Conjugate Priors. Likelihood Conjugate Prior Gaussian Gaussian Binomial Beta distribution Poisson Gamma Distribution Multinomial Dirichlet priors
  255. Bayesian Parameter Uncertainty Quantification To obtain Bayesian credible region estimate, we find a and b such that The probability that the true values of 𝛳is in the interval (a,b) is equal to 1-α In analogy with classical confidence interval and (a,b) is called a 1-α Posterior interval
  256. Difference between Confidence/Credible Regions • Bayesianism : Probabilistic statement about model parameters given a fixed credible region. Given our observed data, there is a 95% probability that the true value of 𝛳 lies within the credible region. • Frequentism : Probabilistic statement about a recipe for generating confidence intervals given a fixed model parameter. If our experiment is repeated many times, in 95% of these cases, the computed confidence interval will contain the true 𝛳
  257. (image slide)
  258. Examples of Marginalized Posteriors arXiv:1405.7435
  259. Bayesian Model Selection • To find out which of two models say M1 and M2 are supported by data we compare their posterior probabilities via the odds ratio in favor of model M2 over model M1 (sometimes also called posterior odds) Where the posterior probability that the model M is correct given data D is given by
  260. where is called the evidence or marginal likelihood or Bayesian evidence. It quantifies the Probability that the data D would be observed if the model M were the correct model Odds Ratio becomes : where Bayes Factor
  261. Interpretation of Odds Ratio • Jeffreys Scale used as a qualitative guide to decide between model 2 and model 1 K = Bayes Factor wikipedia (note that model M1 is in the numerator in wikipedia definition. of Bayes factor)
  262. Open Questions/Limitations of Bayesian Analysis • Criticism of Bayesian Model selection by Efsthathiou (for cosmology) (arXiv:0802.3185) and Bob Cousins (particle physics) (arXiv: 0807.1330) , where not enough care is given to selection of models and priors and posterior model probabilities maybe function of unjustified assumptions. • How to deal with Lindley’s paradox (where Bayesian and frequentist hypothesis testing lead to contradictory answers). (See arXiv:1310.3791) • How to assess the completeness of a set of known models? Is there a principled way of constructing an absolute scale for model performance in a Bayesian context? (see arxiv:1511.02363 for some research on this) • Is Bayesian model averaging (model independent estimation of parameters) useful ? • Is there such a thing as a correct prior? • Many posteriors used in astronomical literature are improprer arXiv:1712.03549 • One should also consider fluctations in Bayesian evidence arXiv:2102.09547