# 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] "C:\\Users\\biocbuild\\bbs-3.12-bioc\\tmpdir\\RtmpU38bOS/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: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/infinity_flow_example/fcs
    #>  intermediary: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/infinity_flow_example/tmp
    #>  subset: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/infinity_flow_example/tmp/subsetted_fcs
    #>  rds: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/infinity_flow_example/tmp/rds
    #>  annotation: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/infinity_flow_example/tmp/annotation.csv
    #>  output: C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS/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
    #>
    #>  10.93756 seconds
    #>      SVM
    #>
    #>  1.812509 seconds
    #>      LASSO2
    #>
    #>  8.078166 seconds
    #>      LM
    #>
    #>  0.984381 seconds
    #> Imputing missing measurements
    #>  Randomly drawing events to predict from the test set
    #>  Imputing...
    #>      XGBoost
    #>
    #>  4.140646 seconds
    #>      SVM
    #>
    #>  2.437512 seconds
    #>      LASSO2
    #>
    #>  1.312507 seconds
    #>      LM
    #>
    #>  0.5312531 seconds
    #>  Concatenating predictions
    #>  Writing to disk
    #> Performing dimensionality reduction
    #> 22:26:57 UMAP embedding parameters a = 1.262 b = 1.003
    #> 22:26:57 Read 5000 rows and found 17 numeric columns
    #> 22:26:57 Using Annoy for neighbor search, n_neighbors = 15
    #> 22:26:57 Building Annoy index with metric = euclidean, n_trees = 50
    #> 0%   10   20   30   40   50   60   70   80   90   100%
    #> [----|----|----|----|----|----|----|----|----|----|
    #> **************************************************|
    #> 22:26:58 Writing NN index file to temp file C:\Users\biocbuild\bbs-3.12-bioc\tmpdir\RtmpU38bOS\filee68632263f3
    #> 22:27:05 Searching Annoy index using 1 thread, search_k = 1500
    #> 22:27:06 Annoy recall = 100%
    #> 22:27:06 Commencing smooth kNN distance calibration using 1 thread
    #> 22:27:07 Initializing from normalized Laplacian + noise
    #> 22:27:07 Commencing optimization for 1000 epochs, with 101740 positive edges using 1 thread
    #> 22:27:34 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
    #> 1 52791.90  0.04035001 -0.04833498 4331.57  0.04755276 -0.09059185   0.6907079
    #> 2 42699.96 -0.58006273 -0.51119369 2580.14 -0.64388848 -0.93773260  -0.9539474
    #>      Zombie      MHCII        CD4        CD44        CD8     CD11c      CD11b
    #> 1 539.40082 -0.8057837  1.7803529  0.64527539  0.5851340 -2.315555 0.47835424
    #> 2 -23.56643  0.7453973 -0.4051692 -0.06433007 -0.6310805 -2.161572 0.09510357
    #>         F480      Ly6C    Lineage  CD45a488 FJComp-PE(yg)-A       CD24
    #> 1 -1.2044234 -1.308614 1.59234821 0.7488189        2.325362 -1.4421832
    #> 2 -0.7184957 -1.292221 0.01599983 0.2893867        0.472948  0.7013006
    #>        CD103      Time CD137.LASSO2_bgc CD137.LM_bgc CD137.SVM_bgc
    #> 1 -1.0349163 3494.2092       -0.3077289   -0.5094183     -1.414277
    #> 2 -0.7694443  841.1022       -0.1747816   -0.6087559     -1.049594
    #>   CD137.XGBoost_bgc CD28.LASSO2_bgc CD28.LM_bgc CD28.SVM_bgc CD28.XGBoost_bgc
    #> 1        -0.8469490      0.73805718   0.3019619  1.259969877        0.7602414
    #> 2         0.3263508     -0.07883164  -0.1543901 -0.008943954       -0.3807403
    #>   CD49b(pan-NK).LASSO2_bgc CD49b(pan-NK).LM_bgc CD49b(pan-NK).SVM_bgc
    #> 1                0.4401390           -0.1017494             0.8985189
    #> 2               -0.2604814           -0.3353360            -0.3641775
    #>   CD49b(pan-NK).XGBoost_bgc KLRG1.LASSO2_bgc KLRG1.LM_bgc KLRG1.SVM_bgc
    #> 1                 1.4101291        1.0216243    0.2292339      1.231808
    #> 2                -0.4068673       -0.3948214   -0.4045759     -1.377872
    #>   KLRG1.XGBoost_bgc Ly-49c/F/I/H.LASSO2_bgc Ly-49c/F/I/H.LM_bgc
    #> 1          1.115909              -0.1458021          -0.2783837
    #> 2         -1.011616              -0.2323227          -0.3624930
    #>   Ly-49c/F/I/H.SVM_bgc Ly-49c/F/I/H.XGBoost_bgc Podoplanin.LASSO2_bgc
    #> 1           -0.5045613               -0.9024090            -0.4907910
    #> 2           -0.9276748               -0.6392111            -0.4846039
    #>   Podoplanin.LM_bgc Podoplanin.SVM_bgc Podoplanin.XGBoost_bgc SHIgG.LASSO2_bgc
    #> 1        -0.4172669         -0.6861190              0.2145381    -8.940419e-17
    #> 2        -0.6080634         -0.6389008             -0.7489333     2.246143e-16
    #>    SHIgG.LM_bgc SHIgG.SVM_bgc SHIgG.XGBoost_bgc SSEA-3.LASSO2_bgc SSEA-3.LM_bgc
    #> 1 -1.788084e-16  2.980140e-17      1.379688e-17      -0.098493572   -0.01017301
    #> 2  1.352101e-16 -1.272078e-16      1.379688e-17      -0.002953713   -0.08783253
    #>   SSEA-3.SVM_bgc SSEA-3.XGBoost_bgc TCR Vg3.LASSO2_bgc TCR Vg3.LM_bgc
    #> 1     -0.5774018         0.51515094        -0.07683607     -0.3352735
    #> 2     -0.1586131         0.08687002        -0.15478696     -0.4057652
    #>   TCR Vg3.SVM_bgc TCR Vg3.XGBoost_bgc rIgM.LASSO2_bgc   rIgM.LM_bgc
    #> 1      -1.0292872          0.09398269    1.127762e-15 -2.980140e-17
    #> 2      -0.4922873         -0.57342274   -2.853209e-16  1.272078e-16
    #>    rIgM.SVM_bgc rIgM.XGBoost_bgc     UMAP1    UMAP2 PE_id
    #> 1  1.104859e-15     3.518221e-16  83.52677 638.6662     1
    #> 2 -1.093270e-15     1.948129e-16 306.76354 101.0795     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)

    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.0.3 (2020-10-10)
    #> Platform: x86_64-w64-mingw32/x64 (64-bit)
    #> Running under: Windows Server 2012 R2 x64 (build 9600)
    #>
    #> Matrix products: default
    #>
    #> Random number generation:
    #>  RNG:     L'Ecuyer-CMRG
    #>  Normal:  Inversion
    #>  Sample:  Rejection
    #>
    #> locale:
    #> [1] LC_COLLATE=C
    #> [2] LC_CTYPE=English_United States.1252
    #> [3] LC_MONETARY=English_United States.1252
    #> [4] LC_NUMERIC=C
    #> [5] LC_TIME=English_United States.1252
    #>
    #> attached base packages:
    #> [1] stats     graphics  grDevices utils     datasets  methods   base
    #>
    #> other attached packages:
    #> [1] e1071_1.7-4        glmnetUtils_1.1.6  infinityFlow_1.0.0 flowCore_2.2.0
    #>
    #> loaded via a namespace (and not attached):
    #>  [1] Rcpp_1.0.5          RSpectra_0.16-0     compiler_4.0.3
    #>  [4] cytolib_2.2.0       class_7.3-17        iterators_1.0.13
    #>  [7] tools_4.0.3         uwot_0.1.8          digest_0.6.27
    #> [10] evaluate_0.14       lattice_0.20-41     png_0.1-7
    #> [13] rlang_0.4.8         foreach_1.5.1       Matrix_1.2-18
    #> [16] yaml_2.2.1          parallel_4.0.3      xfun_0.18
    #> [19] stringr_1.4.0       knitr_1.30          raster_3.3-13
    #> [22] generics_0.0.2      S4Vectors_0.28.0    stats4_4.0.3
    #> [25] xgboost_1.2.0.1     grid_4.0.3          glmnet_4.0-2
    #> [28] Biobase_2.50.0      data.table_1.13.2   RcppAnnoy_0.0.16
    #> [31] pbapply_1.4-3       survival_3.2-7      rmarkdown_2.5
    #> [34] sp_1.4-4            RProtoBufLib_2.2.0  matlab_1.0.2
    #> [37] magrittr_1.5        splines_4.0.3       codetools_0.2-16
    #> [40] matrixStats_0.57.0  htmltools_0.5.0     BiocGenerics_0.36.0
    #> [43] shape_1.4.5         stringi_1.5.3       RcppParallel_5.0.2