Glmnet is a package that fits a generalized linear model via penalized maximum likelihood. The regularization path is computed for the lasso or elasticnet penalty at a grid of values for the regularization parameter lambda. The algorithm is extremely fast, and can exploit sparsity in the input matrix `x`

. It fits linear, logistic and multinomial, poisson, and Cox regression models. A variety of predictions can be made from the fitted models. It can also fit multi-response linear regression.

The authors of glmnet are Jerome Friedman, Trevor Hastie, Rob Tibshirani and Noah Simon, and the R package is maintained by Trevor Hastie. The matlab version of glmnet is maintained by Junyang Qian. This vignette describes the usage of glmnet in R.

`glmnet`

solves the following problem
\[
\min_{\beta_0,\beta} \frac{1}{N} \sum_{i=1}^{N} w_i l(y_i,\beta_0+\beta^T x_i) + \lambda\left[(1-\alpha)||\beta||_2^2/2 + \alpha ||\beta||_1\right],
\]
over a grid of values of \( \lambda \) covering the entire range. Here \( l(y,\eta) \) is the negative log-likelihood contribution for observation \( i \); e.g. for the Gaussian case it is \( \frac{1}{2}(y-\eta)^2 \). The *elastic-net* penalty is controlled by \( \alpha \), and bridges the gap between lasso (\( \alpha=1 \), the default) and ridge (\( \alpha=0 \)). The tuning parameter \( \lambda \) controls the overall strength of the penalty.

It is known that the ridge penalty shrinks the coefficients of correlated predictors towards each other while the lasso tends to pick one of them and discard the others. The elastic-net penalty mixes these two; if predictors are correlated in groups, an \( \alpha=0.5 \) tends to select the groups in or out together. This is a higher level parameter, and users might pick a value upfront, else experiment with a few different values. One use of \( \alpha \) is for numerical stability; for example, the elastic net with \( \alpha = 1 - \epsilon \) for some small \( \epsilon > 0 \) performs much like the lasso, but removes any degeneracies and wild behavior caused by extreme correlations.

The `glmnet`

algorithms use cyclical coordinate descent, which successively optimizes the objective function over each parameter with others fixed, and cycles repeatedly until convergence. The package also makes use of the strong rules for efficient restriction of the active set. Due to highly efficient updates and techniques such as warm starts and active-set convergence, our algorithms can compute the solution path very fast.

The code can handle sparse input-matrix formats, as well as range constraints on coefficients. The core of `glmnet`

is a set of fortran subroutines, which make for very fast execution.

The package also includes methods for prediction and plotting, and a function that performs K-fold cross-validation.

Like many other R packages, the simplest way to obtain `glmnet`

is to install it directly from CRAN. Type the following command in R console:

```
install.packages("glmnet", repos = "http://cran.us.r-project.org")
```

```
##
## The downloaded binary packages are in
## /var/folders/f4/c1t2d_5d0lb6z9g3pp8gs5_m0000gq/T//Rtmp7B8EBA/downloaded_packages
```

Users may change the `repos`

options depending on their locations and preferences. Other options such as the directories where to install the packages can be altered in the command. For more details, see `help(install.packages)`

.

Here the R package has been downloaded and installed to the default directories.

Alternatively, users can download the package source at http://cran.r-project.org/web/packages/glmnet/index.html and type Unix commands to install it to the desired location.

The purpose of this section is to give users a general sense of the package, including the components, what they do and some basic usage. We will briefly go over the main functions, see the basic operations and have a look at the outputs. Users may have a better idea after this section what functions are available, which one to choose, or at least where to seek help. More details are given in later sections.

First, we load the `glmnet`

package:

```
library(glmnet)
```

```
## Loading required package: Matrix
## Loaded glmnet 1.9-5
```

The default model used in the package is the Guassian linear model or “least squares”, which we will demonstrate in this section. We load a set of data created beforehand for illustration. Users can either load their own data or use those saved in the workspace.

```
load("QSExample.RData")
```

The command loads an input matrix `x`

and a response vector `y`

from this saved R data archive.

We fit the model using the most basic call to `glmnet`

.

```
fit = glmnet(x, y)
```

“fit” is an object of class `glmnet`

that contains all the relevant information of the fitted model for further use. We do not encourage users to extract the components directly. Instead, various methods are provided for the object such as `plot`

, `print`

, `coef`

and `predict`

that enable us to execute those tasks more elegantly.

We can visualize the coefficients by executing the `plot`

function:

```
plot(fit)
```

Each curve corresponds to a variable. It shows the path of its coefficient against the \( \ell_1 \)-norm of the whole coefficient vector at as \( \lambda \) varies. The axis above indicates the number of nonzero coefficients at the current \( \lambda \), which is the effective degrees of freedom (*df*) for the lasso. Users may also wish to annotate the curves; this can be done by setting `label = TRUE`

in the plot command.

A summary of the `glmnet`

path at each step is displayed if we just enter the object name or use the `print`

function:

```
print(fit)
```

```
##
## Call: glmnet(x = x, y = y)
##
## Df %Dev Lambda
## [1,] 0 0.0000 1.63000
## [2,] 2 0.0553 1.49000
## [3,] 2 0.1460 1.35000
## [4,] 2 0.2210 1.23000
## [5,] 2 0.2840 1.12000
## [6,] 2 0.3350 1.02000
## [7,] 4 0.3900 0.93300
## [8,] 5 0.4560 0.85000
## [9,] 5 0.5150 0.77500
## [10,] 6 0.5740 0.70600
## [11,] 6 0.6260 0.64300
## [12,] 6 0.6690 0.58600
## [13,] 6 0.7050 0.53400
## [14,] 6 0.7340 0.48700
## [15,] 7 0.7620 0.44300
## [16,] 7 0.7860 0.40400
## [17,] 7 0.8050 0.36800
## [18,] 7 0.8220 0.33500
## [19,] 7 0.8350 0.30600
## [20,] 7 0.8460 0.27800
## [21,] 7 0.8560 0.25400
## [22,] 7 0.8630 0.23100
## [23,] 8 0.8710 0.21100
## [24,] 8 0.8770 0.19200
## [25,] 8 0.8820 0.17500
## [26,] 8 0.8860 0.15900
## [27,] 8 0.8900 0.14500
## [28,] 8 0.8930 0.13200
## [29,] 8 0.8960 0.12100
## [30,] 8 0.8980 0.11000
## [31,] 9 0.8990 0.10000
## [32,] 9 0.9010 0.09120
## [33,] 9 0.9020 0.08310
## [34,] 9 0.9030 0.07570
## [35,] 10 0.9040 0.06900
## [36,] 11 0.9050 0.06280
## [37,] 11 0.9060 0.05730
## [38,] 12 0.9070 0.05220
## [39,] 15 0.9080 0.04750
## [40,] 16 0.9090 0.04330
## [41,] 16 0.9090 0.03950
## [42,] 16 0.9100 0.03600
## [43,] 17 0.9100 0.03280
## [44,] 17 0.9110 0.02990
## [45,] 18 0.9110 0.02720
## [46,] 18 0.9110 0.02480
## [47,] 19 0.9120 0.02260
## [48,] 19 0.9120 0.02060
## [49,] 19 0.9120 0.01870
## [50,] 19 0.9120 0.01710
## [51,] 19 0.9130 0.01560
## [52,] 19 0.9130 0.01420
## [53,] 19 0.9130 0.01290
## [54,] 19 0.9130 0.01180
## [55,] 19 0.9130 0.01070
## [56,] 19 0.9130 0.00978
## [57,] 19 0.9130 0.00891
## [58,] 19 0.9130 0.00812
## [59,] 19 0.9130 0.00740
## [60,] 19 0.9130 0.00674
## [61,] 19 0.9130 0.00614
## [62,] 20 0.9130 0.00559
## [63,] 20 0.9130 0.00510
## [64,] 20 0.9130 0.00464
## [65,] 20 0.9130 0.00423
## [66,] 20 0.9130 0.00386
## [67,] 20 0.9130 0.00351
```

