Kolmogorov–Smirnov test

From HandWiki
Short description: Non-parametric statistical test between two distributions
Illustration of the Kolmogorov–Smirnov statistic. The red line is a model CDF, the blue line is an empirical CDF, and the black arrow is the KS statistic.

In statistics, the Kolmogorov–Smirnov test (K-S test or KS test) is a nonparametric test of the equality of continuous (or discontinuous, see Section 2.2), one-dimensional probability distributions that can be used to compare a sample with a reference probability distribution (one-sample K–S test), or to compare two samples (two-sample K–S test). In essence, the test answers the question "What is the probability that this collection of samples could have been drawn from that probability distribution?" or, in the second case, "What is the probability that these two sets of samples were drawn from the same (but unknown) probability distribution?". It is named after Andrey Kolmogorov and Nikolai Smirnov.

The Kolmogorov–Smirnov statistic quantifies a distance between the empirical distribution function of the sample and the cumulative distribution function of the reference distribution, or between the empirical distribution functions of two samples. The null distribution of this statistic is calculated under the null hypothesis that the sample is drawn from the reference distribution (in the one-sample case) or that the samples are drawn from the same distribution (in the two-sample case). In the one-sample case, the distribution considered under the null hypothesis may be continuous (see Section 2), purely discrete or mixed (see Section 2.2). In the two-sample case (see Section 3), the distribution considered under the null hypothesis is a continuous distribution but is otherwise unrestricted. However, the two sample test can also be performed under more general conditions that allow for discontinuity, heterogeneity and dependence across samples.[1]

The two-sample K–S test is one of the most useful and general nonparametric methods for comparing two samples, as it is sensitive to differences in both location and shape of the empirical cumulative distribution functions of the two samples.

The Kolmogorov–Smirnov test can be modified to serve as a goodness of fit test. In the special case of testing for normality of the distribution, samples are standardized and compared with a standard normal distribution. This is equivalent to setting the mean and variance of the reference distribution equal to the sample estimates, and it is known that using these to define the specific reference distribution changes the null distribution of the test statistic (see Test with estimated parameters). Various studies have found that, even in this corrected form, the test is less powerful for testing normality than the Shapiro–Wilk test or Anderson–Darling test.[2] However, these other tests have their own disadvantages. For instance the Shapiro–Wilk test is known not to work well in samples with many identical values.

Kolmogorov–Smirnov statistic

The empirical distribution function Fn for n independent and identically distributed (i.i.d.) ordered observations Xi is defined as

[math]\displaystyle{ F_{n}(x)=\frac{\text {number of (elements in the sample} \leq x)}{n}=\frac{1}{n} \sum_{i=1}^{n} 1_{[-\infty,x]}(X_{i}), }[/math]
where [math]\displaystyle{ 1_{[-\infty,x]}(X_i) }[/math] is the indicator function, equal to 1 if [math]\displaystyle{ X_i \le x }[/math] and equal to 0 otherwise.

The Kolmogorov–Smirnov statistic for a given cumulative distribution function F(x) is

[math]\displaystyle{ D_n= \sup_x |F_n(x)-F(x)| }[/math]

where supx is the supremum of the set of distances. Intuitively, the statistic takes the largest absolute difference between the two distribution functions across all x values.

By the Glivenko–Cantelli theorem, if the sample comes from distribution F(x), then Dn converges to 0 almost surely in the limit when [math]\displaystyle{ n }[/math] goes to infinity. Kolmogorov strengthened this result, by effectively providing the rate of this convergence (see Kolmogorov distribution). Donsker's theorem provides a yet stronger result.

In practice, the statistic requires a relatively large number of data points (in comparison to other goodness of fit criteria such as the Anderson–Darling test statistic) to properly reject the null hypothesis.

Kolmogorov distribution

Illustration of the Kolmogorov distribution's PDF.

The Kolmogorov distribution is the distribution of the random variable

[math]\displaystyle{ K=\sup_{t\in[0,1]}|B(t)| }[/math]

where B(t) is the Brownian bridge. The cumulative distribution function of K is given by[3]

