Learn R Programming

hpa (version 1.1.2)

hpaML: Semi-nonparametric maximum likelihood estimation

Description

This function performs semi-nonparametric maximum likelihood estimation via hermite polynomial densities approximation.

Usage

hpaML(
  x,
  pol_degrees = numeric(0),
  tr_left = numeric(0),
  tr_right = numeric(0),
  given_ind = logical(0),
  omit_ind = logical(0),
  x0 = numeric(0),
  cov_type = "sandwich",
  boot_iter = 100L,
  is_parallel = FALSE,
  opt_type = "optim",
  opt_control = NULL
)

Arguments

x

numeric matrix which rows are realizations of independent identically distributed random vectors while columns correspond to variables.

pol_degrees

non-negative integer vector of polynomial degrees.

tr_left

numeric matrix of left (lower) truncation limits. Note that tr_right rows are observations while variables are columns. If tr_left or tr_right is single row matrix then the same truncation limits would be applied to all observations that are determined by the first rows of these matrices.

tr_right

numeric matrix of right (upper) truncation limits. Note that tr_right rows are observations while variables are columns. If tr_left or tr_right is single row matrix then the same truncation limits would be applied to all observations that are determined by the first rows of these matrices.

given_ind

logical vector indicating wheather corresponding component is conditioned. By default it is a logical vector of FALSE values.

omit_ind

logical vector indicating wheather corresponding component is omitted. By default it is a logical vector of FALSE values.

x0

numeric vector of optimization routine initial values. Note that x0=c(pol_coefficients[-1], mean, sd). For pol_coefficients, mean and sd documentation see dhpa function.

cov_type

string value determining the type of covariance matrix to be returned and used for summary. If cov_type = "hessian" then negative inverse of Hessian matrix will be applied. If cov_type = "gop" then inverse of Jacobian outer products will be used. If cov_type = "sandwich" (default) then sandwich covariance matrix estimator will be applied. If cov_type = "bootstrap" then bootstrap with boot_iter iterations will be used. If cov_type = "hessianFD" or cov_type = "sandwichFD" then accurate but computationally demanding central difference Hessian approximation will be calculated for the inverse Hessian and sandwich estimators correspondingly. Central differences are computed via analytically provided gradient. This Hessian matrix estimation approach seems to be less accurate then BFGS approximation if polynomial order is high (usually greater then 5).

boot_iter

the number of bootstrap iterations for cov_type = "bootstrap" covariance matrix estimator type.

is_parallel

if TRUE then multiple cores will be used for some calculations. It usually provides speed advantage for large enough samples (about more than 1000 observations).

opt_type

string value determining the type of the optimization routine to be applied. The default is "optim" meaning that BFGS method from the optim function will be applied. If opt_type = "GA" then ga function will be additionally applied.

opt_control

a list containing arguments to be passed to the optimization routine depending on opt_type argument value. Please see details to get additional information.

Value

This function returns an object of class "hpaML". An object of class "hpaML" is a list containing the following components:

  • optim - optim function output. If opt_type = "GA" then it is the list containing optim and ga functions outputs.

  • x1 - numeric vector of distribution parameters estimates.

  • mean - density function mean vector estimate.

  • sd - density function sd vector estimate.

  • pol_coefficients - polynomial coefficients estimates.

  • tr_left - the same as tr_left input parameter.

  • tr_right - the same as tr_right input parameter.

  • omit_ind - the same as omit_ind input parameter.

  • given_ind - the same as given_ind input parameter.

  • cov_mat - covariance matrix estimate.

  • results - numeric matrix representing estimation results.

  • log-likelihood - value of Log-Likelihood function.

  • AIC - AIC value.

  • data - the same as x input parameter but without NA observations.

  • n_obs - number of observations.

  • bootstrap - list where bootstrap estimation results are stored.

Details

Semi-nonparametric (SNP) approach has been implemented via densities hermite polynomial approximation

Densities hermite polynomial approximation approach has been proposed by A. Gallant and D. W. Nychka in 1987. The main idea is to approximate unknown distribution density with hermite polynomial of degree pol_degree. In this framework hermite polynomial represents adjusted (to insure integration to 1) product of squared polynomial and normal distribution densities. Parameters mean and sd determine means and standard deviations of normal distribution density functions which are parts of this polynomial. For more information please refer to the literature listed below.

Parameters mean, sd, given_ind, omit_ind should have the same length as pol_degrees parameter.

The first polynomial coefficient (zero powers) set to 1 for identification reasons.

The function calculates standard errors via sandwich estimator and significance levels are reported taking into account quasi maximum likelihood estimator (QMLE) asymptotic normality. If ones wants to switch from QMLE to semi-nonparametric estimator (SNPE) during hypothesis testing then covariance matrix should be estimated again using bootstrap.

This function maximizes (quasi) log-likelihood function via optim function setting it's method argument to "BFGS". If opt_type = "GA" then genetic algorithm from ga function will be additionally (after optim putting it's solution (par) to suggestions matrix) applied in order to perform global optimization. Note that global optimization takes much more time (usually minutes but sometimes hours or even days). The number of iterations and population size of the genetic algorithm will grow linearly along with the number of estimated parameters. If it is seems that global maximum has not been found than it is possible to continue the search restarting the function setting it's input argument x0 to x1 output value. Note that if cov_type = "bootstrap" then ga function will not be used for bootstrap iterations since it may be extremely time consuming.