It shows from left to right the number of nonzero coefficients (`Df`

), the percent (of null) deviance explained (`%dev`

) and the value of \( \lambda \) (`Lambda`

). Although by default `glmnet`

calls for 100 values of `lambda`

the program stops early if %dev% does not change sufficently from one lambda to the next (typically near the end of the path.)

We can obtain the actual coefficients at one or more \( \lambda \)'s within the range of the sequence:

```
coef(fit, s = 0.1)
```

```
## 21 x 1 sparse Matrix of class "dgCMatrix"
## 1
## (Intercept) 0.150928
## V1 1.320597
## V2 .
## V3 0.675110
## V4 .
## V5 -0.817412
## V6 0.521437
## V7 0.004829
## V8 0.319416
## V9 .
## V10 .
## V11 0.142499
## V12 .
## V13 .
## V14 -1.059979
## V15 .
## V16 .
## V17 .
## V18 .
## V19 .
## V20 -1.021874
```

(why `s`

and not `lambda`

? In case later we want to allow one to specify the model size in other ways.)
Users can also make predictions at specific \( \lambda \)'s with new input data:

```
nx = matrix(rnorm(10 * 20), 10, 20)
predict(fit, newx = nx, s = c(0.1, 0.05))
```

```
## 1 2
## [1,] 0.8231 1.1442
## [2,] 0.6223 0.6098
## [3,] -0.9225 -1.0475
## [4,] 1.5652 1.5358
## [5,] 3.6345 3.8440
## [6,] 0.7437 0.7559
## [7,] 1.0432 1.1380
## [8,] -3.4333 -3.6218
## [9,] -2.8670 -3.0409
## [10,] 2.2482 2.4189
```

The function `glmnet`

returns a sequence of models for the users to choose from. In many cases, users may prefer the software to select one of them. Cross-validation is perhaps the simplest and most widely used method for that task.

`cv.glmnet`

is the main function to do cross-validation here, along with various supporting methods such as plotting and prediction. We still act on the sample data loaded before.

```
cvfit = cv.glmnet(x, y)
```

`cv.glmnet`

returns a `cv.glmnet`

object, which is “cvfit” here, a list with all the ingredients of the cross-validation fit. As for `glmnet`

, we do not encourage users to extract the components directly except for viewing the selected values of \( \lambda \). The package provides well-designed functions for potential tasks.

We can plot the object.

```
plot(cvfit)
```

It includes the cross-validation curve (red dotted line), and upper and lower standard deviation curves along the \( \lambda \) sequence (error bars). Two selected \( \lambda \)'s are indicated by the vertical dotted lines (see below).

We can view the selected \( \lambda \)'s and the corresponding coefficients. For example,

```
cvfit$lambda.min
```

```
## [1] 0.07569
```

`lambda.min`

is the value of \( \lambda \) that gives minimum mean cross-validated error. The other \( \lambda \) saved is `lambda.1se`

, which gives the most regularized model such that error is within one standard error of the minimum. To use that, we only need to replace `lambda.min`

with `lambda.1se`

above.

```
coef(cvfit, s = "lambda.min")
```

```
## 21 x 1 sparse Matrix of class "dgCMatrix"
## 1
## (Intercept) 0.14867
## V1 1.33378
## V2 .
## V3 0.69788
## V4 .
## V5 -0.83727
## V6 0.54334
## V7 0.02669
## V8 0.33741
## V9 .
## V10 .
## V11 0.17105
## V12 .
## V13 .
## V14 -1.07553
## V15 .
## V16 .
## V17 .
## V18 .
## V19 .
## V20 -1.05279
```

Note that the coefficients are represented in the sparse matrix format. The reason is that the solutions along the regularization path are often sparse, and hence it is more efficient in time and space to use a sparse format. If you prefer non-sparse format, pipe the output through `as.matrix()`

.

Predictions can be made based on the fitted `cv.glmnet`

object. Let's see a toy example.

```
predict(cvfit, newx = x[1:5, ], s = "lambda.min")
```

```
## 1
## [1,] -1.364
## [2,] 2.571
## [3,] 0.573
## [4,] 1.988
## [5,] 1.518
```

`newx`

is for the new input matrix and `s`

, as before, is the value(s) of \( \lambda \) at which predictions are made.

That is the end of `glmnet`

101. With the tools introduced so far, users are able to fit the entire elastic net family, including ridge regression, using squared-error loss. In the package, there are many more options that give users a great deal of flexibility. To learn more, move on to later sections.

Linear regression here refers to two families of models. One is `gaussian`

, the Gaussian family, and the other is `mgaussian`

, the multiresponse Gaussian family. We first discuss the ordinary Gaussian and the multiresponse one after that.

`gaussian`

is the default family option in the function `glmnet`

. Suppose we have observations \( x_i \in \mathbb{R}^p \) and the responses \( y_i \in \mathbb{R}, i = 1, \ldots, N \). The objective function for the Gaussian family is
\[
\min_{(\beta_0, \beta) \in \mathbb{R}^{p+1}}\frac{1}{2N} \sum_{i=1}^N (y_i -\beta_0-x_i^T \beta)^2+\lambda \left[ (1-\alpha)||\beta||_2^2/2 + \alpha||\beta||_1\right],
\]
where \( \lambda \geq 0 \) is a complexity parameter and \( 0 \leq \alpha \leq 1 \) is a compromise between ridge (\( \alpha = 0 \)) and lasso (\( \alpha = 1 \)).

Coordinate descent is applied to solve the problem. Specifically, suppose we have current estimates \( \tilde{\beta_0} \) and \( \tilde{\beta}_\ell \) \( \forall j\in 1,]\ldots,p \). By computing the gradient at \( \beta_j = \tilde{\beta}_j \) and simple calculus, the update is \[ \tilde{\beta}_j \leftarrow \frac{S(\frac{1}{N}\sum_{i=1}^N x_{ij}(y_i-\tilde{y}_i^{(j)}),\lambda \alpha)}{1+\lambda(1-\alpha)}, \] where \( \tilde{y}_i^{(j)} = \tilde{\beta}_0 + \sum_{\ell \neq j} x_{i\ell} \tilde{\beta}_\ell \), and \( S(z, \gamma) \) is the soft-thresholding operator with value \( \text{sign}(z)(|z|-\gamma)_+ \).

This formula above applies when the `x`

variables are standardized to have unit variance (the default); it is slightly more complicated when they are not. Note that for “family=gaussian”, `glmnet`

standardizes \( y \) to have unit variance before computing its lambda sequence (and then unstandardizes the resulting coefficients); if you wish to reproduce/compare results with other software, best to supply a standardized \( y \) first (Using the “1/N” variance formula).

`glmnet`

provides various options for users to customize the fit. We introduce some commonly used options here and they can be specified in the `glmnet`

function.

`alpha`

is for the elastic-net mixing parameter \( \alpha \), with range \( \alpha \in [0,1] \). \( \alpha = 1 \) is the lasso (default) and \( \alpha = 0 \) is the ridge.`weights`

is for the observation weights. Default is 1 for each observation. (Note:`glmnet`

rescales the weights to sum to N, the sample size.)`nlambda`

is the number of \( \lambda \) values in the sequence. Default is 100.`lambda`

can be provided, but is typically not and the program constructs a sequence. When automatically generated, the \( \lambda \) sequence is determined by`lambda.max`

and`lambda.min.ratio`

. The latter is the ratio of smallest value of the generated \( \lambda \) sequence (say`lambda.min`

) to`lambda.max`

. The program then generated`nlambda`

values linear on the log scale from`lambda.max`

down to`lambda.min`

.`lambda.max`

is not given, but easily computed from the input \( x \) and \( y \); it is the smallest value for`lambda`

such that all the coefficients are zero. For`alpha=0`

(ridge)`lambda.max`

would be \( \infty \); hence for this case we pick a value corresponding to a small value for`alpha`

close to zero.)`standardize`

is a logical flag for`x`

variable standardization, prior to fitting the model sequence. The coefficients are always returned on the original scale. Default is`standardize=TRUE`

.

For more information, type `help(glmnet)`

or simply `?glmnet`

