invgamma implements the [dpqr] statistics functions for the
inverse gamma
distribution
in R. It is ideal for using in other
packages since it is lightweight and leverages the [dpqr]gamma() line
of functions maintained by CRAN.
Please see the section on parameterizations below to avoid any
unintended mistakes!
Getting invgamma
There are two ways to get invgamma. For the CRAN
version, use
The functions in invgamma match those for the gamma distribution
provided by the stats package. Namely, it uses as its density f(x)
= (b^a / Gamma(a)) x^-(a+1) e^(-b/x), where a = shape and b = rate.
The PDF
(the f(x) above) can be evaluated with the dinvgamma() function:
library("invgamma")
x <- seq(0, 5, .01)
shape <- 7; rate <- 10
plot(x, dinvgamma(x, shape, rate), type = "l")
The
CDF
can be evaluated with the pinvgamma() function:
qqplot( "x" = ppoints(n) |> qinvgamma(shape, rate), "y" = draws,
xlab = "Theoretical quantiles", ylab = "Sample quantiles",
main = "QQ plot for inverse gamma draws"
)
abline(0, 1, col = "red")
Both of these indicate that the samplers are consistent. As an
inferential alternative, we can use a KS
test:
ks.test(
draws,
function(p) pinvgamma(p, shape, rate)
)
#
# Asymptotic one-sample Kolmogorov-Smirnov test
#
# data: draws
# D = 0.0029822, p-value = 0.3361
# alternative hypothesis: two-sided
The [dpqr]invchisq() and [dpqr]invexp() functions
The gamma
distribution subsumes
the
chi-squared
and
exponentialdistributions,
so it makes sense to include the *invchisq() and *invexp() functions
in invgamma. Their implementations, however, wrap *chisq() and
*exp(), not *invgamma().
A note on parameterizations
As detailed here, the
parameterizations of the functions in this package cue off of their
corresponding non-inverse distributions from stats. This commonly
causes the confusion that, for example, the parameter rate in
dinvgamma() is the rate parameter of the inverse gamma distribution.
It is not! It is the rate parameter of the corresponding gamma
distribution. Please take care with this distinction.
A note on numerics
invgamma was intended to be a lightweight and simple, largely
self-maintaining package implementing the inverse gamma, inverse
chi-square, and inverse exponential distributions. It uses the
transformation
theorem
in all cases.
One of the challenges to using naive implementations of distributions is
that their
numerics may
not work well. Arithmetic on a computer is not the same as arithmetic in
theory, the kind that you meet in math classes, and as a consequence the
best computer implementations of mathematical facts/algorithms need to
be tailored to the specific cases at hand.
In January 2023 I did a little poking around into this for rinvgamma()
and found that it performs poorly when the shape parameter is less than
.001 or so. The resulting distributions are very heavy-tailed, and the
draws from these distributions returned by rinvgamma() are so large
that they get rounded to either very large numbers (where the floating
point representation of numbers does not provide many numbers) or
infinity. Here’s an example:
Notice that rinvgamma() issues a warning in this circumstance; this is
the general behavior of invgamma: if a particular parameter
configuration is known to not produce valid results, a warning is
issued.
KS tests for sampling accuracy
rinvgamma()
Here is a more detailed Monte Carlo investigation that checks sampler
quality using the Kolmogorov-Smirnov
test.
First, we write a basic Monte Carlo test for the sampler that works by
generating a large (n = 1e6) sample of draws from the inverse gamma
distribution for a given shape and rate:
The function returns the p-value associated with the KS test, so
“small” values suggest a departure from the null hypothesis that the
distribution is from the corresponding inverse gamma distribution: the
sampler is performing poorly. Under the null hypothesis, the p-value
has an approximate uniform
distribution,
a fact that can be found in most advanced mathematical statistics books,
so we would expect some proportion to be small regardless.
We want to see the behavior of the sampler rinvgamma() across a wide
array of parameter values. To do this, we use a range of parameter
values running from small (10−4) to large (104):
And we visualize the distribution of the p-values over that space,
binning the colors to at .05 to highlight the rejections of the tests at
the 5% level:
ggplot(param_grid, aes(shape, rate, color = p_val)) +
geom_point() +
scale_x_log10(expression(alpha), n.breaks = 10, labels = fmt(-5:5)) +
scale_y_log10(expression(lambda), n.breaks = 10, labels = fmt(-5:5)) +
scale_color_binned(breaks = c(0, .05, 1)) +
labs(color = "p value") +
labs("title" = "KS GoF Test of Draws for Different Parameter Values") +
coord_equal()
If the sampler were working correctly, the p-values would be
approximately IID uniform(0,1), so we would expect about 5% of the
points to be purple, and those 5% would be uniformly distributed over
the whole space with no patterns. Obviously, that’s not the case: when
the shape parameter is small, the test is always rejecting. Clearly,
when shape is small, the sampler does not work well. Further
investigations reveal that, as an easy rule, the sampler can be
considered unreliable for shape values less than 0.01. As a
consequence, rinvgamma() issues a warning in those circumstances.
(This warning has been suppressed in the above computations.)
rinvchisq() and rinvexp()
Similar investigations using the inverse chi-squared and inverse
exponential reveal that rinvchisq() should not be trusted when
df <= .01 and ncp <= 10 and rinvexp() is trustworthy for all
values. Here is the illustration for the inverse chi-squared:
invgamma
invgamma implements the
[dpqr]statistics functions for the inverse gamma distribution in R. It is ideal for using in other packages since it is lightweight and leverages the[dpqr]gamma()line of functions maintained by CRAN.Please see the section on parameterizations below to avoid any unintended mistakes!
Getting invgamma
There are two ways to get invgamma. For the CRAN version, use
For the development version, use
The
[dpqr]invgamma()functionsThe functions in invgamma match those for the gamma distribution provided by the stats package. Namely, it uses as its density f(x) = (b^a / Gamma(a)) x^-(a+1) e^(-b/x), where a =
shapeand b =rate.The PDF (the f(x) above) can be evaluated with the
dinvgamma()function:The CDF can be evaluated with the
pinvgamma()function:The quantile function can be evaluated with
qinvgamma():And random number generation can be performed with
rinvgamma():rinvgamma()can be used to obtain a Monte Carlo estimate of the probability given bypinvgamma()above:Moreover, we can check the consistency and correctness of the implementation with first a kernel density estimate…
…and also a quantile plot…
Both of these indicate that the samplers are consistent. As an inferential alternative, we can use a KS test:
The
[dpqr]invchisq()and[dpqr]invexp()functionsThe gamma distribution subsumes the chi-squared and exponential distributions, so it makes sense to include the
*invchisq()and*invexp()functions in invgamma. Their implementations, however, wrap*chisq()and*exp(), not*invgamma().A note on parameterizations
As detailed here, the parameterizations of the functions in this package cue off of their corresponding non-inverse distributions from stats. This commonly causes the confusion that, for example, the parameter
rateindinvgamma()is the rate parameter of the inverse gamma distribution. It is not! It is the rate parameter of the corresponding gamma distribution. Please take care with this distinction.A note on numerics
invgamma was intended to be a lightweight and simple, largely self-maintaining package implementing the inverse gamma, inverse chi-square, and inverse exponential distributions. It uses the transformation theorem in all cases.
One of the challenges to using naive implementations of distributions is that their numerics may not work well. Arithmetic on a computer is not the same as arithmetic in theory, the kind that you meet in math classes, and as a consequence the best computer implementations of mathematical facts/algorithms need to be tailored to the specific cases at hand.
In January 2023 I did a little poking around into this for
rinvgamma()and found that it performs poorly when the shape parameter is less than .001 or so. The resulting distributions are very heavy-tailed, and the draws from these distributions returned byrinvgamma()are so large that they get rounded to either very large numbers (where the floating point representation of numbers does not provide many numbers) or infinity. Here’s an example:Notice that
rinvgamma()issues a warning in this circumstance; this is the general behavior of invgamma: if a particular parameter configuration is known to not produce valid results, a warning is issued.KS tests for sampling accuracy
rinvgamma()Here is a more detailed Monte Carlo investigation that checks sampler quality using the Kolmogorov-Smirnov test.
First, we write a basic Monte Carlo test for the sampler that works by generating a large (
n = 1e6) sample of draws from the inverse gamma distribution for a given shape and rate:The function returns the p-value associated with the KS test, so “small” values suggest a departure from the null hypothesis that the distribution is from the corresponding inverse gamma distribution: the sampler is performing poorly. Under the null hypothesis, the p-value has an approximate uniform distribution, a fact that can be found in most advanced mathematical statistics books, so we would expect some proportion to be small regardless.
We want to see the behavior of the sampler
rinvgamma()across a wide array of parameter values. To do this, we use a range of parameter values running from small (10−4) to large (104):Here’s what the experiment’s design space looks like:
Now, we run our test for each point in the design space in parallel. (Note: we’ve suppressed warnings here that are relevant.)
And we visualize the distribution of the p-values over that space, binning the colors to at .05 to highlight the rejections of the tests at the 5% level:
If the sampler were working correctly, the p-values would be approximately IID uniform(0,1), so we would expect about 5% of the points to be purple, and those 5% would be uniformly distributed over the whole space with no patterns. Obviously, that’s not the case: when the shape parameter is small, the test is always rejecting. Clearly, when
shapeis small, the sampler does not work well. Further investigations reveal that, as an easy rule, the sampler can be considered unreliable forshapevalues less than0.01. As a consequence,rinvgamma()issues a warning in those circumstances. (This warning has been suppressed in the above computations.)rinvchisq()andrinvexp()Similar investigations using the inverse chi-squared and inverse exponential reveal that
rinvchisq()should not be trusted whendf <= .01andncp <= 10andrinvexp()is trustworthy for all values. Here is the illustration for the inverse chi-squared:And here is the illustration for the inverse exponential: