The 'cito' package provides a user-friendly interface for training and interpreting deep neural networks (DNN). 'cito' simplifies the fitting of DNNs by supporting the familiar formula syntax, hyperparameter tuning under cross-validation, and helps to detect and handle convergence problems. DNNs can be trained on CPU, GPU and MacOS GPUs. In addition, 'cito' has many downstream functionalities such as various explainable AI (xAI) metrics (e.g. variable importance, partial dependence plots, accumulated local effect plots, and effect estimates) to interpret trained DNNs. 'cito' optionally provides confidence intervals (and p-values) for all xAI metrics and predictions. At the same time, 'cito' is computationally efficient because it is based on the deep learning framework 'torch'. The 'torch' package is native to R, so no Python installation or other API is required for this package.
The ‘cito’ package provides a user-friendly interface for training and interpreting deep neural networks (DNN). ‘cito’ simplifies the fitting of DNNs by supporting the familiar formula syntax, hyperparameter tuning under cross-validation, and helps to detect and handle convergence problems. DNNs can be trained on CPU, GPU and MacOS GPUs. In addition, ‘cito’ has many downstream functionalities such as various explainable AI (xAI) metrics (e.g. variable importance, partial dependence plots, accumulated local effect plots, and effect estimates) to interpret trained DNNs. ‘cito’ optionally provides confidence intervals (and p-values) for all xAI metrics and predictions. At the same time, ‘cito’ is computationally efficient because it is based on the deep learning framework ‘torch’. The ‘torch’ package is native to R, so no Python installation or other API is required for this package.
Before installing ‘cito’ make sure ‘torch’ is installed. See the code chunk below if you are unsure on how to check this
# check package
if(!require('torch',quietly = TRUE)) install.packages('torch')
library('torch')
#install torch
if(!torch_is_installed()) install_torch()
If you have trouble installing ‘torch’, please visit the website of the ‘torch’ package or create an issue on our github website. We are happy to help you.
A stable version of cito from CRAN can be installed with:
install.packages("cito")
The development version from GitHub can be installed by:
if(!require('devtools', quietly = TRUE)) install.packages('devtools')
devtools::install_github('citoverse/cito')
Once installed, the main function dnn() can be used. See the example
below. A more in depth explanation can be found in the vignettes or
here under articles.
library(cito)
nn.fit <- dnn(Sepal.Length~., data = datasets::iris, bootstrap = 30L)
analyze_training(nn.fit)
# At 1st glance, the networks converged since the loss is lower than the baseline loss and the training loss is on a plateau at the end of the training.
plot(nn.fit, plot_type = "arch") draws the
architecture)plot(nn.fit)

summary function:summary(nn.fit)
## Summary of Deep Neural Network Model
##
## ── Feature Importance
## Importance Std.Err Z value Pr(>|z|)
## Sepal.Width -> 0.0468 0.0137 3.40 0.00066 ***
## Petal.Length -> 1.4363 0.3436 4.18 2.9e-05 ***
## Petal.Width -> 0.0647 0.0521 1.24 0.21376
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## ── Average Conditional Effects
## ACE Std.Err Z value Pr(>|z|)
## Sepal.Width -> 0.4828 0.0647 7.46 8.6e-14 ***
## Petal.Length -> 0.6717 0.0751 8.95 < 2e-16 ***
## Petal.Width -> -0.3021 0.1416 -2.13 0.033 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
dim(predict(nn.fit, newdata = datasets::iris))
## [1] 150 1
Certain arguments/parameters such as the architecture, activation
function, and the learning rate can be automatically tuned under
crossvalidation (for a full list, see ?dnn). Parameters that should be
tuned, can be flagged by using the function tune() instead of a
hyperparameter value:
nn.fit <- dnn(Sepal.Length~., data = datasets::iris, lr = tune(0.0001, 0.1))
## Starting hyperparameter tuning...
## Fitting final model...
nn.fit$tuning
## # A tibble: 10 × 5
## steps test train models lr
## <int> <dbl> <dbl> <lgl> <dbl>
## 1 1 Inf 0 NA 0.0333
## 2 2 28.9 0 NA 0.0136
## 3 3 Inf 0 NA 0.0867
## 4 4 Inf 0 NA 0.0690
## 5 5 Inf 0 NA 0.0173
## 6 6 Inf 0 NA 0.0487
## 7 7 Inf 0 NA 0.0229
## 8 8 Inf 0 NA 0.0938
## 9 9 Inf 0 NA 0.0924
## 10 10 Inf 0 NA 0.0748
The tuning can be configured with tuning=config_tuning(). After
tuning, a final model trained with the best hyperparameters is returned.
Hyperparameter combinations that do not achieve a loss below the
baseline loss will be aborted early and not fully cross-validated. These
runs are given a test loss of infinity.
cnn() fits convolutional networks to images (or 1D/3D arrays). The
input is an array [samples, channels, ...], a folder of jpeg/png/tiff
files, or windows cut from one large georeferenced raster with
raster_patches(). The architecture is assembled from layers with
create_architecture():
shapes <- cito:::simulate_shapes(n = 320, size = 32, channels = 3)
architecture <- create_architecture(conv(5), maxPool(), conv(5), maxPool(), linear(10))
cnn.fit <- cnn(X = shapes$data, Y = shapes$labels, architecture = architecture,
loss = "cross-entropy", optimizer = "adam", lr = 0.005, epochs = 20,
verbose = FALSE, plot = FALSE)
table(predicted = predict(cnn.fit, type = "class"), observed = shapes$labels)
## observed
## predicted ellipsoid rectangle
## ellipsoid 172 0
## rectangle 0 148
The architecture of the fitted network:
plot(cnn.fit)