.

As an example, we set \( \alpha = 0.2 \) (more like a ridge regression), and give double weights to the latter half of the observations. To avoid too long a display here, we set `nlambda`

to 20. In practice, however, the number of values of \( \lambda \) is recommended to be 100 (default) or more. In most cases, it does not come with extra cost because of the warm-starts used in the algorithm, and for nonlinear models leads to better convergence properties.

```
fit = glmnet(x, y, alpha = 0.2, weights = c(rep(1, 50), rep(2, 50)), nlambda = 20)
```

We can then print the `glmnet`

object.

```
print(fit)
```

```
##
## Call: glmnet(x = x, y = y, weights = c(rep(1, 50), rep(2, 50)), alpha = 0.2, nlambda = 20)
##
## Df %Dev Lambda
## [1,] 0 0.000 7.94000
## [2,] 4 0.179 4.89000
## [3,] 7 0.444 3.01000
## [4,] 7 0.657 1.85000
## [5,] 8 0.785 1.14000
## [6,] 9 0.854 0.70300
## [7,] 10 0.887 0.43300
## [8,] 11 0.902 0.26700
## [9,] 14 0.910 0.16400
## [10,] 17 0.914 0.10100
## [11,] 17 0.915 0.06230
## [12,] 17 0.916 0.03840
## [13,] 19 0.916 0.02360
## [14,] 20 0.916 0.01460
## [15,] 20 0.916 0.00896
## [16,] 20 0.916 0.00552
## [17,] 20 0.916 0.00340
```

This displays the call that produced the object `fit`

and a three-column matrix with columns `Df`

(the number of nonzero coefficients), `%dev`

(the percent deviance explained) and `Lambda`

(the corresponding value of \( \lambda \)).

(Note that the `digits`

option can used to specify significant digits in the printout.)

Here the actual number of \( \lambda \)'s here is less than specified in the call. The reason lies in the stopping criteria of the algorithm. According to the default internal settings, the computations stop if either the fractional change in deviance down the path is less than \( 10^{-5} \) or the fraction of explained deviance reaches \( 0.999 \). From the last few lines , we see the fraction of deviance does not change much and therefore the computation ends when meeting the stopping criteria. We can change such internal parameters. For details, see the Appendix section or type `help(glmnet.control)`

.

We can plot the fitted object as in the previous section. There are more options in the `plot`

function.

Users can decide what is on the X-axis. `xvar`

allows three measures: “norm” for the \( \ell_1 \)-norm of the coefficients (default), “lambda” for the log-lambda value and “dev” for %deviance explained.

Users can also label the curves with variable sequence numbers simply by setting `label = TRUE`

.

Let's plot “fit” against the log-lambda value and with each curve labeled.

```
plot(fit, xvar = "lambda", label = TRUE)
```

Now when we plot against %deviance we get a very different picture. This is percent deviance explained on the training data. What we see here is that toward the end of the path this value are not changing much, but the coefficients are “blowing up” a bit. This lets us focus attention on the parts of the fit that matter. This will especially be true for other models, such as logistic regression.

```
plot(fit, xvar = "dev", label = TRUE)
```

We can extract the coefficients and make predictions at certain values of \( \lambda \). Two commonly used options are:

`s`

specifies the value(s) of \( \lambda \) at which extraction is made.`exact`

indicates whether the exact values of coefficients are desired or not. That is, if`exact = TRUE`

, and predictions are to be made at values of s not included in the original fit, these values of s are merged with`object$lambda`

, and the model is refit before predictions are made. If`exact=FALSE`

(default), then the predict function uses linear interpolation to make predictions for values of s that do not coincide with lambdas used in the fitting algorithm.

A simple example is:

```
any(fit$lambda == 0.5)
```

```
## [1] FALSE
```

```
coef.exact = coef(fit, s = 0.5, exact = TRUE)
coef.apprx = coef(fit, s = 0.5, exact = FALSE)
cbind2(coef.exact, coef.apprx)
```

```
## 21 x 2 sparse Matrix of class "dgCMatrix"
## 1 1
## (Intercept) 0.19657 0.199099
## V1 1.17496 1.174650
## V2 . .
## V3 0.52934 0.531935
## V4 . .
## V5 -0.76126 -0.760959
## V6 0.46627 0.468209
## V7 0.06148 0.061927
## V8 0.38049 0.380301
## V9 . .
## V10 . .
## V11 0.14214 0.143261
## V12 . .
## V13 . .
## V14 -0.91090 -0.911207
## V15 . .
## V16 . .
## V17 . .
## V18 . 0.009197
## V19 . .
## V20 -0.86099 -0.863117
```

The left column is for `exact = TRUE`

and the right for `FALSE`

. We see from the above that 0.01 is not in the sequence and that hence there are some difference, though not much. Linear interpolation is mostly enough if there are no special requirements.

Users can make predictions from the fitted object. In addition to the options in `coef`

, the primary argument is `newx`

, a matrix of new values for `x`

. The `type`

option allows users to choose the type of prediction:

“link” gives the fitted values

“response” the sames as “link” for “gaussian” family.

“coefficients” computes the coefficients at values of

`s`

“nonzero” retuns a list of the indices of the nonzero coefficients for each value of

`s`

.

For example,

```
predict(fit, newx = x[1:5, ], type = "response", s = 0.05)
```

```
## 1
## [1,] -0.9803
## [2,] 2.2992
## [3,] 0.6011
## [4,] 2.3573
## [5,] 1.7520
```

gives the fitted values for the first 5 observations at \( \lambda = 0.05 \). If multiple values of `s`

are supplied, a matrix of predictions is produced.

Users can customize K-fold cross-validation. In addition to all the `glmnet`

parameters, `cv.glmnet`

has its special parameters including `nfolds`

(the number of folds), `foldid`

(user-supplied folds), `type.measure`

(the loss used for cross-validation):

“deviance” or “mse” uses squared loss

“mae” uses mean absolute error

As an example,

```
cvfit = cv.glmnet(x, y, type.measure = "mse", nfolds = 20)
```

does 20-fold cross-validation, based on mean squared error criterion (default though).

Parallel computing is also supported by `cv.glmnet`

. To make it work, users must register parallel beforehand. We give a simple example of comparison here.

```
require(doMC)
```

```
## Loading required package: doMC
## Loading required package: foreach
## Loading required package: iterators
## Loading required package: parallel
```

```
registerDoMC(cores = 2)
X = matrix(rnorm(10000 * 200), 10000, 200)
Y = rnorm(10000)
```

```
system.time(cv.glmnet(X, Y))
```

```
## user system elapsed
## 3.995 0.107 4.103
```

```
system.time(cv.glmnet(X, Y, parallel = TRUE))
```

```
## user system elapsed
## 0.600 0.087 2.053
```

As suggested from the above, parallel computing can significantly speed up the computation process especially for large-scale problems.

Functions `coef`

and `predict`

on cv.glmnet object are similar to those for a `glmnet`

object, except that two special strings are also supported by `s`

(the values of \( \lambda \) requested):

“lambda.1se”: the largest \( \lambda \) at which the MSE is within one standard error of the minimal MSE.

“lambda.min”: the \( \lambda \) at which the minimal MSE is achieved.

```
cvfit$lambda.min
```

```
## [1] 0.06897
```

```
coef(cvfit, s = "lambda.min")
```

```
## 21 x 1 sparse Matrix of class "dgCMatrix"
## 1
## (Intercept) 0.147927
## V1 1.337394
## V2 .
## V3 0.704086
## V4 .
## V5 -0.842853
## V6 0.549403
## V7 0.032704
## V8 0.342431
## V9 .
## V10 0.001207
## V11 0.178996
## V12 .
## V13 .
## V14 -1.079993
## V15 .
## V16 .
## V17 .
## V18 .
## V19 .
## V20 -1.061382
```

```
predict(cvfit, newx = x[1:5, ], s = "lambda.min")
```

```
## 1
## [1,] -1.3627
## [2,] 2.5737
## [3,] 0.5767
## [4,] 2.0063
## [5,] 1.5410
```