If opt_type = "GA" then opt_control should be the list containing the values to be passed to ga function. It is possible to pass arguments lower, upper, popSize, pcrossover, pmutation, elitism, maxiter, suggestions, optim, optimArgs, seed and monitor. Note that it is possible to set population, selection, crossover and mutation arguments changing ga default parameters via gaControl function. These arguments information reported in ga. In order to provide manual values for lower and upper bounds please follow parameters ordering mentioned above for the x0 argument. If these bonds are not provided manually then they (except those related to the polynomial coefficients) will depend on the estimates obtained by local optimization via optim function (this estimates will be in the middle between lower and upper). Specifically for each sd parameter lower (upper) bound is 5 times lower (higher) then this parameter optim estimate. For each mean and regression coefficient parameter it's lower and upper bounds deviate from corresponding optim estimate by two absolute value of this estimate. Finally, lower and upper bounds for each polynomial coefficient are -10 and 10 correspondingly (do not depend on their optim estimates).

The following arguments are differ from their defaults in ga:

  • pmutation = 0.2,

  • optim = TRUE,

  • optimArgs = list("method" = "Nelder-Mead", "poptim" = 0.2, "pressel" = 0.5),

  • seed = 8,

  • elitism = 2 + round(popSize * 0.1).

The arguments popSize and maxiter of ga function have been set proportional to the number of estimated polynomial coefficients

  • popSize = 10 + (prod(pol_degrees + 1) - 1) * 2.

  • maxiter = 50 * (prod(pol_degrees + 1))

References

A. Gallant and D. W. Nychka (1987) <doi:10.2307/1913241>

See Also

summary.hpaML, predict.hpaML, AIC.hpaML, logLik.hpaML

Examples

Run this code
# NOT RUN {
## Approximate student (t) distribution

# Set seed for reproducibility
set.seed(123)

# Simulate 5000 realizations of student distribution with 5 degrees of freedom
 n <- 5000
df <- 5
x <- matrix(rt(n, df), ncol = 1)
pol_degrees <- c(4)

# Apply pseudo maximum likelihood routine
ml_result <- hpa::hpaML(x = x, pol_degrees = pol_degrees)
summary(ml_result)

# Get predicted probabilites (density values) approximations
predict(ml_result)

# Plot density approximation
plot(ml_result)

## Approximate chi-squared distribution

# Set seed for reproducibility
set.seed(123)

# Simulate 5000 realizations of chi-squared distribution with 5 degrees of freedom

n <- 5000
df <- 5
x <- matrix(rchisq(n, df), ncol = 1)
pol_degrees <- c(5)

# Apply pseudo maximum likelihood routine
ml_result <- hpaML(x = x, pol_degrees = as.vector(pol_degrees), 
				tr_left = 0)
summary(ml_result)

# Get predicted probabilites (density values) approximations
predict(ml_result)

# Plot density approximation
plot(ml_result)

## Approximate multivariate student (t) distribution
## Note that calculations may take up to a minute

# Set seed for reproducibility
set.seed(123)

# Simulate 5000 realizations of three dimensional student distribution with 5 degrees of freedom
library("mvtnorm")
cov_mat <- matrix(c(1, 0.5, -0.5, 0.5, 1, 0.5, -0.5, 0.5, 1), ncol = 3)
x <- rmvt(n = 5000, sigma = cov_mat, df = 5)

# Estimate approximating joint distribution parameters
ml_result <- hpaML(x = x, pol_degrees = c(1, 1, 1))

# Get summary
summary(ml_result)

# Get predicted values for joint density function
predict(ml_result)

# Plot density approximation for the
# second random variable
plot(ml_result, ind = 2)

# Plot density approximation for the
# second random variable conditioning
# on x1 = 1
plot(ml_result, ind = 2, given = c(1, NA, NA))

## Approximate student (t) distribution and plot densities approximated
## under different hermite polynomial degrees against 
## true density (of student distribution)

# Simulate 5000 realizations of t-distribution with 5 degrees of freedom
n <- 5000
df <- 5
x <- matrix(rt(n, df), ncol=1)

# Apply pseudo maximum likelihood routine
# Create matrix of lists where i-th element contains hpaML results for K=i
ml_result <- matrix(list(), 4, 1)
for(i in 1:4)
{
 ml_result[[i]] <- hpa::hpaML(x = x, pol_degrees = i)
}

# Generate test values
test_values <- seq(qt(0.001, df), qt(0.999, df), 0.001)
n0 <- length(test_values)

# t-distribution density function at test values points
true_pred <- dt(test_values, df)

# Create matrix of lists where i-th element contains densities predictions for K=i
PGN_pred <- matrix(list(), 4, 1)
for(i in 1:4)
{
  PGN_pred[[i]] <- predict(object = ml_result[[i]], 
                           newdata = matrix(test_values, ncol=1))
}
# Plot the result
library("ggplot2")

# prepare the data
h <- data.frame("values" = rep(test_values,5),
                "predictions" = c(PGN_pred[[1]],PGN_pred[[2]],
                                  PGN_pred[[3]],PGN_pred[[4]],
                                  true_pred), 
                "Density" = c(
                  rep("K=1",n0), rep("K=2",n0),
                  rep("K=3",n0), rep("K=4",n0),
                  rep("t-distribution",n0))
                  )
                  
# build the plot
ggplot(h, aes(values, predictions)) + geom_point(aes(color = Density)) +
  theme_minimal() + theme(legend.position = "top", text = element_text(size=26),
                         legend.title=element_text(size=20), legend.text=element_text(size=28)) +
  guides(colour = guide_legend(override.aes = list(size=10))
  )

# Get informative estimates summary for K=4
summary(ml_result[[4]])
# }

Run the code above in your browser using DataLab