# Training non default regression models

#### Etienne Becht

#### June 2020

# Introduction

This vignette explains how to specify non-default machine learning frameworks and their hyperparameters when applying Infinity Flow. We will assume here that the basic usage of Infinity Flow has already been read, if you are not familiar with this material I suggest you first look at the basic usage vignette

This vignette will cover:

1. Loading the example data
2. Note on package design
3. The `regression_functions` argument
4. The `extra_args_regression_params` argument
5. Neural networks

# Loading the example data

Here is a single R code chunk that recapitulates all of the data preparation covered in the basic usage vignette.

    if(!require(devtools)){
        install.packages("devtools")
    }
    if(!require(infinityFlow)){
        library(devtools)
        install_github("ebecht/infinityFlow")
    }

    library(infinityFlow)

    data(steady_state_lung)
    data(steady_state_lung_annotation)
    data(steady_state_lung_backbone_specification)

    dir <- file.path(tempdir(), "infinity_flow_example")
    input_dir <- file.path(dir, "fcs")
    write.flowSet(steady_state_lung, outdir = input_dir)
    #> [1] "/var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/fcs"

    write.csv(steady_state_lung_backbone_specification, file = file.path(dir, "backbone_selection_file.csv"), row.names = FALSE)

    path_to_fcs <- file.path(dir, "fcs")
    path_to_output <- file.path(dir, "output")
    path_to_intermediary_results <- file.path(dir, "tmp")
    backbone_selection_file <- file.path(dir, "backbone_selection_file.csv")

    targets <- steady_state_lung_annotation$Infinity_target
    names(targets) <- rownames(steady_state_lung_annotation)
    isotypes <- steady_state_lung_annotation$Infinity_isotype
    names(isotypes) <- rownames(steady_state_lung_annotation)

    input_events_downsampling <- 1000
    prediction_events_downsampling <- 500
    cores = 1L

# Note on package design

The `infinity_flow()` function which encapsulates the complete Infinity Flow computational pipeline uses two arguments to respectively select regression models and their hyperparameters. These two arguments are both lists, and should have the same length. The idea is that the first list, `regression_functions` will be a list of model templates (XGBoost, Neural Networks, SVMs…) to train, while the second will be used to specify their hyperparameters. The list of templates is then fit to the data using parallel computing with socketing (using the `parallel` package through the `pbapply` package), which is more memory efficient.

# The `regression_functions` argument

This argument is a list of functions which specifies how many models to train per well and which ones. Each type of machine learning model is supported through a wrapper in the infinityFlow package, and has a name of the form `fitter_*`. See below for the complete list:

    print(grep("fitter_", ls("package:infinityFlow"), value = TRUE))
    #> [1] "fitter_glmnet"  "fitter_linear"  "fitter_nn"      "fitter_svm"
    #> [5] "fitter_xgboost"

fitter_ function | Backend | Model type
--- | --- | ---
fitter_xgboost | XGBoost | Gradient boosted trees
fitter_nn | Tensorflow/Keras | Neural networks
fitter_svm | e1071 | Support vector machines
fitter_glmnet | glmnet | Generalized linear and polynomial models
fitter_lm | stats | Linear and polynomial models

These functions rely on optional package dependencies (so that you do not need to install e.g. Keras if you are not planning to use it). We need to make sure that these dependencies are however met:

           optional_dependencies <- c("glmnetUtils", "e1071")
           unmet_dependencies <- setdiff(optional_dependencies, rownames(installed.packages()))
           if(length(unmet_dependencies) > 0){
               install.packages(unmet_dependencies)
           }
           for(pkg in optional_dependencies){
               library(pkg, character.only = TRUE)
           }