Users can control the folds used. Here we use the same folds so we can also select a value for \( \alpha \).

```
foldid = sample(1:10, size = length(y), replace = TRUE)
cv1 = cv.glmnet(x, y, foldid = foldid, alpha = 1)
cv.5 = cv.glmnet(x, y, foldid = foldid, alpha = 0.5)
cv0 = cv.glmnet(x, y, foldid = foldid, alpha = 0)
```

There are no built-in plot functions to put them all on the same plot, so we are on our own here:

```
par(mfrow = c(2, 2))
plot(cv1)
plot(cv.5)
plot(cv0)
plot(log(cv1$lambda), cv1$cvm, pch = 19, col = "red", xlab = "log(Lambda)",
ylab = cv1$name)
points(log(cv.5$lambda), cv.5$cvm, pch = 19, col = "grey")
points(log(cv0$lambda), cv0$cvm, pch = 19, col = "blue")
legend("topleft", legend = c("alpha= 1", "alpha= .5", "alpha 0"), pch = 19,
col = c("red", "grey", "blue"))
```

We see that lasso (`alpha=1`

) does about the best here. We also see that the range of lambdas used differs with alpha.

These are recently added features that enhance the scope of the models. Suppose we want to fit our model, but limit the coefficients to be bigger than -0.7 and less than 0.5. This is easily achieved via the `upper.limits`

and `lower.limits`

arguments:

```
tfit = glmnet(x, y, lower = -0.7, upper = 0.5)
plot(tfit)
```

These are rather arbitrary limits; often we want the coefficients to be positive, so we can set only `lower.limit`

to be 0.
(Note, the lower limit must be no bigger than zero, and the upper limit no smaller than zero.)
These bounds can be a vector, with different values for each coefficient. If given as a scalar, the same number gets recycled for all.

This argument allows users to apply separate penalty factors to each coefficient. Its default is 1 for each parameter, but other values can be specified. In particular, any variable with `penalty.factor`

equal to zero is not penalized at all! Let \( v_j \) denote the penalty factor for \( j \) th variable. The penalty term becomes
\[
\lambda \sum_{j=1}^p \boldsymbol{v_j} P_\alpha(\beta_j) = \lambda \sum_{j=1}^p \boldsymbol{v_j} \left[ (1-\alpha)\frac{1}{2} \beta_j^2 + \alpha |\beta_j| \right].
\]
Note the penalty factors are internally rescaled to sum to nvars.

This is very useful when people have prior knowledge or preference over the variables. In many cases, some variables may be so important that one wants to keep them all the time, which can be achieved by setting corresponding penalty factors to 0:

```
p.fac = rep(1, 20)
p.fac[c(5, 10, 15)] = 0
pfit = glmnet(x, y, penalty.factor = p.fac)
plot(pfit, label = TRUE)
```

We see from the labels that the three variables with 0 penalty factors always stay in the model, while the others follow typical regularization paths and shrunken to 0 eventually.

Some other useful arguments. `exclude`

allows one to block certain variables from being the model at all. Of course, one could simply subset these out of `x`

, but sometimes `exclude`

is more useful, since it returns a full vector of coefficients, just with the excluded ones set to zero. There is also an `intercept`

argument which defaults to `TRUE`

; if `FALSE`

the intercept is forced to be zero.

The multiresponse Gaussian family is obtained using `family = "mgaussian"`

option in `glmnet`

. It is very similar to the single-response case above. This is useful when there are a number of (correlated) responses - the so-called “multi-task learning” problem. Here the sharing involves which variables are selected, since when a variable is selected, a coefficient is fit for each response. Most of the options are the same, so we focus here on the differences with the single response model.

Obviously, as the name suggests, \( y \) is not a vector, but a matrix of quantitative responses in this section. The coefficients at each value of lambda are also a matrix as a result.

Here we solve the following problem: \[ \min_{(\beta_0, \beta) \in \mathbb{R}^{(p+1)\times K}}\frac{1}{2N} \sum_{i=1}^N ||y_i -\beta_0-\beta^T x_i||^2_F+\lambda \left[ (1-\alpha)||\beta||_F^2/2 + \alpha\sum_{j=1}^p||\beta_j||_2\right]. \] Here \( \beta_j \) is the jth row of the \( p\times K \) coefficient matrix \( \beta \), and we replace the absolute penalty on each single coefficient by a group-lasso penalty on each coefficient K-vector \( \beta_j \) for a single predictor \( x_j \).

We use a set of data generated beforehand for illustration.

```
load("MGExample.RData")
```

We fit the data, with an object “mfit” returned.

```
mfit = glmnet(x, y, family = "mgaussian")
```

For multiresponse Gaussian, the options in `glmnet`

are almost the same as the single-response case, such as `alpha`

, `weights`

, `nlambda`

, `standardize`

. A exception to be noticed is that `standardize.response`

is only for `mgaussian`

family. The default value is `FALSE`

. If `standardize.response = TRUE`

, it standardizes the response variables.

To visualize the coefficients, we use the `plot`

function.

```
plot(mfit, xvar = "lambda", label = TRUE, type.coef = "2norm")
```

Note that we set `type.coef = "2norm"`

. Under this setting, a single curve is plotted per variable, with value equal to the \( \ell_2 \) norm. The default setting is `type.coef = "coef"`

, where a coefficient plot is created for each response (multiple figures).

`xvar`

and `label`

are two other options besides ordinary graphical parameters. They are the same as the single-response case.

We can extract the coefficients at requested values of \( \lambda \) by using the function `coef`

and make predictions by `predict`

. The usage is similar and we only provide an example of `predict`

here.

```
predict(mfit, newx = x[1:5, ], s = c(0.1, 0.01))
```

```
## , , 1
##
## y1 y2 y3 y4
## [1,] -4.7113 -1.1654 0.6012 3.741
## [2,] 4.1221 -3.0527 -1.2120 4.965
## [3,] 3.1589 -0.5758 0.2638 2.051
## [4,] 0.6443 2.1166 -0.2240 3.147
## [5,] -1.1727 0.1044 -7.3316 3.250
##
## , , 2
##
## y1 y2 y3 y4
## [1,] -4.6413 -1.2287 0.6121 3.779
## [2,] 4.4721 -3.2528 -1.2573 5.266
## [3,] 3.4735 -0.6929 0.4681 2.056
## [4,] 0.7355 2.2969 -0.2191 2.989
## [5,] -1.2767 0.2893 -7.8262 3.205
```

The prediction result is saved in a three-dimensional array with the first two dimensions being the prediction matrix for each response variable and the third indicating the response variables.

We can also do k-fold cross-validation. The options are almost the same as the ordinary Gaussian family and we do not expand here.

```
cvmfit = cv.glmnet(x, y, family = "mgaussian")
```

We plot the resulting `cv.glmnet`

object “cvmfit”.

```
plot(cvmfit)
```

To show explicitly the selected optimal values of \( \lambda \), type

```
cvmfit$lambda.min
```

```
## [1] 0.03928
```

```
cvmfit$lambda.1se
```

```
## [1] 0.12
```

As before, the first one is the value at which the minimal mean squared error is achieved and the second is for the most regularized model whose mean squared error is within one standard error of the minimal.

Prediction for `cv.glmnet`

object works almost the same as for `glmnet`

object. We omit the details here.

Logistic regression is another widely-used model when the response is categorical. If there are two possible outcomes, we use the binomial distribution, else we use the multinomial.

For the binomial model, suppose the response variable takes value in \( \mathcal{G}=\{1,2\} \). Denote \( y_i = I(g_i=1) \). We model \[ \mbox{Pr}(G=2|X=x)+\frac{e^{\beta_0+\beta^Tx}}{1+e^{\beta_0+\beta^Tx}}, \] which can be written in the following form \[ \log\frac{\mbox{Pr}(G=2|X=x)}{\mbox{Pr}(G=1|X=x)}=\beta_0+\beta^Tx, \] the so-called “logistic” or log-odds transformation.

