# G-test

In statistics, G-tests are likelihood-ratio or maximum likelihood statistical significance tests that are increasingly being used in situations where chi-squared tests were previously recommended.

## Formulation

The general formula for G is
    $G=2\sum _{i}{O_{i}\cdot \ln \left({\frac {O_{i}}{E_{i}}}\right)},$
where O$_i$≥0{\textstyle O_{i}\geq 0} is the observed count in a cell, E$_i$>0{\textstyle E_{i}>0} is the expected count under the null hypothesis, ln{\textstyle \ln } denotes the natural logarithm, and the sum is taken over all non-empty cells. The resulting G{\textstyle G} is chi-squared distributed.
Furthermore, the total observed count should be equal to the total expected count:$\sum _{i}O_{i}=\sum _{i}E_{i}=N$where N{\textstyle N} is the total number of observations.

### Derivation

We can derive the value of the G-test from the log-likelihood ratio test where the underlying model is a multinomial model.
Suppose we had a sample x=(x$_1$, …, x$_m$){\textstyle x=(x_{1}, \ldots , x_{m})} where each x$_i${\textstyle x_{i}} is the number of times that an object of type i{\textstyle i} was observed. Furthermore, let n=∑$_{i=1}$$^m$x$_i${\textstyle n=\sum _{i=1}^{m}x_{i}} be the total number of objects observed. If we assume that the underlying model is multinomial, then the test statistic is defined by$\ln \left({\frac {L({\tilde {\theta }}|x)}{L({\hat {\theta }}|x)}}\right)=\ln \left({\frac {\prod _{i=1}^{m}{\tilde {\theta }}_{i}^{x_{i}}}{\prod _{i=1}^{m}{\hat {\theta }}_{i}^{x_{i}}}}\right)$where θ$^~${\textstyle {\tilde {\theta }}} is the null hypothesis and ${\hat {\theta }}$ is the maximum likelihood estimate (MLE) of the parameters given the data. Recall that for the multinomial model, the MLE of θ$^^$$_i${\textstyle {\hat {\theta }}_{i}} given some data is defined by${\hat {\theta }}_{i}={\frac {x_{i}}{n}}$Furthermore, we may represent each null hypothesis parameter ${\tilde {\theta }}_{i}$ as${\tilde {\theta }}_{i}={\frac {e_{i}}{n}}$Thus, by substituting the representations of θ$^~${\textstyle {\tilde {\theta }}} and θ$^^${\textstyle {\hat {\theta }}} in the log-likelihood ratio, the equation simplifies to${\begin{aligned}\ln \left({\frac {L({\tilde {\theta }}|x)}{L({\hat {\theta }}|x)}}\right)&=\ln \prod _{i=1}^{m}\left({\frac {e_{i}}{x_{i}}}\right)^{x_{i}}\\&=\sum _{i=1}^{m}x_{i}\ln \left({\frac {e_{i}}{x_{i}}}\right)\\\end{aligned}}$Relabel the variables e$_i${\textstyle e_{i}} with E$_i${\textstyle E_{i}} and x$_i${\textstyle x_{i}} with O$_i${\textstyle O_{i}}. Finally, multiply by a factor of −2{\textstyle -2} (used to make the G test formula asymptotically equivalent to the Pearson's chi-squared test formula) to achieve the form
${\begin{alignedat}{2}G&=&\;-2\sum _{i=1}^{m}O_{i}\ln \left({\frac {E_{i}}{O_{i}}}\right)\\&=&2\sum _{i=1}^{m}O_{i}\ln \left({\frac {O_{i}}{E_{i}}}\right)\end{alignedat}}$
Heuristically, one can imagine $~O_{i}~$ as continuous and approaching zero, in which case $~O_{i}\ln O_{i}\to 0~,$ and terms with zero observations can simply be dropped. However the expected count in each cell must be strictly greater than zero for each cell ($~E_{i}>0~\forall \,i~$) to apply the method.

## Distribution and use

Given the null hypothesis that the observed frequencies result from random sampling from a distribution with the given expected frequencies, the distribution of G is approximately a chi-squared distribution, with the same number of degrees of freedom as in the corresponding chi-squared test.
For very small samples the multinomial test for goodness of fit, and Fisher's exact test for contingency tables, or even Bayesian hypothesis selection are preferable to the G-test. McDonald recommends to always use an exact test (exact test of goodness-of-fit, Fisher's exact test) if the total sample size is less than 1 000 .
    There is nothing magical about a sample size of 1 000, it's just a nice round number that is well within the range where an exact test, chi-square test, and G–test will give almost identical p values. Spreadsheets, web-page calculators, and SAS shouldn't have any problem doing an exact test on a sample size of 1 000 .
             — John H. McDonald
G-tests have been recommended at least since the 1981 edition of Biometry, a statistics textbook by Robert R. Sokal and F. James Rohlf.

## Relation to other metrics
### Relation to the chi-squared test

The commonly used chi-squared tests for goodness of fit to a distribution and for independence in contingency tables are in fact approximations of the log-likelihood ratio on which the G-tests are based.
The general formula for Pearson's chi-squared test statistic is
    $\chi ^{2}=\sum _{i}{\frac {\left(O_{i}-E_{i}\right)^{2}}{E_{i}}}~.$
