| Title: | Header-Only C++ Mathematical Optimization Library for 'Armadillo' |
| Version: | 0.3.11.2.1 |
| Description: | 'Ensmallen' is a templated C++ mathematical optimization library (by the 'MLPACK' team) that provides a simple set of abstractions for writing an objective function to optimize. Provided within are various standard and cutting-edge optimizers that include full-batch gradient descent techniques, small-batch techniques, gradient-free optimizers, and constrained optimization. The 'RcppEnsmallen' package includes the header files from the 'Ensmallen' library and pairs the appropriate header files from 'armadillo' through the 'RcppArmadillo' package. Therefore, users do not need to install 'Ensmallen' nor 'Armadillo' to use 'RcppEnsmallen'. Note that 'Ensmallen' is licensed under 3-Clause BSD, 'Armadillo' starting from 7.800.0 is licensed under Apache License 2, 'RcppArmadillo' (the 'Rcpp' bindings/bridge to 'Armadillo') is licensed under the GNU GPL version 2 or later. Thus, 'RcppEnsmallen' is also licensed under similar terms. Note that 'Ensmallen' requires a compiler that supports 'C++14' and 'Armadillo' 10.8.2 or later. |
| Depends: | R (≥ 4.3.0) |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://github.com/coatless-rpkg/rcppensmallen, https://r-pkg.thecoatlessprofessor.com/rcppensmallen/, https://github.com/mlpack/ensmallen, https://ensmallen.org/ |
| BugReports: | https://github.com/coatless-rpkg/rcppensmallen/issues |
| Encoding: | UTF-8 |
| LinkingTo: | Rcpp, RcppArmadillo |
| Imports: | Rcpp |
| Suggests: | knitr, rmarkdown, tinytest, quantreg, nnls |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-24 04:58:19 UTC; ronin |
| Author: | James Joseph Balamuta
|
| Maintainer: | James Joseph Balamuta <balamut2@illinois.edu> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-24 08:20:09 UTC |
RcppEnsmallen: Header-Only C++ Mathematical Optimization Library for 'Armadillo'
Description
'Ensmallen' is a templated C++ mathematical optimization library (by the 'MLPACK' team) that provides a simple set of abstractions for writing an objective function to optimize. Provided within are various standard and cutting-edge optimizers that include full-batch gradient descent techniques, small-batch techniques, gradient-free optimizers, and constrained optimization. The 'RcppEnsmallen' package includes the header files from the 'Ensmallen' library and pairs the appropriate header files from 'armadillo' through the 'RcppArmadillo' package. Therefore, users do not need to install 'Ensmallen' nor 'Armadillo' to use 'RcppEnsmallen'. Note that 'Ensmallen' is licensed under 3-Clause BSD, 'Armadillo' starting from 7.800.0 is licensed under Apache License 2, 'RcppArmadillo' (the 'Rcpp' bindings/bridge to 'Armadillo') is licensed under the GNU GPL version 2 or later. Thus, 'RcppEnsmallen' is also licensed under similar terms. Note that 'Ensmallen' requires a compiler that supports 'C++14' and 'Armadillo' 10.8.2 or later.
Author(s)
Maintainer: James Joseph Balamuta balamut2@illinois.edu (ORCID) [copyright holder]
Authors:
James Joseph Balamuta balamut2@illinois.edu (ORCID) [copyright holder]
Dirk Eddelbuettel edd@debian.org (ORCID) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/coatless-rpkg/rcppensmallen/issues
Least Absolute Deviations Regression with Particle Swarm Optimization
Description
Solves least absolute deviations regression by minimizing the sum of absolute residuals with the local best particle swarm optimizer.
Usage
lad_reg_pso(X, y)
Arguments
X |
A |
y |
A |
Details
The objective is the sum of absolute residuals:
f(\beta) = \sum_i \left\lvert y_i - \mathbf{x}_i^{T} \beta \right\rvert
Compared with the residual sum of squares, the absolute value leaves large residuals with a constant rather than a growing influence, so the fit tolerates heavy tailed errors and outlying responses.
The price is that the objective has a kink at every \beta that
makes a residual zero, and for a design with p columns a solution
sets p of the residuals to zero. The minimum therefore sits on the
kinks, where no gradient exists.
LADFunction in the source of this example supplies
double Evaluate(const arma::mat& beta);
and no Gradient(). That is ensmallen's arbitrary function contract.
Optimizers that need a derivative reject a class shaped this way at compile
time, so fewer optimizers accept it than accept the differentiable
objectives behind lin_reg_lbfgs() and logistic_reg_lbfgs().
Particle swarm optimization scatters candidate parameter vectors across the
search space and moves each one toward the best point it has seen and the
best point its neighbors have seen. Only the shape of the starting matrix
reaches the optimizer, since the swarm is placed at random. Those draws
come from R's random number generator, so set.seed() makes a run
reproducible. Unseeded runs land at slightly different points, and the
spread widens as X gains columns.
Value
The estimated \beta parameter values for the least absolute
deviations fit.
Examples
# Number of Points
n = 400
# Select beta parameters
beta = c(2, -1.5, 0.8)
# Number of Predictors (including intercept)
p = length(beta)
# The swarm is initialized at random, so fix the seed
set.seed(512)
# Generate predictors from a normal distribution
X_i = matrix(rnorm(n * (p - 1)), ncol = p - 1)
# Add an intercept
X = cbind(1, X_i)
# Generate responses with heavy tailed errors
y = X %*% beta + rt(n, df = 2)
# Run optimization with particle swarm optimization
theta_hat = lad_reg_pso(X, y)
# Compare against a derivative free search in base R
nm = optim(rep(0, p), function(b) sum(abs(y - X %*% b)),
method = "Nelder-Mead",
control = list(maxit = 20000, reltol = 1e-12))
cbind(actual = beta, ensmallen = theta_hat, optim = nm$par)
# Compare the objective each one reached
obj = function(b) sum(abs(y - X %*% b))
c(ensmallen = obj(theta_hat), optim = obj(nm$par))
Linear Regression with L-BFGS
Description
Solves the Linear Regression's Residual Sum of Squares using the L-BFGS optimizer.
Usage
lin_reg_lbfgs(X, y)
Arguments
X |
A |
y |
A |
Details
Consider the Residual Sum of Squares, also known as RSS, defined as:
RSS\left( \beta \right) = \left( { \mathbf{y} - \mathbf{X} \beta } \right)^{T} \left( \mathbf{y} - \mathbf{X} \beta \right)
The objective function is defined as:
f(\beta) = (y - X\beta)^2
The gradient is defined as:
\frac{\partial RSS}{\partial \beta} = -2 \mathbf{X}^{T} \left(\mathbf{y} - \mathbf{X} \beta \right)
Value
The estimated \beta parameter values for the linear regression.
Examples
# Number of Points
n = 1000
# Select beta parameters
beta = c(-2, 1.5, 3, 8.2, 6.6)
# Number of Predictors (including intercept)
p = length(beta)
# Generate predictors from a normal distribution
X_i = matrix(rnorm(n), ncol = p - 1)
# Add an intercept
X = cbind(1, X_i)
# Generate y values
y = X%*%beta + rnorm(n / (p - 1))
# Run optimization with lbfgs
theta_hat = lin_reg_lbfgs(X, y)
# Verify parameters were recovered
cbind(actual = beta, estimated = theta_hat)
Logistic Regression with Adam
Description
Solves logistic regression with the mini-batch Adam optimizer by expressing the negative log-likelihood as a separable objective function.
Usage
logistic_reg_adam(
X,
y,
batch_size = 32L,
max_epochs = 50L,
step_size = 0.05,
verbose = FALSE
)
Arguments
X |
A |
y |
A |
batch_size |
An |
max_epochs |
An |
step_size |
A |
verbose |
A |
Details
The objective and gradient match those of logistic_reg_lbfgs() with
lambda = 0, but are evaluated one mini-batch at a time.
The optimizer's MaxIterations() counts data points visited, not batches
and not epochs, so max_epochs is converted internally by multiplying by
nrow(X).
As of 'ensmallen' 3.10 the SGD family divides the step size by the batch
size, so a step size carried over from 'ensmallen' 2 will behave
differently unless ENS_OLD_SEPARABLE_STEP_BEHAVIOR is defined. This is why
step_size defaults to 0.05 rather than the 0.001 that ens::Adam itself
uses: with a batch size of 32 the effective step is 0.001 / 32, roughly
3e-5, which leaves the optimizer far short of the optimum after 50 epochs.
Adam shuffles the data between epochs. That shuffle draws on Armadillo's
random number generator, which 'RcppArmadillo' routes to R's own stream, so
the result is reproducible under set.seed(). The flip side is that each
call consumes random numbers from R's stream and therefore shifts any
runif() or rnorm() draws that follow it. Without an explicit seed,
successive calls start from different positions in the stream and so give
slightly different answers.
Value
The estimated \beta parameter values for the logistic regression.
Examples
# Number of Points
n = 5000
# Select beta parameters
beta = c(-1, 0.7, -0.5, 1.2)
# Number of Predictors (including intercept)
p = length(beta)
# Generate the design matrix with an intercept
X = cbind(1, matrix(rnorm(n * (p - 1)), ncol = p - 1))
# Generate binary responses
y = rbinom(n, size = 1, prob = 1 / (1 + exp(-X %*% beta)))
# Run optimization with Adam
theta_hat = logistic_reg_adam(X, y)
# Compare against the full-batch L-BFGS solution
cbind(actual = beta,
adam = theta_hat,
lbfgs = logistic_reg_lbfgs(X, y))
Logistic Regression with L-BFGS
Description
Solves logistic regression by minimizing the penalized negative log-likelihood with the L-BFGS optimizer.
Usage
logistic_reg_lbfgs(X, y, lambda = 0)
Arguments
X |
A |
y |
A |
lambda |
A |
Details
Writing \eta = \mathbf{X} \beta, the objective is the
penalized negative log-likelihood:
f(\beta) = \sum_i \left[ \log \left(1 + e^{\eta_i} \right) - y_i \eta_i \right] + \frac{\lambda}{2} \lVert \beta \rVert_2^2
with gradient
\nabla f(\beta) = \mathbf{X}^{T} \left( \sigma \left( \eta \right) - \mathbf{y} \right) + \lambda \beta
where \sigma is the logistic function.
The penalty is applied to every coefficient, including the intercept. This
keeps the example self-contained, since the function cannot know which
column of X holds the intercept. Production code normally leaves the
intercept unpenalized.
Because the objective is convex, optimization starts from a vector of zeros rather than a random point, which makes the result reproducible.
Value
The estimated \beta parameter values for the logistic regression.
Examples
# Number of Points
n = 1000
# Select beta parameters
beta = c(-1, 0.7, -0.5, 1.2)
# Number of Predictors (including intercept)
p = length(beta)
# Generate predictors from a normal distribution
X_i = matrix(rnorm(n * (p - 1)), ncol = p - 1)
# Add an intercept
X = cbind(1, X_i)
# Generate binary responses
y = rbinom(n, size = 1, prob = 1 / (1 + exp(-X %*% beta)))
# Run optimization with L-BFGS
theta_hat = logistic_reg_lbfgs(X, y)
# Compare against glm()
cbind(actual = beta,
ensmallen = theta_hat,
glm = glm.fit(X, y, family = binomial())$coefficients)
Logistic Regression with L-BFGS, Recording the Optimizer's Path
Description
Solves logistic regression as logistic_reg_lbfgs() does, and returns
every point the optimizer visited on the way rather than the fit alone.
Usage
logistic_reg_lbfgs_path(X, y, lambda = 0)
Arguments
X |
A |
y |
A |
lambda |
A |
Details
The objective, its gradient, the starting point and the optimizer settings
are those of logistic_reg_lbfgs(), which documents them. The only
addition is an ens::L_BFGS callback that copies the coordinates into a
matrix each time the optimizer moves.
A callback in 'ensmallen' is a plain class that defines whichever of the
documented hooks it needs; the library detects them at compile time. This
one uses BeginOptimization() for the starting point, StepTaken() for
each accepted step, and EndOptimization() for the point the run finished
on. Callbacks are passed as trailing arguments to Optimize().
The column count is not fixed. L-BFGS stops once the gradient norm falls below its tolerance or the objective stops improving, so the number of steps depends on the data. A point that repeats the previous one is not recorded twice.
Value
A matrix with one row per coefficient and one column per recorded point.
The first column is the starting point, a vector of zeros, and each column
after it holds the coordinates following one accepted step. The last column
is the fit, and matches what logistic_reg_lbfgs() returns for the same
arguments to within the optimizer's tolerance.
Coefficients run down the rows and iterations run across the columns, so
two coordinates can be traced against each other with
plot(path[2, ], path[4, ]).
Examples
# Number of Points
n = 1000
# Select beta parameters
beta = c(-1, 0.7, -0.5, 1.2)
# Number of Predictors (including intercept)
p = length(beta)
# Generate predictors from a normal distribution
X_i = matrix(rnorm(n * (p - 1)), ncol = p - 1)
# Add an intercept
X = cbind(1, X_i)
# Generate binary responses
y = rbinom(n, size = 1, prob = 1 / (1 + exp(-X %*% beta)))
# Record the path L-BFGS takes
path = logistic_reg_lbfgs_path(X, y)
# One row per coefficient, one column per recorded point
dim(path)
# The last column is the fit
cbind(actual = beta,
path = path[, ncol(path)],
lbfgs = drop(logistic_reg_lbfgs(X, y)))
# Trace two coefficients against each other
plot(path[2, ], path[4, ], type = "b", pch = 16,
xlab = "beta 2", ylab = "beta 4",
main = "L-BFGS path through two coordinates")
# Mark where the run started and where it ended
points(path[2, 1], path[4, 1], col = "blue", pch = 16, cex = 1.5)
points(path[2, ncol(path)], path[4, ncol(path)],
col = "red", pch = 16, cex = 1.5)
Non-Negative Least Squares with the Augmented Lagrangian
Description
Solves least squares subject to every coefficient being non-negative with the augmented Lagrangian optimizer.
Usage
nnls_auglag(X, y)
Arguments
X |
A |
y |
A |
Details
The objective is the residual sum of squares
f(\beta) = \lVert \mathbf{y} - \mathbf{X} \beta \rVert_2^2
with gradient
\nabla f(\beta) = -2 \mathbf{X}^{T} \left( \mathbf{y} - \mathbf{X} \beta \right)
minimized subject to \beta_j \ge 0 for every column
j of X.
ens::AugLagrangian calls for the constrained function contract, which
extends the Evaluate() and Gradient() pair of a differentiable function
with NumConstraints(), EvaluateConstraint() and GradientConstraint().
Every constraint is an equality, c_i(\beta) = 0, and a
bound has to be recast as a residual that is zero while the bound holds.
Here that residual is \min(0, \beta_j), one per
coefficient.
The bound is imposed through a penalty rather than by projection, so a coefficient resting on the boundary is returned as a small number of order 1e-10 rather than as exactly zero, and that number can be slightly negative. Round the result before comparing it with zero.
Optimization starts from a vector of zeros, which satisfies every constraint and makes the result reproducible.
Value
The estimated \beta parameter values, each of them
non-negative.
Examples
# Number of Points
n = 100
# Select beta parameters, two of which are exactly zero
beta = c(2, 0, 1.5, 0)
# Number of Predictors
p = length(beta)
set.seed(24)
# Generate predictors from a normal distribution
X = matrix(rnorm(n * p), ncol = p)
# Generate continuous responses
y = as.vector(X %*% beta + rnorm(n))
# The unconstrained least squares fit lands outside the feasible region
ols = qr.solve(X, y)
min(ols)
# Run optimization with the augmented Lagrangian
beta_hat = nnls_auglag(X, y)
# Compare against optim() with a lower bound of zero
rss = function(b) sum((y - X %*% b)^2)
box = optim(rep(0, p), rss, method = "L-BFGS-B", lower = rep(0, p))
cbind(actual = beta,
ols = ols,
ensmallen = beta_hat,
optim = box$par)