The objective function for the penalized logistic regression uses the negative binomial log-likelihood, and is \[ \min_{(\beta_0, \beta) \in \mathbb{R}^{p+1}} -\left[\frac{1}{N} \sum_{i=1}^N y_i \cdot (\beta_0 + x_i^T \beta) - \log (1+e^{(\beta_0+x_i^T \beta)})\right] + \lambda \big[ (1-\alpha)||\beta||_2^2/2 + \alpha||\beta||_1\big]. \] Logistic regression is often plagued with degeneracies when \( p > N \) and exhibits wild behavior even when \( N \) is close to \( p \); the elastic-net penalty alleviates these issues, and regularizes and selects variables as well.

Our algorithm uses a quadratic approximation to the log-likelihood, and then coordinate descent on the resulting penalized weighted least-squares problem. These constitute an outer and inner loop.

For illustration purpose, we load pre-generated input matrix `x`

and the response vector `y`

from the data file.

```
load("BNExample.RData")
```

The input matrix \( x \) is the same as other families. For binomial logistic regression, the response variable \( y \) should be either a factor with two levels, or a two-column matrix of counts or proportions.

Other optional arguments of `glmnet`

for binomial regression are almost same as those for Gaussian family. Don't forget to set `family`

option to “binomial”.

```
fit = glmnet(x, y, family = "binomial")
```

Like before, we can print and plot the fitted object, extract the coefficients at specific \( \lambda \)'s and also make predictions. For plotting, the optional arguments such as `xvar`

and `label`

are similar to the Gaussian. We plot against the deviance explained and show the labels.

```
plot(fit, xvar = "dev", label = TRUE)
```

Prediction is a little different for logistic from Gaussian, mainly in the option `type`

. “link” and “response” are never equivalent and “class” is only available for logistic regression. In summary,

“link” gives the linear predictors

“response” gives the fitted probabilities

“class” produces the class label corresponding to the maximum probability.

“coefficients” computes the coefficients at values of

`s`

“nonzero” retuns a list of the indices of the nonzero coefficients for each value of

`s`

.

For “binomial” models, results (“link”, “response”, “coefficients”, “nonzero”) are returned only for the class corresponding to the second level of the factor response.

In the following example, we make prediction of the class labels at \( \lambda = 0.05, 0.01 \).

```
predict(fit, newx = x[1:5, ], type = "class", s = c(0.05, 0.01))
```

```
## 1 2
## [1,] "0" "0"
## [2,] "1" "1"
## [3,] "1" "1"
## [4,] "0" "0"
## [5,] "1" "1"
```

For logistic regression, `cv.glmnet`

has similar arguments and usage as Gaussian. `nfolds`

, `weights`

, `lambda`

, `parallel`

are all available to users. There are some differences in `type.measure`

: “deviance” and “mse” do not both mean squared loss and “class” is enabled. Hence,

“mse” uses squared loss.

“deviance” uses actual deviance.

“mae” uses mean absolute error.

“class” gives misclassification error.

“auc” (for two-class logistic regression ONLY) gives area under the ROC curve.

For example,

```
cvfit = cv.glmnet(x, y, family = "binomial", type.measure = "class")
```

It uses misclassification error as the criterion for 10-fold cross-validation.

We plot the object and show the optimal values of \( \lambda \).

```
plot(cvfit)
```

```
cvfit$lambda.min
```

```
## [1] 0.02141
```

```
cvfit$lambda.1se
```

```
## [1] 0.03106
```

`coef`

and `predict`

are simliar to the Gaussian case and we omit the details. We review by some examples.

```
coef(cvfit, s = "lambda.min")
```

```
## 31 x 1 sparse Matrix of class "dgCMatrix"
## 1
## (Intercept) 0.23891
## V1 .
## V2 0.52699
## V3 -0.43796
## V4 -0.98637
## V5 -0.13713
## V6 -0.78219
## V7 .
## V8 -0.44163
## V9 0.60519
## V10 -1.19558
## V11 -0.02544
## V12 -0.01992
## V13 .
## V14 .
## V15 .
## V16 0.22011
## V17 .
## V18 .
## V19 .
## V20 .
## V21 .
## V22 0.17504
## V23 0.27000
## V24 .
## V25 0.53944
## V26 -0.28760
## V27 -0.04983
## V28 0.17122
## V29 -0.17311
## V30 0.02248
```

As mentioned previously, the results returned here are only for the second level of the factor response.

```
predict(cvfit, newx = x[1:10, ], s = "lambda.min", type = "class")
```

```
## 1
## [1,] "0"
## [2,] "1"
## [3,] "1"
## [4,] "0"
## [5,] "1"
## [6,] "0"
## [7,] "0"
## [8,] "0"
## [9,] "1"
## [10,] "1"
```

Like other GLMs, glmnet allows for an “offset”. This is a fixed vector of N numbers that is added into the linear predictor. For example, you may have fitted some other logistic regression using other variables (and data), and now you want to see if the present variables can add anything. So you use the predicted logit from the other model as an offset in.

For the multinomial model, suppose the response variable has \( K \) levels \( {\cal G}=\{1,2,\ldots,K\} \). Here we model \[ \mbox{Pr}(G=k|X=x)=\frac{e^{\beta_{0k}+\beta_k^Tx}}{\sum_{\ell=1}^Ke^{\beta_{0\ell}+\beta_\ell^Tx}}. \]

Let \( {Y} \) be the \( N \times K \) indicator response matrix, with elements \( y_{i\ell} = I(g_i=\ell) \). Then the elastic-net penalized negative log-likelihood function becomes \[ \ell(\{\beta_{0k},\beta_{k}\}_1^K) = -\left[\frac{1}{N} \sum_{i=1}^N \Big(\sum_{k=1}^Ky_{il} (\beta_{0k} + x_i^T \beta_k)- \log \big(\sum_{k=1}^K e^{\beta_{0k}+x_i^T \beta_k}\big)\Big)\right] +\lambda \left[ (1-\alpha)||\beta||_F^2/2 + \alpha\sum_{j=1}^p||\beta_j||_q\right]. \] Here we really abuse notation! \( \beta \) is a \( p\times K \) matrix of coefficients. \( \beta_k \) refers to the kth column (for outcome category k), and \( \beta_j \) the jth row (vector of K coefficients for variable j). The last penalty term is \( ||\beta_j||_q \), we have two options for q: \( q\in \{1,2\} \). When q=1, this is a lasso penalty on each of the parameters. When q=2, this is a grouped-lasso penalty on all the K coefficients for a particular variables, which makes them all be zero or nonzero together.

The standard Newton algorithm can be tedious here. Instead, we use a so-called partial Newton algorithm by making a partial quadratic approximation to the log-likelihood, allowing only \( (\beta_{0k}, \beta_k) \) to vary for a single class at a time. For each value of \( \lambda \), we first cycle over all classes indexed by \( k \), computing each time a partial quadratic approximation about the parameters of the current class. Then the inner procedure is almost the same as for the binomial case. This is the case for lasso (q=1). When q=2, we use a different approach, which we wont dwell on here.

For the multinomial case, the usage is similar to logistic regression, and we mainly illustrate by examples and address any differences. We load a set of generated data.

```
load("MNExample.RData")
```

The optional arguments in `glmnet`

for multinomial logistic regression are mostly similar to binomial regression except for a few cases.

The response variable can be a `nc >= 2`

level factor, or a `nc`

-column matrix of counts or proportions.
Internally glmnet will make the rows of this matrix sum to 1, and absorb the total mass into the weight for that observation.

`offset`

should be a `nobs x nc`

matrix if there is one.

A special option for multinomial regression is `type.multinomial`

, which allows the usage of a grouped lasso penalty if `type.multinomial = "grouped"`

. This will ensure that the multinomial coefficients for a variable are all in or out together, just like for the multi-response Gaussian.

```
fit = glmnet(x, y, family = "multinomial", type.multinomial = "grouped")
```

We plot the resulting object “fit”.

```
plot(fit, xvar = "lambda", label = TRUE, type.coef = "2norm")
```

The options are `xvar`

, `label`

and `type.coef`

, in addition to other ordinary graphical parameters.

`xvar`

and `label`

are the same as other families while `type.coef`