mmn() combines several data streams, e.g. images and tabular
predictors, in one network. Each stream gets its own dnn() or cnn()
submodel, and a fusion network on top combines them. summary() reports
how much each stream contributes:
X_tab <- matrix(runif(320*3), 320, 3)
Y <- (as.integer(shapes$labels) - 1)*2 + 0.5*X_tab[,1] - 0.8*X_tab[,3]
mmn.fit <- mmn(Y ~ dnn(~., data = X_tab, hidden = c(50, 50)) +
cnn(X = X_img, architecture = architecture),
dataList = list(Y = Y, X_img = shapes$data, X_tab = X_tab),
loss = "mse", optimizer = "adam", lr = 0.005, epochs = 20,
verbose = FALSE, plot = FALSE)
summary(mmn.fit)
## Summary of Multi-Modal Neural Network
##
## ── Permutation importance of the data streams
## Loss increase SD Share
## dnn(~., data = X_tab, hidden = c(50, 50)) 0.1358 0.0101 0.0651
## cnn(X = X_img, architecture = architecture) 1.9493 0.1205 0.9349
##
## Baseline loss 0.0067, 10 permutations per stream. A stream that contributes little
## can come out negative by chance; compare the estimate against its SD before reading it.
plot(mmn.fit, plot_type = "arch")

We can pass custom loss functions to ‘cito’, optionally with additional parameters that should be fitted. The only requirement is that all calculations must be written using the ‘torch’ package (cito automatically converts the initial values of the custom parameters to ‘torch’ objects).
We use a multivariate normal distribution as the likelihood function and we want to parameterize/fit the covariance matrix of the multivariate normal distribution:
We need one helper function, create_cov() that builds the
covariance matrix based on a lower triangular matrix and the
diagonals (low-rank approximation of the covariance matrix)
We need our custom likelihood function which uses the
distr_multivariate_normal(…) function from the torch package:
create_cov = function(L, Diag) {
return(torch::torch_matmul(L, L$t()) + torch::torch_diag(Diag$exp()+0.001))
}
custom_loss_MVN = function(true, pred) {
Sigma = create_cov(SigmaPar, SigmaDiag)
logLik = torch::distr_multivariate_normal(pred,
covariance_matrix = Sigma)$
log_prob(true)
return(-logLik$mean())
}
nn.fit<- dnn(cbind(Sepal.Length, Sepal.Width, Petal.Length)~.,
data = datasets::iris,
lr = 0.01,
epochs = 200L,
loss = custom_loss_MVN,
verbose = FALSE,
plot = FALSE,
custom_parameters =
list(SigmaDiag = rep(0, 3), # Our parameters with starting values
SigmaPar = matrix(rnorm(6, sd = 0.001), 3, 2)) # Our parameters with starting values
)
Estimated covariance matrix:
as.matrix(create_cov(nn.fit$loss$parameters$SigmaPar,
nn.fit$loss$parameters$SigmaDiag))
## [,1] [,2] [,3]
## [1,] 0.25706124 0.05718974 0.11934890
## [2,] 0.05718974 0.11492345 0.03901247
## [3,] 0.11934890 0.03901247 0.16983800
Empirical covariance matrix:
cov(predict(nn.fit) - nn.fit$data$Y)
## Sepal.Length Sepal.Width Petal.Length
## Sepal.Length 0.21880961 0.05860395 0.11779459
## Sepal.Width 0.05860395 0.09050435 0.01886577
## Petal.Length 0.11779459 0.01886577 0.13105972