[math]\displaystyle{ \operatorname{Pr}(K\leq x)=1-2\sum_{k=1}^\infty (-1)^{k-1} e^{-2k^2 x^2}=\frac{\sqrt{2\pi}}{x}\sum_{k=1}^\infty e^{-(2k-1)^2\pi^2/(8x^2)}, }[/math]

which can also be expressed by the Jacobi theta function [math]\displaystyle{ \vartheta_{01}(z=0;\tau=2ix^2/\pi) }[/math]. Both the form of the Kolmogorov–Smirnov test statistic and its asymptotic distribution under the null hypothesis were published by Andrey Kolmogorov,[4] while a table of the distribution was published by Nikolai Smirnov.[5] Recurrence relations for the distribution of the test statistic in finite samples are available.[4]

Under null hypothesis that the sample comes from the hypothesized distribution F(x),

[math]\displaystyle{ \sqrt{n}D_n\xrightarrow{n\to\infty}\sup_t |B(F(t))| }[/math]

in distribution, where B(t) is the Brownian bridge. If F is continuous then under the null hypothesis [math]\displaystyle{ \sqrt{n}D_n }[/math] converges to the Kolmogorov distribution, which does not depend on F. This result may also be known as the Kolmogorov theorem.

The accuracy of this limit as an approximation to the exact cdf of [math]\displaystyle{ K }[/math] when [math]\displaystyle{ n }[/math] is finite is not very impressive: even when [math]\displaystyle{ n=1000 }[/math], the corresponding maximum error is about [math]\displaystyle{ 0.9~\% }[/math]; this error increases to [math]\displaystyle{ 2.6~\% }[/math] when [math]\displaystyle{ n=100 }[/math] and to a totally unacceptable [math]\displaystyle{ 7~\% }[/math] when [math]\displaystyle{ n=10 }[/math]. However, a very simple expedient of replacing [math]\displaystyle{ x }[/math] by

[math]\displaystyle{ x+\frac{1}{6\sqrt{n}}+ \frac{x-1}{4n} }[/math]

in the argument of the Jacobi theta function reduces these errors to [math]\displaystyle{ 0.003~\% }[/math], [math]\displaystyle{ 0.027\% }[/math], and [math]\displaystyle{ 0.27~\% }[/math] respectively; such accuracy would be usually considered more than adequate for all practical applications.[6]

The goodness-of-fit test or the Kolmogorov–Smirnov test can be constructed by using the critical values of the Kolmogorov distribution. This test is asymptotically valid when [math]\displaystyle{ n \to\infty. }[/math] It rejects the null hypothesis at level [math]\displaystyle{ \alpha }[/math] if

[math]\displaystyle{ \sqrt{n}D_n\gt K_\alpha,\, }[/math]

where Kα is found from

[math]\displaystyle{ \operatorname{Pr}(K\leq K_\alpha)=1-\alpha.\, }[/math]

The asymptotic power of this test is 1.

Fast and accurate algorithms to compute the cdf [math]\displaystyle{ \operatorname{Pr}(D_n \leq x) }[/math] or its complement for arbitrary [math]\displaystyle{ n }[/math] and [math]\displaystyle{ x }[/math], are available from:

  • [7] and [8] for continuous null distributions with code in C and Java to be found in.[7]
  • [9] for purely discrete, mixed or continuous null distribution implemented in the KSgeneral package [10] of the R project for statistical computing, which for a given sample also computes the KS test statistic and its p-value. Alternative C++ implementation is available from.[9]

Test with estimated parameters

If either the form or the parameters of F(x) are determined from the data Xi the critical values determined in this way are invalid. In such cases, Monte Carlo or other methods may be required, but tables have been prepared for some cases. Details for the required modifications to the test statistic and for the critical values for the normal distribution and the exponential distribution have been published,[11] and later publications also include the Gumbel distribution.[12] The Lilliefors test represents a special case of this for the normal distribution. The logarithm transformation may help to overcome cases where the Kolmogorov test data does not seem to fit the assumption that it came from the normal distribution.