In this vignette we will train all of these models. Note that if you do it on your own data, it make take quite a bit of memory (remember that the output expression matrix will be a numeric matrix of size `(prediction_events_downsampling x number of wells) rows x (number of wells x number of models)`.

To train multiple models we create a list of these fitter_* functions and assign this to the `regression_functions` argument that will be fed to the `infinity_flow` function. The names of this list will be used to name your models.

    regression_functions <- list(
        XGBoost = fitter_xgboost, # XGBoost
        SVM = fitter_svm, # SVM
        LASSO2 = fitter_glmnet, # L1-penalized 2nd degree polynomial model
        LM = fitter_linear # Linear model
    )

# The `extra_args_regression_params` argument

This argument is a list of list (so of the form `list(list(...), list(...), etc.)`) of length `length(regression_functions)`. Each element of the extra_args_regression_params object is thus a list. This lower-level list will be used to pass named arguments to the machine learning fitting function. The list of `extra_args_regression_params` is matched with the list of machine learning models `regression_functions` using the order of the elements in these two lists (e.g. the first regression model is matched with the first element of the list of arguments, then the seconds elements are matched together, etc…).

    backbone_size <- table(read.csv(backbone_selection_file)[,"type"])["backbone"]
    extra_args_regression_params <- list(
         ## Passed to the first element of `regression_functions`, e.g. XGBoost. See ?xgboost for which parameters can be passed through this list
        list(nrounds = 500, eta = 0.05),

        # ## Passed to the second element of `regression_functions`, e.g. neural networks through keras::fit. See https://keras.rstudio.com/articles/tutorial_basic_regression.html
        # list(
        #         object = { ## Specifies the network's architecture, loss function and optimization method
        #             model = keras_model_sequential()
        #             model %>%
        #                 layer_dense(units = backbone_size, activation = "relu", input_shape = backbone_size) %>%
        #                 layer_dense(units = backbone_size, activation = "relu", input_shape = backbone_size) %>%
        #                 layer_dense(units = 1, activation = "linear")
        #             model %>%
        #                 compile(loss = "mean_squared_error", optimizer = optimizer_sgd(lr = 0.005))
        #             serialize_model(model)
        #         },
        #         epochs = 1000, ## Number of maximum training epochs. The training is however stopped early if the loss on the validation set does not improve for 20 epochs. This early stopping is hardcoded in fitter_nn.
        #         validation_split = 0.2, ## Fraction of the training data used to monitor validation loss
        #         verbose = 0,
        #         batch_size = 128 ## Size of the minibatches for training.
        # ),

        # Passed to the third element, SVMs. See help(svm, "e1071") for possible arguments
        list(type = "nu-regression", cost = 8, nu=0.5, kernel="radial"),

        # Passed to the fourth element, fitter_glmnet. This should contain a mandatory argument `degree` which specifies the degree of the polynomial model (1 for linear, 2 for quadratic etc...). Here we use degree = 2 corresponding to our LASSO2 model Other arguments are passed to getS3method("cv.glmnet", "formula"),
        list(alpha = 1, nfolds=10, degree = 2),

        # Passed to the fourth element, fitter_linear. This only accepts a degree argument specifying the degree of the polynomial model. Here we use degree = 1 corresponding to a linear model.
        list(degree = 1)
    )

We can now run the pipeline with these custom arguments to train all the models.

    if(length(regression_functions) != length(extra_args_regression_params)){
        stop("Number of models and number of lists of hyperparameters mismatch")
    }
    imputed_data <- infinity_flow(
        regression_functions = regression_functions,
        extra_args_regression_params = extra_args_regression_params,
        path_to_fcs = path_to_fcs,
        path_to_output = path_to_output,
        path_to_intermediary_results = path_to_intermediary_results,
        backbone_selection_file = backbone_selection_file,
        annotation = targets,
        isotype = isotypes,
        input_events_downsampling = input_events_downsampling,
        prediction_events_downsampling = prediction_events_downsampling,
        verbose = TRUE,
        cores = cores
    )
    #> Using directories...
    #>  input: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/fcs
    #>  intermediary: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/tmp
    #>  subset: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/tmp/subsetted_fcs
    #>  rds: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/tmp/rds
    #>  annotation: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/tmp/annotation.csv
    #>  output: /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/infinity_flow_example/output
    #> Parsing and subsampling input data
    #>  Downsampling to 1000 events per input file
    #>  Concatenating expression matrices
    #>  Writing to disk
    #> Logicle-transforming the data
    #>  Backbone data
    #>  Exploratory data
    #>  Writing to disk
    #>  Transforming expression matrix
    #>  Writing to disk
    #> Harmonizing backbone data
    #>  Scaling expression matrices
    #>  Writing to disk
    #> Fitting regression models
    #>  Randomly selecting 50% of the subsetted input files to fit models
    #>  Fitting...
    #>      XGBoost
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Passed unrecognized parameters: ",
    #> paste(head(names_unrecognized), : Passed unrecognized parameters: verbose. This
    #> warning will become an error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'data' has been renamed to 'x'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'label' has been renamed to 'y'. This warning will become an
    #> error in a future version.
    #> Warning in throw_err_or_depr_msg("Parameter '", match_old, "' has been renamed
    #> to '", : Parameter 'eta' has been renamed to 'learning_rate'. This warning will
    #> become an error in a future version.
    #>  6.21599 seconds
    #>      SVM
    #>
    #>  0.372726 seconds
    #>      LASSO2
    #>
    #>  2.775987 seconds
    #>      LM
    #>
    #>  0.02674007 seconds
    #> Imputing missing measurements
    #>  Randomly drawing events to predict from the test set
    #>  Imputing...
    #>      XGBoost
    #>
    #>  0.17627 seconds
    #>      SVM
    #>
    #>  0.4068191 seconds
    #>      LASSO2
    #>
    #>  0.3445721 seconds
    #>      LM
    #>
    #>  0.01766086 seconds
    #>  Concatenating predictions
    #>  Writing to disk
    #> Performing dimensionality reduction
    #> 18:33:21 UMAP embedding parameters a = 1.262 b = 1.003
    #> 18:33:21 Read 5000 rows and found 17 numeric columns
    #> 18:33:21 Using Annoy for neighbor search, n_neighbors = 15
    #> 18:33:21 Building Annoy index with metric = euclidean, n_trees = 50
    #> 0%   10   20   30   40   50   60   70   80   90   100%
    #> [----|----|----|----|----|----|----|----|----|----|
    #> **************************************************|
    #> 18:33:21 Writing NN index file to temp file /var/folders/r0/l4fjk6cj5xj0j3brt4bplpl40000gt/T//Rtmp008A5V/fileaf1832bdbea2
    #> 18:33:21 Searching Annoy index using 1 thread, search_k = 1500
    #> 18:33:22 Annoy recall = 100%
    #> 18:33:22 Commencing smooth kNN distance calibration using 1 thread with target n_neighbors = 15
    #> 18:33:22 Initializing from normalized Laplacian + noise (using RSpectra)
    #> 18:33:22 Commencing optimization for 1000 epochs, with 102142 positive edges using 1 thread
    #> 18:33:22 Using rng type: pcg
    #> 18:33:29 Optimization finished
    #> Exporting results
    #>  Transforming predictions back to a linear scale
    #>  Exporting FCS files (1 per well)
    #> Plotting
    #>  Chopping off the top and bottom 0.005 quantiles
    #>  Shuffling the order of cells (rows)
    #>  Producing plot
    #> Background correcting
    #>  Transforming background-corrected predictions. (Use logarithm to visualize)
    #>  Exporting FCS files (1 per well)
    #> Plotting
    #>  Chopping off the top and bottom 0.005 quantiles
    #>  Shuffling the order of cells (rows)
    #>  Producing plot

Our model names are appended to the predicted markers in the output. For more discussion about the outputs (including output files written to disk and plots), see the basic usage vignette

       print(imputed_data$bgc[1:2, ])
    #>      FSC-A      FSC-H      FSC-W   SSC-A      SSC-H      SSC-W CD69-CD301b
    #> 5 32859.87 -2.1449160  1.3450308 8654.45 0.92507623  0.7849237   -2.076328
    #> 6 58102.14  0.4782935 -0.4311442 4303.92 0.05494837 -0.2107653   -1.389634
    #>     Zombie      MHCII       CD4      CD44       CD8     CD11c    CD11b     F480
    #> 5 299.3122  0.4089399 -2.197290 1.1562806 -1.601334 0.2165821 1.867456 1.467150
    #> 6 494.3557 -1.7596337  0.774347 0.9155062 -1.318072 0.7303352 1.614958 1.980995
    #>        Ly6C    Lineage  CD45a488 FJComp-PE(yg)-A      CD24     CD103      Time
    #> 5 1.8185607 -2.7206697 0.7867635        1.261139 0.2086343 1.6745213 2817.6074
    #> 6 0.7310753 -0.4658658 0.5931866        1.655705 0.1967055 0.2677174  426.8011
    #>   CD137.LASSO2_bgc CD137.LM_bgc CD137.SVM_bgc CD137.XGBoost_bgc CD28.LASSO2_bgc
    #> 5       0.08042909    0.1983903    0.43364761         0.4338506       0.5771817
    #> 6       0.61403877    0.1142942   -0.05536389         0.1431117      -0.3091259
    #>   CD28.LM_bgc CD28.SVM_bgc CD28.XGBoost_bgc CD49b(pan-NK).LASSO2_bgc
    #> 5 -0.01729384    1.5654989        0.2844930              -0.04947471
    #> 6 -0.15897823   -0.5658218       -0.8773111              -0.55313684
    #>   CD49b(pan-NK).LM_bgc CD49b(pan-NK).SVM_bgc CD49b(pan-NK).XGBoost_bgc
    #> 5            0.2819700            -1.0775226                -0.5708965
    #> 6           -0.1723178            -0.1620367                -0.5017029
    #>   KLRG1.LASSO2_bgc KLRG1.LM_bgc KLRG1.SVM_bgc KLRG1.XGBoost_bgc
    #> 5      -0.50056997    0.2808805    1.05705505        0.48428235
    #> 6      -0.09139122    0.1157290   -0.01855306       -0.06305932
    #>   Ly-49c/F/I/H.LASSO2_bgc Ly-49c/F/I/H.LM_bgc Ly-49c/F/I/H.SVM_bgc
    #> 5               0.7082326          -0.0505043           -0.1072312
    #> 6              -0.2831090          -0.2587553           -1.2370760
    #>   Ly-49c/F/I/H.XGBoost_bgc Podoplanin.LASSO2_bgc Podoplanin.LM_bgc
    #> 5               -0.6876995           -0.03245581        -0.4812653
    #> 6               -0.3650602           -0.15094733        -0.3963808
    #>   Podoplanin.SVM_bgc Podoplanin.XGBoost_bgc SHIgG.LASSO2_bgc  SHIgG.LM_bgc
    #> 5        0.006969572             -0.4440527     3.871948e-15 -2.093784e-16
    #> 6       -0.526057836             -0.6021933    -1.152348e-15 -5.236917e-17
    #>   SHIgG.SVM_bgc SHIgG.XGBoost_bgc SSEA-3.LASSO2_bgc SSEA-3.LM_bgc
    #> 5 -1.494126e-15      2.717801e-15        -0.6975234   -0.58168997
    #> 6 -3.950609e-16     -1.678457e-15        -0.3528369    0.07826569
    #>   SSEA-3.SVM_bgc SSEA-3.XGBoost_bgc TCR Vg3.LASSO2_bgc TCR Vg3.LM_bgc
    #> 5     -0.5221341         -0.5771078         -0.4600406     0.36087598
    #> 6     -1.2085801          0.3623279         -0.1582165     0.09898223
    #>   TCR Vg3.SVM_bgc TCR Vg3.XGBoost_bgc rIgM.LASSO2_bgc   rIgM.LM_bgc
    #> 5        1.362288         -0.04214163   -4.700675e-16  1.389691e-15
    #> 6       -1.244955         -1.07061027   -1.098105e-15 -3.374110e-16
    #>    rIgM.SVM_bgc rIgM.XGBoost_bgc    UMAP1    UMAP2 PE_id
    #> 5 -2.584583e-16    -1.599968e-15 568.2101 572.0743     1
    #> 6  2.125694e-16    -6.579129e-16 625.1977 572.8485     1

# Neural networks

Neural networks won’t build in knitr for me but here is an example of the syntax if you want to use them.

Note: there is an issue with serialization of the neural networks and socketing since I updated to R-4.0.1. If you want to use neural networks, please make sure to set

    cores = 1L

    optional_dependencies <- c("keras", "tensorflow")
    unmet_dependencies <- setdiff(optional_dependencies, rownames(installed.packages()))
    if(length(unmet_dependencies) > 0){
         install.packages(unmet_dependencies)
    }
    for(pkg in optional_dependencies){
        library(pkg, character.only = TRUE)
    }

    invisible(eval(try(keras_model_sequential()))) ## avoids conflicts with flowCore...

    if(!is_keras_available()){
         install_keras() ## Instal keras unsing the R interface - can take a while
    }

    if (!requireNamespace("BiocManager", quietly = TRUE)){
        install.packages("BiocManager")
    }
    BiocManager::install("infinityFlow")

    library(infinityFlow)
    library(keras)

    data(steady_state_lung)
    data(steady_state_lung_annotation)
    data(steady_state_lung_backbone_specification)

    dir <- file.path(tempdir(), "infinity_flow_example")
    input_dir <- file.path(dir, "fcs")
    write.flowSet(steady_state_lung, outdir = input_dir)

    write.csv(steady_state_lung_backbone_specification, file = file.path(dir, "backbone_selection_file.csv"), row.names = FALSE)

    path_to_fcs <- file.path(dir, "fcs")
    path_to_output <- file.path(dir, "output")
    path_to_intermediary_results <- file.path(dir, "tmp")
    backbone_selection_file <- file.path(dir, "backbone_selection_file.csv")

    targets <- steady_state_lung_annotation$Infinity_target
    names(targets) <- rownames(steady_state_lung_annotation)
    isotypes <- steady_state_lung_annotation$Infinity_isotype
    names(isotypes) <- rownames(steady_state_lung_annotation)

    input_events_downsampling <- 1000
    prediction_events_downsampling <- 500

    ## Passed to fitter_nn, e.g. neural networks through keras::fit. See https://keras.rstudio.com/articles/tutorial_basic_regression.html
    regression_functions <- list(NN = fitter_nn)

    backbone_size <- table(read.csv(backbone_selection_file)[,"type"])["backbone"]
    extra_args_regression_params <- list(
            list(
            object = { ## Specifies the network's architecture, loss function and optimization method
            model = keras_model_sequential()
            model %>%
            layer_dense(units = backbone_size, activation = "relu", input_shape = backbone_size) %>%
            layer_dense(units = backbone_size, activation = "relu", input_shape = backbone_size) %>%
            layer_dense(units = 1, activation = "linear")
            model %>%
            compile(loss = "mean_squared_error", optimizer = optimizer_sgd(lr = 0.005))
            serialize_model(model)
            },
            epochs = 1000, ## Number of maximum training epochs. The training is however stopped early if the loss on the validation set does not improve for 20 epochs. This early stopping is hardcoded in fitter_nn.
            validation_split = 0.2, ## Fraction of the training data used to monitor validation loss
            verbose = 0,
            batch_size = 128 ## Size of the minibatches for training.
        )
    )

    imputed_data <- infinity_flow(
        regression_functions = regression_functions,
        extra_args_regression_params = extra_args_regression_params,
        path_to_fcs = path_to_fcs,
        path_to_output = path_to_output,
        path_to_intermediary_results = path_to_intermediary_results,
        backbone_selection_file = backbone_selection_file,
        annotation = targets,
        isotype = isotypes,
        input_events_downsampling = input_events_downsampling,
        prediction_events_downsampling = prediction_events_downsampling,
        verbose = TRUE,
        cores = 1L
    )

# Conclusion

Thank you for following this vignette, I hope you made it through the end without too much headache and that it was informative. General questions about proper usage of the package are best asked on the Bioconductor support site to maximize visibility for future users. If you encounter bugs, feel free to raise an issue on infinityFlow’s github.

# Information about the R session when this vignette was built

    sessionInfo()
    #> R version 4.6.0 Patched (2026-04-24 r89963)
    #> Platform: aarch64-apple-darwin23
    #> Running under: macOS Tahoe 26.3.1
    #>
    #> Matrix products: default
    #> BLAS:   /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRblas.0.dylib
    #> LAPACK: /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1
    #>
    #> Random number generation:
    #>  RNG:     L'Ecuyer-CMRG
    #>  Normal:  Inversion
    #>  Sample:  Rejection
    #>
    #> locale:
    #> [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
    #>
    #> time zone: America/New_York
    #> tzcode source: internal
    #>
    #> attached base packages:
    #> [1] stats     graphics  grDevices utils     datasets  methods   base
    #>
    #> other attached packages:
    #> [1] infinityFlow_1.22.0 flowCore_2.24.0
    #>
    #> loaded via a namespace (and not attached):
    #>  [1] sass_0.4.10         generics_0.1.4      class_7.3-23
    #>  [4] gtools_3.9.5        shape_1.4.6.1       lattice_0.22-9
    #>  [7] digest_0.6.39       evaluate_1.0.5      grid_4.6.0
    #> [10] iterators_1.0.14    fastmap_1.2.0       foreach_1.5.2
    #> [13] glmnet_4.1-10       xgboost_3.2.1.1     jsonlite_2.0.0
    #> [16] Matrix_1.7-5        RSpectra_0.16-2     e1071_1.7-17
    #> [19] survival_3.8-6      pbapply_1.7-4       codetools_0.2-20
    #> [22] jquerylib_0.1.4     glmnetUtils_1.1.9   cli_3.6.6
    #> [25] rlang_1.2.0         RProtoBufLib_2.24.0 Biobase_2.72.0
    #> [28] RcppAnnoy_0.0.23    uwot_0.2.4          matlab_1.0.4.1
    #> [31] splines_4.6.0       cachem_1.1.0        yaml_2.3.12
    #> [34] otel_0.2.0          cytolib_2.24.0      tools_4.6.0
    #> [37] raster_3.6-32       parallel_4.6.0      BiocGenerics_0.58.0
    #> [40] R6_2.6.1            png_0.1-9           matrixStats_1.5.0
    #> [43] stats4_4.6.0        proxy_0.4-29        lifecycle_1.0.5
    #> [46] S4Vectors_0.50.0    terra_1.9-11        bslib_0.10.0
    #> [49] data.table_1.18.2.1 Rcpp_1.1.1-1.1      xfun_0.57
    #> [52] knitr_1.51          htmltools_0.5.9     rmarkdown_2.31
    #> [55] compiler_4.6.0      sp_2.2-1