The approximation of G by chi squared is obtained by a second order Taylor expansion of the natural logarithm around 1 (see #Derivation (chi-squared) below). We have $G\approx \chi ^{2}$ when the observed counts $~O_{i}~$ are close to the expected counts $~E_{i}~.$ When this difference is large, however, the $~\chi ^{2}~$ approximation begins to break down. Here, the effects of outliers in data will be more pronounced, and this explains the why $~\chi ^{2}~$ tests fail in situations with little data.
For samples of a reasonable size, the G-test and the chi-squared test will lead to the same conclusions. However, the approximation to the theoretical chi-squared distribution for the G-test is better than for the Pearson's chi-squared test. In cases where $~O_{i}>2\cdot E_{i}~$ for some cell case the G-test is always better than the chi-squared test.
For testing goodness-of-fit the G-test is infinitely more efficient than the chi squared test in the sense of Bahadur, but the two tests are equally efficient in the sense of Pitman or in the sense of Hodges and Lehmann.

#### Derivation (chi-squared)

Consider
    $G=2\sum _{i}{O_{i}\ln \left({\frac {O_{i}}{E_{i}}}\right)}~,$
and let $O_{i}=E_{i}+\delta _{i}$ with $\sum _{i}\delta _{i}=0~,$ so that the total number of counts remains the same. Upon substitution we find,
    $G=2\sum _{i}{(E_{i}+\delta _{i})\ln \left(1+{\frac {\delta _{i}}{E_{i}}}\right)}~.$
A Taylor expansion around $1+{\frac {\delta _{i}}{E_{i}}}$ can be performed using $\ln(1+x)=x-{\frac {1}{2}}x^{2}+{\mathcal {O}}(x^{3})$. The result is
    $G=2\sum _{i}(E_{i}+\delta _{i})\left({\frac {\delta _{i}}{E_{i}}}-{\frac {1}{2}}{\frac {\delta _{i}^{2}}{E_{i}^{2}}}+{\mathcal {O}}\left(\delta _{i}^{3}\right)\right)~,$ and distributing terms we find,
    $G=2\sum _{i}\delta _{i}+{\frac {1}{2}}{\frac {\delta _{i}^{2}}{E_{i}}}+{\mathcal {O}}\left(\delta _{i}^{3}\right)~.$
Now, using the fact that $~\sum _{i}\delta _{i}=0~$ and $~\delta _{i}=O_{i}-E_{i}~,$ we can write the result,
    $~G\approx \sum _{i}{\frac {\left(O_{i}-E_{i}\right)^{2}}{E_{i}}}~.$

### Relation to Kullback–Leibler divergence

The G-test statistic is proportional to the Kullback–Leibler divergence of the theoretical distribution from the empirical distribution:
    ${\begin{aligned}G&=2\sum _{i}{O_{i}\cdot \ln \left({\frac {O_{i}}{E_{i}}}\right)}=2N\sum _{i}{o_{i}\cdot \ln \left({\frac {o_{i}}{e_{i}}}\right)}\\&=2N\,D_{\mathrm {KL} }(o\|e),\end{aligned}}$
where N is the total number of observations and $o_{i}$ and $e_{i}$ are the empirical and theoretical frequencies, respectively.

### Relation to mutual information

For analysis of contingency tables the value of G can also be expressed in terms of mutual information.
Let
    $N=\sum _{ij}{O_{ij}}\;$ , $\;\pi _{ij}={\frac {O_{ij}}{N}}\;$ , $\;\pi _{i.}={\frac {\sum _{j}O_{ij}}{N}}\;$, and $\;\pi _{.j}={\frac {\sum _{i}O_{ij}}{N}}\;$.
Then G can be expressed in several alternative forms:
    $G=2\cdot N\cdot \sum _{ij}{\pi _{ij}\left(\ln(\pi _{ij})-\ln(\pi _{i.})-\ln(\pi _{.j})\right)},$
    $G=2\cdot N\cdot \left[H(r)+H(c)-H(r,c)\right],$
    $G=2\cdot N\cdot \operatorname {MI} (r,c)\,,$
where the entropy of a discrete random variable $X\,$ is defined as
    $H(X)=-{\sum _{x\in {\text{Supp}}(X)}p(x)\log p(x)}\,,$
and where
    $\operatorname {MI} (r,c)=H(r)+H(c)-H(r,c)\,$
is the mutual information between the row vector r and the column vector c of the contingency table.
It can also be shown that the inverse document frequency weighting commonly used for text retrieval is an approximation of G applicable when the row sum for the query is much smaller than the row sum for the remainder of the corpus. Similarly, the result of Bayesian inference applied to a choice of single multinomial distribution for all rows of the contingency table taken together versus the more general alternative of a separate multinomial per row produces results very similar to the G statistic.

## Application

* The McDonald–Kreitman test in statistical genetics is an application of the G-test.
* Dunning introduced the test to the computational linguistics community where it is now widely used.
* The R-scape program (used by Rfam) uses G-test to detect co-variation between RNA sequence alignment positions.

## Statistical software

* In R fast implementations can be found in the AMR and Rfast packages. For the AMR package, the command is g.test which works exactly like chisq.test from base R. R also has the likelihood.test Archived 2013-12-16 at the Wayback Machine function in the Deducer Archived 2012-03-09 at the Wayback Machine package. Note: Fisher's G-test in the GeneCycle Package of the R programming language (fisher.g.test) does not implement the G-test as described in this article, but rather Fisher's exact test of Gaussian white-noise in a time series.
* Another R implementation to compute the G statistic and corresponding p-values is provided by the R package entropy. The commands are Gstat for the standard G statistic and the associated p-value and Gstatindep for the G statistic applied to comparing joint and product distributions to test independence.
* In SAS, one can conduct G-test by applying the /chisq option after the proc freq.
* In Stata, one can conduct a G-test by applying the lr option after the tabulate command.
* In Java, use org.apache.commons.math3.stat.inference.GTest.
* In Python, use scipy.stats.power_divergence with lambda_=0.