Using estimated parameters, the question arises which estimation method should be used. Usually this would be the maximum likelihood method, but e.g. for the normal distribution MLE has a large bias error on sigma. Using a moment fit or KS minimization instead has a large impact on the critical values, and also some impact on test power. If we need to decide for Student-T data with df = 2 via KS test whether the data could be normal or not, then a ML estimate based on H0 (data is normal, so using the standard deviation for scale) would give much larger KS distance, than a fit with minimum KS. In this case we should reject H0, which is often the case with MLE, because the sample standard deviation might be very large for T-2 data, but with KS minimization we may get still a too low KS to reject H0. In the Student-T case, a modified KS test with KS estimate instead of MLE, makes the KS test indeed slightly worse. However, in other cases, such a modified KS test leads to slightly better test power.

Discrete and mixed null distribution

Under the assumption that [math]\displaystyle{ F(x) }[/math] is non-decreasing and right-continuous, with countable (possibly infinite) number of jumps, the KS test statistic can be expressed as:

[math]\displaystyle{ D_n= \sup_x |F_n(x)-F(x)| = \sup_{0 \leq t \leq 1} |F_n(F^{-1}(t)) - F(F^{-1}(t))|. }[/math]

From the right-continuity of [math]\displaystyle{ F(x) }[/math], it follows that [math]\displaystyle{ F(F^{-1}(t)) \geq t }[/math] and [math]\displaystyle{ F^{-1}(F(x)) \leq x }[/math] and hence, the distribution of [math]\displaystyle{ D_{n} }[/math] depends on the null distribution [math]\displaystyle{ F(x) }[/math], i.e., is no longer distribution-free as in the continuous case. Therefore, a fast and accurate method has been developed to compute the exact and asymptotic distribution of [math]\displaystyle{ D_{n} }[/math] when [math]\displaystyle{ F(x) }[/math] is purely discrete or mixed,[9] implemented in C++ and in the KSgeneral package [10] of the R language. The functions disc_ks_test(), mixed_ks_test() and cont_ks_test() compute also the KS test statistic and p-values for purely discrete, mixed or continuous null distributions and arbitrary sample sizes. The KS test and its p-values for discrete null distributions and small sample sizes are also computed in [13] as part of the dgof package of the R language. Major statistical packages among which SAS PROC NPAR1WAY,[14] Stata ksmirnov [15] implement the KS test under the assumption that [math]\displaystyle{ F(x) }[/math] is continuous, which is more conservative if the null distribution is actually not continuous (see [16] [17] [18]).

Two-sample Kolmogorov–Smirnov test

Illustration of the two-sample Kolmogorov–Smirnov statistic. Red and blue lines each correspond to an empirical distribution function, and the black arrow is the two-sample KS statistic.

The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ. In this case, the Kolmogorov–Smirnov statistic is

[math]\displaystyle{ D_{n,m}=\sup_x |F_{1,n}(x)-F_{2,m}(x)|, }[/math]

where [math]\displaystyle{ F_{1,n} }[/math] and [math]\displaystyle{ F_{2,m} }[/math] are the empirical distribution functions of the first and the second sample respectively, and [math]\displaystyle{ \sup }[/math] is the supremum function.

For large samples, the null hypothesis is rejected at level [math]\displaystyle{ \alpha }[/math] if

[math]\displaystyle{ D_{n,m}\gt c(\alpha)\sqrt{\frac{n + m}{n\cdot m}}. }[/math]

Where [math]\displaystyle{ n }[/math] and [math]\displaystyle{ m }[/math] are the sizes of first and second sample respectively. The value of [math]\displaystyle{ c({\alpha}) }[/math] is given in the table below for the most common levels of [math]\displaystyle{ \alpha }[/math]

[math]\displaystyle{ \alpha }[/math] 0.20 0.15 0.10 0.05 0.025 0.01 0.005 0.001
[math]\displaystyle{ c({\alpha}) }[/math] 1.073 1.138 1.224 1.358 1.48 1.628 1.731 1.949

and in general[19] by

[math]\displaystyle{ c\left(\alpha\right)=\sqrt{-\ln\left(\tfrac{\alpha}{2}\right)\cdot \tfrac{1}{2}}, }[/math]