is only for multinomial regression and multiresponse Gaussian model. It can produce a figure of coefficients for each response variable if `type.coef = "coef"`

or a figure showing the \( \ell_2 \)-norm in one figure if `type.coef = "2norm"`

We can also do cross-validation and plot the returned object.

```
cvfit = cv.glmnet(x, y, family = "multinomial", type.multinomial = "grouped",
parallel = TRUE)
plot(cvfit)
```

Note that although `type.multinomial`

is not a typical argument in `cv.glmnet`

, in fact any argument that can be passed to `glmnet`

is valid in the argument list of `cv.glmnet`

. We also use parallel computing to accelerate the calculation.

Users may wish to predict at the optimally selected \( \lambda \):

```
predict(cvfit, newx = x[1:10, ], s = "lambda.min", type = "class")
```

```
## 1
## [1,] "3"
## [2,] "2"
## [3,] "2"
## [4,] "3"
## [5,] "1"
## [6,] "3"
## [7,] "3"
## [8,] "1"
## [9,] "1"
## [10,] "2"
```

Poisson regression is used to model count data under the assumption of Poisson error, or otherwise non-negative data where the mean and variance are proportional. Like the Gaussian and binomial model, the Poisson is a member of the exponential family of distributions. We usually model its positive mean on the log scale: \( \log \mu(x) = \beta_0+\beta' x \).

The log-likelihood for observations \( \{x_i,y_i\}_1^N \) is given my
\[
l(\beta|X, Y) = \sum_{i=1}^N (y_i (\beta_0+\beta' x_i) - e^{\beta_0+\beta^Tx_i}.
\]
As before, we optimize the penalized log-lielihood:
\[
\min_{\beta_0,\beta} -\frac1N l(\beta|X, Y) + \lambda \left((1-\alpha) \sum_{i=1}^N \beta_i^2/2) +\alpha \sum_{i=1}^N |\beta_i|\right).
\]

Glmnet uses an outer Newton loop, and an inner weighted least-squares loop (as in logistic regression) to optimize this criterion.

First, we load a pre-generated set of Poisson data.

```
load("POExample.RData")
```

We apply the function `glmnet`

with the `"poisson"`

option.

```
fit = glmnet(x, y, family = "poisson")
```

The optional input arguments of `glmnet`

for `"poisson"`

family are similar to those for others.

`offset`

is a useful argument particularly in Poisson models.

When dealing with rate data in Poisson models, the counts collected are often based on different exposures, such as length of time observed, area and years. A poisson rate \( \mu(x) \) is relative to a unit exposure time, so if an observation \( y_i \) was exposed for \( E_i \) units of time, then the expected count would be \( E_i\mu(x) \), and the log mean would be \( \log(E_i)+\log(\mu(x) \))$. In a case like this, we would supply an *offset* \( \log(E_i) \) for each observation.
Hence `offset`

is a vector of length `nobs`

that is included in the linear predictor. Other families can also use options, typically for different reasons.

(Warning: if `offset`

is supplied in `glmnet`

, offsets must also also be supplied to `predict`

to make reasonable predictions.)

Again, we plot the coefficients to have a first sense of the result.

```
plot(fit)
```

Like before, we can extract the coefficients and make predictions at certain \( \lambda \)'s by using `coef`

and `predict`

respectively. The optional input arguments are similar to those for other families. In function `predict`

, the option `type`

, which is the type of prediction required, has its own specialties for Poisson family. That is,

- “link” (default) gives the linear predictors like others
- “response” gives the fitted mean
- “coefficients” computes the coefficients at the requested values for
`s`

, which can also be realized by`coef`

function - “nonzero” returns a a list of the indices of the nonzero coefficients for each value of
`s`

.

For example, we can do as follows.

```
coef(fit, s = 1)
```

```
## 21 x 1 sparse Matrix of class "dgCMatrix"
## 1
## (Intercept) 0.61123
## V1 0.45820
## V2 -0.77061
## V3 1.34015
## V4 0.04350
## V5 -0.20326
## V6 .
## V7 .
## V8 .
## V9 .
## V10 .
## V11 .
## V12 0.01816
## V13 .
## V14 .
## V15 .
## V16 .
## V17 .
## V18 .
## V19 .
## V20 .
```

```
predict(fit, newx = x[1:5, ], type = "response", s = c(0.1, 1))
```

```
## 1 2
## [1,] 2.4946 4.4398
## [2,] 10.3512 11.0354
## [3,] 0.1179 0.1785
## [4,] 0.9728 1.6720
## [5,] 1.1152 1.9893
```

We may also use cross-validation to find the optimal \( \lambda \)'s and thus make inferences.

```
cvfit = cv.glmnet(x, y, family = "poisson")
```

Options are almost the same as the Gaussian family except that for `type.measure`

,

- “deviance” (default) gives the deviance
- “mse” stands for mean squared error
- “mae” is for mean absolute error.

We can plot the `cv.glmnet`

object.

```
plot(cvfit)
```

We can also show the optimal \( \lambda \)'s and the corresponding coefficients.

```
opt.lam = c(cvfit$lambda.min, cvfit$lambda.1se)
coef(cvfit, s = opt.lam)
```

```
## 21 x 2 sparse Matrix of class "dgCMatrix"
## 1 2
## (Intercept) 0.031263 0.17272
## V1 0.619053 0.57860
## V2 -0.984550 -0.93667
## V3 1.525234 1.47429
## V4 0.231591 0.20129
## V5 -0.336659 -0.30754
## V6 0.001026 .
## V7 -0.012830 .
## V8 . .
## V9 . .
## V10 0.015983 .
## V11 . .
## V12 0.030867 0.02591
## V13 -0.027971 .
## V14 0.032750 .
## V15 -0.005933 .
## V16 0.017506 .
## V17 . .
## V18 0.004026 .
## V19 -0.033579 .
## V20 0.012049 0.01038
```

The `predict`

method is similar and we do not repeat it here.

The Cox proportional hazards model is commonly used for the study of the relationship beteween predictor variables and survival time. In the usual survival analysis framework, we have data of the form \( (y_1, x_1, \delta_1), \ldots, (y_n, x_n, \delta_n) \) where \( y_i \), the observed time, is a time of failure if \( \delta_i \) is 1 or right-censoring if \( \delta_i \) is 0. We also let \( t_1 < t_2 < \ldots < t_m \) be the increasing list of unique failure times, and \( j(i) \) denote the index of the observation failing at time \( t_i \).

The Cox model assumes a semi-parametric form for the hazard \[ h_i(t) = h_0(t) e^{x_i^T \beta}, \] where \( h_i(t) \) is the hazard for patient \( i \) at time \( t \), \( h_0(t) \) is a shared baseline hazard, and \( \beta \) is a fixed, length \( p \) vector. In the classic setting \( n \geq p \), inference is made via the partial likelihood \[ L(\beta) = \prod_{i=1}^m \frac{e^{x_{j(i)}^T \beta}}{\sum_{j \in R_i} e^{x_j^T \beta}}, \] where \( R_i \) is the set of indices \( j \) with \( y_j \geq t_i \) (those at risk at time \( t_i \)).

Note there is no intercept in the Cox mode (its built into the baseline hazard, and like it, would cancel in the partial likelihood.)

We penalize the negative log of the partial likelihood, just like the other models, with an elastic-net penalty.

We use a pre-generated set of sample data and response. Users can load their own data and follow a similar procedure. In this case \( x \) must be an \( n\times p \) matrix of covariate values â€” each row corresponds to a patient and each column a covariate. \( y \) is an \( n \times 2 \) matrix, with a column “time” of failure/censoring times, and “status” a 0/1 indicator, with 1 meaning the time is a failure time, and zero a censoring time.

```
load("CXExample.RData")
y[1:5, ]
```

```
## time status
## [1,] 1.76878 1
## [2,] 0.54528 1
## [3,] 0.04486 0
## [4,] 0.85032 0
## [5,] 0.61488 1
```

The `Surv`

function in the package `survival`

can create such a matrix. Note, however, that the `coxph`

and related linear models can handle interval and other fors of censoring, while glmnet can only handle right censoring in its present form.

We apply the `glmnet`

function to compute the solution path under default settings.

```
fit = glmnet(x, y, family = "cox")
```

All the standard options are available such as `alpha`

, `weights`

, `nlambda`

and `standardize`

. Their usage is similar as in the Gaussian case and we omit the details here. Users can also refer to the help file `help(glmnet)`

.

We can plot the coefficients.

```
plot(fit)
```

As before, we can extract the coefficients at certain values of \( \lambda \).

```
coef(fit, s = 0.05)
```

```
## 30 x 1 sparse Matrix of class "dgCMatrix"
## 1
## V1 0.37694
## V2 -0.09548
## V3 -0.13596
## V4 0.09814
## V5 -0.11438
## V6 -0.38899
## V7 0.24291
## V8 0.03648
## V9 0.34740
## V10 0.03865
## V11 .
## V12 .
## V13 .
## V14 .
## V15 .
## V16 .
## V17 .
## V18 .
## V19 .
## V20 .
## V21 .
## V22 .
## V23 .
## V24 .
## V25 .
## V26 .
## V27 .
## V28 .
## V29 .
## V30 .
```

Since the Cox Model is not commonly used for prediction, we do not give an illustrative example on prediction. If needed, users can refer to the help file by typing `help(predict.glmnet)`

.

Also, the function `cv.glmnet`

can be used to compute \( k \)-fold cross-validation for the Cox model. The usage is similar to that for other families except for two main differences.

One is that `type.measure`

only supports “deviance”(also default), which gives the partial-likelihood.

The other is in the option `grouped`

. `grouped = TRUE`

obtains the CV partial likelihood for the Kth fold by subtraction; by subtracting the log partial likelihood evaluated on the full dataset from that evaluated on the on the (K-1)/K dataset. This makes more efficient use of risk sets. With `grouped=FALSE`

the log partial likelihood is computed only on the Kth fold, which is only reasonable if each fold has a large number of observations.

```
cvfit = cv.glmnet(x, y, family = "cox")
```

Once fit, we can view the optimal \( \lambda \) value and a cross validated error plot to help evaluate our model.

```
plot(cvfit)
```

As previously, the left vertical line in our plot shows us where the CV-error curve hits its minimum. The right vertical line shows us the most regularized model with CV-error within 1 standard deviation of the minimum. We also extract such optimal \( \lambda \)'s.

```
cvfit$lambda.min
```

```
## [1] 0.0175
```

```
cvfit$lambda.1se
```

```
## [1] 0.05344
```

We can check the active covariates in our model and see their coefficients.

```
coef.min = coef(cvfit, s = "lambda.min")
active.min = which(coef.min != 0)
index.min = coef.min[active.min]
```

```
index.min
```

```
## [1] 0.4858932 -0.1709845 -0.2146783 0.1715902 -0.1832270 -0.4857205
## [7] 0.3308570 0.0892416 0.4455480 0.1124757 0.0153665 -0.0162443
## [13] -0.0006241 -0.0209230 -0.0057843
```

```
coef.min
```

```
## 30 x 1 sparse Matrix of class "dgCMatrix"
## 1
## V1 0.4858932
## V2 -0.1709845
## V3 -0.2146783
## V4 0.1715902
## V5 -0.1832270
## V6 -0.4857205
## V7 0.3308570
## V8 0.0892416
## V9 0.4455480
## V10 0.1124757
## V11 .
## V12 .
## V13 0.0153665
## V14 .
## V15 .
## V16 .
## V17 -0.0162443
## V18 .
## V19 .
## V20 .
## V21 -0.0006241
## V22 .
## V23 .
## V24 .
## V25 -0.0209230
## V26 .
## V27 .
## V28 .
## V29 .
## V30 -0.0057843
```

Our package supports sparse input matrices, which allow efficient storage and operations of large matrices but with only a few nonzero entries. It is available for all families except for the `cox`

family. The usage of sparse matrices (inherit from class `"sparseMatrix"`

as in package `Matrix`

) in `glmnet`

is the same as if a regular matrix is provided.

We load a set of sample data created beforehand.

```
load("SXExample.RData")
```

It loads `x`

, a 100*20 sparse input matrix and `y`

, the response vector.

```
class(x)
```

```
## [1] "dgCMatrix"
## attr(,"package")
## [1] "Matrix"
```

Users can create a sparse matrix with the function `sparseMatrix`

by providing the locations and values of the nonzero entries. Alternatively, `Matrix`

function can also be used to contruct a sparse matrix by setting `sparse = TRUE`

, but this defeats the purpose somewhat.

We can fit the model the same way as before.

```
fit = glmnet(x, y)
```

We also do the cross-validation and plot the resulting object.

```
cvfit = cv.glmnet(x, y)
plot(cvfit)
```

The usage of other functions are similar and we do not expand here.

Note that sparse matrices can also be used for `newx`

, the new input matrix in the `predict`

function. For example,

```
i = sample(1:5, size = 25, replace = TRUE)
j = sample(1:20, size = 25, replace = TRUE)
x = rnorm(25)
nx = sparseMatrix(i = i, j = j, x = x, dims = c(5, 20))
predict(cvfit, newx = nx, s = "lambda.min")
```

```
## 1
## [1,] 0.4260
## [2,] 0.2161
## [3,] 0.2501
## [4,] -1.6554
## [5,] -0.8776
```

Our package has a set of internal parameters which control some aspects of the computation of the path. The *factory default* settings are expected to serve in most cases, and users do not need to make changes unless there are special requirements.

There are several parameters that users can change:

`fdev`

- minimum fractional change in deviance for stopping path; factory default = 1.0e-5

`devmax`

- maximum fraction of explained deviance for stopping path; factory default = 0.999

`eps`

- minimum value of lambda.min.ratio (see glmnet); factory default= 1.0e-6`big`

- large floating point number; factory default = 9.9e35. Inf in definition of upper.limit is set to big`mnlam`

- minimum number of path points (lambda values) allowed; factory default = 5`pmin`

- minimum null probability for any class; factory default = 1.0e-5`exmx`

- maximum allowed exponent; factory default = 250.0`prec`

- convergence threshold for multi-response bounds adjustment solution; factory default = 1.0e-10`mxit`

- maximum iterations for multiresponse bounds adjustment solution; factory default = 100`factory`

- If`TRUE`

, reset all the parameters to the factory default; default is`FALSE`

We illustrate the usage by an example. Note that any changes made hold for the duration of the R session, or unless they are changed by the user with a subsequent call to `glmnet.control`

.

```
load("QSExample.RData")
fit = glmnet(x, y)
print(fit)
```

```
##
## Call: glmnet(x = x, y = y)
##
## Df %Dev Lambda
## [1,] 0 0.0000 1.63000
## [2,] 2 0.0553 1.49000
## [3,] 2 0.1460 1.35000
## [4,] 2 0.2210 1.23000
## [5,] 2 0.2840 1.12000
## [6,] 2 0.3350 1.02000
## [7,] 4 0.3900 0.93300
## [8,] 5 0.4560 0.85000
## [9,] 5 0.5150 0.77500
## [10,] 6 0.5740 0.70600
## [11,] 6 0.6260 0.64300
## [12,] 6 0.6690 0.58600
## [13,] 6 0.7050 0.53400
## [14,] 6 0.7340 0.48700
## [15,] 7 0.7620 0.44300
## [16,] 7 0.7860 0.40400
## [17,] 7 0.8050 0.36800
## [18,] 7 0.8220 0.33500
## [19,] 7 0.8350 0.30600
## [20,] 7 0.8460 0.27800
## [21,] 7 0.8560 0.25400
## [22,] 7 0.8630 0.23100
## [23,] 8 0.8710 0.21100
## [24,] 8 0.8770 0.19200
## [25,] 8 0.8820 0.17500
## [26,] 8 0.8860 0.15900
## [27,] 8 0.8900 0.14500
## [28,] 8 0.8930 0.13200
## [29,] 8 0.8960 0.12100
## [30,] 8 0.8980 0.11000
## [31,] 9 0.8990 0.10000
## [32,] 9 0.9010 0.09120
## [33,] 9 0.9020 0.08310
## [34,] 9 0.9030 0.07570
## [35,] 10 0.9040 0.06900
## [36,] 11 0.9050 0.06280
## [37,] 11 0.9060 0.05730
## [38,] 12 0.9070 0.05220
## [39,] 15 0.9080 0.04750
## [40,] 16 0.9090 0.04330
## [41,] 16 0.9090 0.03950
## [42,] 16 0.9100 0.03600
## [43,] 17 0.9100 0.03280
## [44,] 17 0.9110 0.02990
## [45,] 18 0.9110 0.02720
## [46,] 18 0.9110 0.02480
## [47,] 19 0.9120 0.02260
## [48,] 19 0.9120 0.02060
## [49,] 19 0.9120 0.01870
## [50,] 19 0.9120 0.01710
## [51,] 19 0.9130 0.01560
## [52,] 19 0.9130 0.01420
## [53,] 19 0.9130 0.01290
## [54,] 19 0.9130 0.01180
## [55,] 19 0.9130 0.01070
## [56,] 19 0.9130 0.00978
## [57,] 19 0.9130 0.00891
## [58,] 19 0.9130 0.00812
## [59,] 19 0.9130 0.00740
## [60,] 19 0.9130 0.00674
## [61,] 19 0.9130 0.00614
## [62,] 20 0.9130 0.00559
## [63,] 20 0.9130 0.00510
## [64,] 20 0.9130 0.00464
## [65,] 20 0.9130 0.00423
## [66,] 20 0.9130 0.00386
## [67,] 20 0.9130 0.00351
```

We can change the minimum fractional change in deviance for stopping path and compare the results.

```
glmnet.control(fdev = 0)
fit = glmnet(x, y)
print(fit)
```

```
##
## Call: glmnet(x = x, y = y)
##
## Df %Dev Lambda
## [1,] 0 0.0000 1.630000
## [2,] 2 0.0553 1.490000
## [3,] 2 0.1460 1.350000
## [4,] 2 0.2210 1.230000
## [5,] 2 0.2840 1.120000
## [6,] 2 0.3350 1.020000
## [7,] 4 0.3900 0.933000
## [8,] 5 0.4560 0.850000
## [9,] 5 0.5150 0.775000
## [10,] 6 0.5740 0.706000
## [11,] 6 0.6260 0.643000
## [12,] 6 0.6690 0.586000
## [13,] 6 0.7050 0.534000
## [14,] 6 0.7340 0.487000
## [15,] 7 0.7620 0.443000
## [16,] 7 0.7860 0.404000
## [17,] 7 0.8050 0.368000
## [18,] 7 0.8220 0.335000
## [19,] 7 0.8350 0.306000
## [20,] 7 0.8460 0.278000
## [21,] 7 0.8560 0.254000
## [22,] 7 0.8630 0.231000
## [23,] 8 0.8710 0.211000
## [24,] 8 0.8770 0.192000
## [25,] 8 0.8820 0.175000
## [26,] 8 0.8860 0.159000
## [27,] 8 0.8900 0.145000
## [28,] 8 0.8930 0.132000
## [29,] 8 0.8960 0.121000
## [30,] 8 0.8980 0.110000
## [31,] 9 0.8990 0.100000
## [32,] 9 0.9010 0.091200
## [33,] 9 0.9020 0.083100
## [34,] 9 0.9030 0.075700
## [35,] 10 0.9040 0.069000
## [36,] 11 0.9050 0.062800
## [37,] 11 0.9060 0.057300
## [38,] 12 0.9070 0.052200
## [39,] 15 0.9080 0.047500
## [40,] 16 0.9090 0.043300
## [41,] 16 0.9090 0.039500
## [42,] 16 0.9100 0.036000
## [43,] 17 0.9100 0.032800
## [44,] 17 0.9110 0.029900
## [45,] 18 0.9110 0.027200
## [46,] 18 0.9110 0.024800
## [47,] 19 0.9120 0.022600
## [48,] 19 0.9120 0.020600
## [49,] 19 0.9120 0.018700
## [50,] 19 0.9120 0.017100
## [51,] 19 0.9130 0.015600
## [52,] 19 0.9130 0.014200
## [53,] 19 0.9130 0.012900
## [54,] 19 0.9130 0.011800
## [55,] 19 0.9130 0.010700
## [56,] 19 0.9130 0.009780
## [57,] 19 0.9130 0.008910
## [58,] 19 0.9130 0.008120
## [59,] 19 0.9130 0.007400
## [60,] 19 0.9130 0.006740
## [61,] 19 0.9130 0.006140
## [62,] 20 0.9130 0.005590
## [63,] 20 0.9130 0.005100
## [64,] 20 0.9130 0.004640
## [65,] 20 0.9130 0.004230
## [66,] 20 0.9130 0.003860
## [67,] 20 0.9130 0.003510
## [68,] 20 0.9130 0.003200
## [69,] 20 0.9130 0.002920
## [70,] 20 0.9130 0.002660
## [71,] 20 0.9130 0.002420
## [72,] 20 0.9130 0.002210
## [73,] 20 0.9130 0.002010
## [74,] 20 0.9130 0.001830
## [75,] 20 0.9130 0.001670
## [76,] 20 0.9130 0.001520
## [77,] 20 0.9130 0.001390
## [78,] 20 0.9130 0.001260
## [79,] 20 0.9130 0.001150
## [80,] 20 0.9130 0.001050
## [81,] 20 0.9130 0.000955
## [82,] 20 0.9130 0.000870
## [83,] 20 0.9130 0.000793
## [84,] 20 0.9130 0.000723
## [85,] 20 0.9130 0.000658
## [86,] 20 0.9130 0.000600
## [87,] 20 0.9130 0.000547
## [88,] 20 0.9130 0.000498
## [89,] 20 0.9130 0.000454
## [90,] 20 0.9130 0.000413
## [91,] 20 0.9130 0.000377
## [92,] 20 0.9130 0.000343
## [93,] 20 0.9130 0.000313
## [94,] 20 0.9130 0.000285
## [95,] 20 0.9130 0.000260
## [96,] 20 0.9130 0.000237
## [97,] 20 0.9130 0.000216
## [98,] 20 0.9130 0.000196
## [99,] 20 0.9130 0.000179
## [100,] 20 0.9130 0.000163
```

We set `fdev = 0`

to continue all along the path, even without much change. The length of the sequence becomes 100, which is the default of `nlambda`

.

Users can also reset to the default settings.

```
glmnet.control(factory = TRUE)
```

The current settings are obtained as follows.

```
glmnet.control()
```

```
## $fdev
## [1] 1e-05
##
## $eps
## [1] 1e-06
##
## $big
## [1] 9.9e+35
##
## $mnlam
## [1] 5
##
## $devmax
## [1] 0.999
##
## $pmin
## [1] 1e-05
##
## $exmx
## [1] 250
##
## $prec
## [1] 1e-10
##
## $mxit
## [1] 100
```

Jerome Friedman, Trevor Hastie and Rob Tibshirani. (2008).

Regularization Paths for Generalized Linear Models via Coordinate Descent

*Journal of Statistical Software*, Vol. 33(1), 1-22 Feb 2010.

Noah Simon, Jerome Friedman, Trevor Hastie and Rob Tibshirani. (2011).

Regularization Paths for Cox’s Proportional Hazards Model via Coordinate Descent

*Journal of Statistical Software*, Vol. 39(5) 1-13.

Robert Tibshirani, Jacob Bien, Jerome Friedman, Trevor Hastie, Noah Simon, Jonathan Taylor, Ryan J. Tibshirani. (2010).

Strong Rules for Discarding Predictors in Lasso-type Problems

*Journal of the Royal Statistical Society: Series B (Statistical Methodology)*, 74(2), 245-266.

Noah Simon, Jerome Friedman and Trevor Hastie (2013).

A Blockwise Descent Algorithm for Group-penalized Multiresponse and Multinomial Regression

*(in arXiv, submitted) *