so that the condition reads

[math]\displaystyle{ D_{n,m}\gt \sqrt{-\ln\left(\tfrac{\alpha}{2}\right)\cdot \tfrac{1 + \tfrac{m}{n}}{2m}}. }[/math]

Here, again, the larger the sample sizes, the more sensitive the minimal bound: For a given ratio of sample sizes (e.g. [math]\displaystyle{ m=n }[/math]), the minimal bound scales in the size of either of the samples according to its inverse square root.

Note that the two-sample test checks whether the two data samples come from the same distribution. This does not specify what that common distribution is (e.g. whether it's normal or not normal). Again, tables of critical values have been published. A shortcoming of the univariate Kolmogorov–Smirnov test is that it is not very powerful because it is devised to be sensitive against all possible types of differences between two distribution functions. Some argue[20][21] that the Cucconi test, originally proposed for simultaneously comparing location and scale, can be much more powerful than the Kolmogorov–Smirnov test when comparing two distribution functions.

Setting confidence limits for the shape of a distribution function

While the Kolmogorov–Smirnov test is usually used to test whether a given F(x) is the underlying probability distribution of Fn(x), the procedure may be inverted to give confidence limits on F(x) itself. If one chooses a critical value of the test statistic Dα such that P(Dn > Dα) = α, then a band of width ±Dα around Fn(x) will entirely contain F(x) with probability 1 − α.

The Kolmogorov–Smirnov statistic in more than one dimension

A distribution-free multivariate Kolmogorov–Smirnov goodness of fit test has been proposed by Justel, Peña and Zamar (1997).[22] The test uses a statistic which is built using Rosenblatt's transformation, and an algorithm is developed to compute it in the bivariate case. An approximate test that can be easily computed in any dimension is also presented.

The Kolmogorov–Smirnov test statistic needs to be modified if a similar test is to be applied to multivariate data. This is not straightforward because the maximum difference between two joint cumulative distribution functions is not generally the same as the maximum difference of any of the complementary distribution functions. Thus the maximum difference will differ depending on which of [math]\displaystyle{ \Pr(x \lt X \land y \lt Y) }[/math] or [math]\displaystyle{ \Pr(X \lt x \land Y \gt y) }[/math] or any of the other two possible arrangements is used. One might require that the result of the test used should not depend on which choice is made.

One approach to generalizing the Kolmogorov–Smirnov statistic to higher dimensions which meets the above concern is to compare the cdfs of the two samples with all possible orderings, and take the largest of the set of resulting KS statistics. In d dimensions, there are 2d−1 such orderings. One such variation is due to Peacock[23] (see also Gosset[24] for a 3D version) and another to Fasano and Franceschini[25] (see Lopes et al. for a comparison and computational details).[26] Critical values for the test statistic can be obtained by simulations, but depend on the dependence structure in the joint distribution.

In one dimension, the Kolmogorov–Smirnov statistic is identical to the so-called star discrepancy D, so another native KS extension to higher dimensions would be simply to use D also for higher dimensions. Unfortunately, the star discrepancy is hard to calculate in high dimensions.

In 2021 the functional form of the multivariate KS test statistic was proposed, which simplified the problem of estimating the tail probabilities of the multivariate KS test statistic, which is needed for the statistical test. For the multivariate case, if Fi is the ith continuous marginal from a probability distribution with k variables, then

[math]\displaystyle{ \sqrt{n}D_n\xrightarrow{n\to\infty}\max_{1\le i \le k}\sup_t |B(F_i(t))| }[/math]

so the limiting distribution does not depend on the marginal distributions.[1]

Implementations

The Kolmogorov-Smirnov test is implemented in many software programs. Most of these implement both the one and two sampled test.

  • Mathematica has KolmogorovSmirnovTest.
  • MATLAB's Statistics Toolbox has kstest and kstest2 for one-sample and two-sample Kolmogorov-Smirnov tests, respectively.
  • The R package "KSgeneral"[10] computes the KS test statistics and its p-values under arbitrary, possibly discrete, mixed or continuous null distribution.
  • R's statistics base-package implements the test as ks.test {stats} in its "stats" package.
  • SAS implements the test in its PROC NPAR1WAY procedure.
  • In Python, the SciPy package implements the test in the scipy.stats.kstest function.[27]
  • SYSTAT (SPSS Inc., Chicago, IL)
  • Java has an implementation of this test provided by Apache Commons.[28]
  • KNIME has a node implementing this test based on the above Java implementation.[29]
  • Julia has the package HypothesisTests.jl with the function ExactOneSampleKSTest(x::AbstractVector{<:Real}, d::UnivariateDistribution).[30]
  • StatsDirect (StatsDirect Ltd, Manchester, UK) implements all common variants.
  • Stata (Stata Corporation, College Station, TX) implements the test in ksmirnov (Kolmogorov–Smirnov equality-of-distributions test) command.[31]
  • PSPP implements the test in its KOLMOGOROV-SMIRNOV (or using KS shortcut function).
  • The Real Statistics Resource Pack for Excel runs the test as KSCRIT and KSPROB.[32]

See also

References

  1. 1.0 1.1 Naaman, Michael (2021). "On the tight constant in the multivariate Dvoretzky-Kiefer-Wolfowitz inequality". Statistics and Probability Letters 173: 109088. doi:10.1016/j.spl.2021.109088. https://www.sciencedirect.com/science/article/pii/S016771522100050X. 
  2. Stephens, M. A. (1974). "EDF Statistics for Goodness of Fit and Some Comparisons". Journal of the American Statistical Association 69 (347): 730–737. doi:10.2307/2286009. 
  3. "Evaluating Kolmogorov's Distribution". Journal of Statistical Software 8 (18): 1–4. 2003. doi:10.18637/jss.v008.i18. 
  4. 4.0 4.1 Kolmogorov A (1933). "Sulla determinazione empirica di una legge di distribuzione". G. Ist. Ital. Attuari 4: 83–91. 
  5. Smirnov N (1948). "Table for estimating the goodness of fit of empirical distributions". Annals of Mathematical Statistics 19 (2): 279–281. doi:10.1214/aoms/1177730256. 
  6. "Small-Sample Corrections to Kolmogorov–Smirnov Test Statistic". Pioneer Journal of Theoretical and Applied Statistics 15 (1–2): 15–23. 2018. 
  7. 7.0 7.1 "Computing the Two-Sided Kolmogorov–Smirnov Distribution". Journal of Statistical Software 39 (11): 1–18. 2011. doi:10.18637/jss.v039.i11. 
  8. "Fast calculation of boundary crossing probabilities for Poisson processes". Statistics and Probability Letters 123: 177–182. 2017. doi:10.1016/j.spl.2016.11.027. 
  9. 9.0 9.1 9.2 "Computing the Kolmogorov–Smirnov Distribution when the Underlying cdf is Purely Discrete, Mixed or Continuous". Journal of Statistical Software 95 (10): 1–42. 2020. doi:10.18637/jss.v095.i10. 
  10. 10.0 10.1 10.2 Dimitrova, Dimitrina; Kaishev, Vladimir; Tan, Senren (2 October 2020). "KSgeneral: Computing P-Values of the KS Test for (Dis)Continuous Null Distribution". https://cran.r-project.org/web/packages/KSgeneral/index.html. 
  11. Pearson, E. S., ed (1972). Biometrika Tables for Statisticians. 2. Cambridge University Press. pp. 117–123, Tables 54, 55. ISBN 978-0-521-06937-3. 
  12. Shorack, Galen R.; Wellner, Jon A. (1986). Empirical Processes with Applications to Statistics. Wiley. p. 239. ISBN 978-0471867258. 
  13. Arnold, Taylor B.; Emerson, John W. (2011). "Nonparametric Goodness-of-Fit Tests for Discrete Null Distributions". The R Journal 3 (2): 34\[Dash]39. doi:10.32614/rj-2011-016. http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Arnold+Emerson.pdf. 
  14. "SAS/STAT(R) 14.1 User's Guide". https://support.sas.com/documentation/cdl/en/statug/68162/HTML/default/viewer.htm#statug_npar1way_toc.htm. 
  15. "ksmirnov — Kolmogorov–Smirnov equality-of-distributions test". https://www.stata.com/manuals15/rksmirnov.pdf. 
  16. "Note on the Kolmogorov Statistic in the Discrete Case". Metrika 7 (1): 115–116. 1963. doi:10.1007/bf02613966. 
  17. "A Comparison of the Pearson Chi-Square and Kolmogorov Goodness-of-Fit Tests with Respect to Validity". Journal of the American Statistical Association 60 (311): 854–858. 1965. doi:10.2307/2283251. 
  18. "Bounded Probability Properties of Kolmogorov–Smirnov and Similar Statistics for Discrete Data". Annals of the Institute of Statistical Mathematics 15 (1): 153–158. 1963. doi:10.1007/bf02865912. 
  19. Eq. (15) in Section 3.3.1 of Knuth, D.E., The Art of Computer Programming, Volume 2 (Seminumerical Algorithms), 3rd Edition, Addison Wesley, Reading Mass, 1998.
  20. Marozzi, Marco (2009). "Some Notes on the Location-Scale Cucconi Test". Journal of Nonparametric Statistics 21 (5): 629–647. doi:10.1080/10485250902952435. 
  21. Marozzi, Marco (2013). "Nonparametric Simultaneous Tests for Location and Scale Testing: a Comparison of Several Methods". Communications in Statistics – Simulation and Computation 42 (6): 1298–1317. doi:10.1080/03610918.2012.665546. 
  22. Justel, A.; Peña, D.; Zamar, R. (1997). "A multivariate Kolmogorov–Smirnov test of goodness of fit". Statistics & Probability Letters 35 (3): 251–259. doi:10.1016/S0167-7152(97)00020-5. 
  23. Peacock J.A. (1983). "Two-dimensional goodness-of-fit testing in astronomy". Monthly Notices of the Royal Astronomical Society 202 (3): 615–627. doi:10.1093/mnras/202.3.615. Bibcode1983MNRAS.202..615P. 
  24. Gosset E. (1987). "A three-dimensional extended Kolmogorov-Smirnov test as a useful tool in astronomy}". Astronomy and Astrophysics 188 (1): 258–264. Bibcode1987A&A...188..258G. 
  25. Fasano, G., Franceschini, A. (1987). "A multidimensional version of the Kolmogorov–Smirnov test". Monthly Notices of the Royal Astronomical Society 225: 155–170. doi:10.1093/mnras/225.1.155. ISSN 0035-8711. Bibcode1987MNRAS.225..155F. 
  26. Lopes, R.H.C., Reid, I., Hobson, P.R. (23–27 April 2007). "The two-dimensional Kolmogorov–Smirnov test". XI International Workshop on Advanced Computing and Analysis Techniques in Physics Research. Amsterdam, the Netherlands. http://dspace.brunel.ac.uk/bitstream/2438/1166/1/acat2007.pdf. 
  27. "scipy.stats.kstest". SciPy v1.7.1 Manual. The Scipy community. https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html. 
  28. "KolmogorovSmirnovTest". https://commons.apache.org/proper/commons-math/javadocs/api-3.5/org/apache/commons/math3/stat/inference/KolmogorovSmirnovTest.html. 
  29. "New statistics nodes". https://www.knime.com/whats-new-in-knime-37#new-statistics-nodes. 
  30. "Nonparametric tests · HypothesisTests.jl". https://juliastats.org/HypothesisTests.jl/stable/nonparametric/#Kolmogorov-Smirnov-test-1. 
  31. "ksmirnov — Kolmogorov –Smirnov equality-of-distributions test". https://www.stata.com/manuals15/rksmirnov.pdf. 
  32. "Kolmogorov-Smirnov Test for Normality Hypothesis Testing". http://www.real-statistics.com/tests-normality-and-symmetry/statistical-tests-normality-symmetry/kolmogorov-smirnov-test/. 

Further reading

External links