-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathREADME.Rmd
183 lines (153 loc) · 9.61 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
---
output: github_document
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/"
)
```
# mrIML: Multivariate (multi-response) interpretable machine learning <img src="man/figures/logo.png" align="right" height="120"/></a>
<!-- badges: start -->
![GitHub R package version](https://img.shields.io/github/r-package/v/nfj1380/mrIML?logo=github&logoColor=%2300ff37&style=flat-square)
![GitHub contributors](https://img.shields.io/github/contributors/nfj1380/mrIML?style=flat-square)
![GitHub last commit](https://img.shields.io/github/last-commit/nfj1380/mrIML?style=flat-square)
[![R-CMD-check](https://github.com/nfj1380/mrIML/workflows/R-CMD-check/badge.svg)](https://github.com/nfj1380/mrIML/actions)
<!-- badges: end -->
This package aims to enable users to build and interpret multivariate machine learning models harnessing the tidyverse (tidy model syntax in particular). This package builds off ideas from Gradient Forests [Ellis et al 2012](https://esajournals-onlinelibrary-wiley-com.prox.lib.ncsu.edu/doi/full/10.1890/11-0252.1)), ecological genomic approaches [Fitzpatrick and Keller, 2014](https://onlinelibrary.wiley.com/doi/abs/10.1111/ele.12376) and multi-response stacking algorithms [Xing et al 2019].
This package can be of use for any multi-response machine learning problem, but was designed to handle data common to community ecology (site by species data) and ecological genomics (individual or population by SNP loci).
## Installation
Install the stable version of the package:
```{r, eval = FALSE}
#install.packages("devtools")
#devtools::install_github('nfj1380/mrIML')
library(mrIML)
```
## Quick start
**mrIML** is designed to be used with a single function call or to be used in an ad-hoc fashion via individual function calls. In the following section we give an overview of the simple use case. For more on using each function see the [function documentation](https://nfj1380.github.io/mrIML/reference/index.html). The core functions for both regression and classification are: [`mrIMLpredicts`](https://nfj1380.github.io/mrIML/reference/mrIMLpredicts.html),
[`mrIMLperformance`](https://nfj1380.github.io/mrIML/reference/mrIMLperformance.html), and
[`mrvip`](https://nfj1380.github.io/mrIML/reference/mrvip.html), [`mrFlashlight`](https://nfj1380.github.io/mrIML/reference/mrFlashlight.html), and[`mrProfileplots`](https://nfj1380.github.io/mrIML/reference/mrProfileplots.html).
We also allow users to get bootstrapped estimations of partial dependencies and variable importance using [`mrBootstrap`](https://nfj1380.github.io/mrIML/reference/mrBootstrap.html).
The first step to using the package is to load it as follows.
```{r, message = FALSE, message = FALSE, warning = FALSE, include=FALSE}
pacman:: p_load(
vip, tidymodels, randomForest, caret, gbm,
tidyverse, parallel, doParallel, themis, viridis,
janitor, hrbrthemes, xgboost, vegan, flashlight,
ggrepel, iml, plyr, future.apply, gridExtra, cowplot, mrIML,hstats)
```
## Model component
Now all the data is loaded and ready to go we can formulate the model using tidymodel syntax. In this case we have binary data (SNP presence/absence at each loci) but the data could also be counts or continuous (the set_model argument would be "regression" instead of "classification"). The user can specify any model from the 'tidymodel' universe as 'model 1' (see https://www.tidymodels.org/find/ for details). However, we have done most of our testing on random forests (rf) and glms (generalized linear models). Here we will specify a random forest classification model as the model applied to each response.
```{r }
model_rf <-rand_forest(trees = 100,
mode = "classification",
mtry = tune(),
min_n = tune()) %>% #100 trees are set for brevity. Aim to start with 1000
set_engine("randomForest")
```
### [`mrIMLpredicts`](https://nfj1380.github.io/mrIML/reference/mrIMLpredicts.html)
This function represents the core functionality of the package and
includes results reporting, plotting and optional saving. It requires a
data frame of X t( the snp data for example) and Y represented by the covariates or features.
Load example data (cite) data from `{mrIML}`.
``` {r}
fData <- filterRareCommon (Responsedata,
lower=0.4,
higher=0.7)
data <- fData[1:20]
```
## Parallel processing
MrIML provides uses the flexible future apply functionality to set up multi-core processing. In the example below, we set up a cluster using 4 cores. If you don't set up a cluster, the default settings will be used and the analysis will run sequentially.
```{r, eval = FALSE}
# detectCores() #check how many cores you have available. We suggest keeping one core free for internet browsing etc.
cl <- parallel::makeCluster(4)
plan(cluster,
workers=cl)
```
``` {r message = FALSE, warning = FALSE}
Y <- fData #For simplicity when comparing
#Define set the outcomes of interest
str(Features)
#Remove NAs from the feature/predictor data.
FeaturesnoNA<-Features[complete.cases(Features), ]
X <- FeaturesnoNA #For simplicity
#For more efficient testing for interactions (more variables more interacting pairs)
X <- FeaturesnoNA[c(1:3)] #Three features only
yhats_rf <- mrIMLpredicts(X=X,Y=Y, #specify which data to use
Model=model_rf, #what model
balance_data='no', #balance the data or not
mode='classification', #classification or regression
k=5,
tune_grid_size=5, #tuning parameters
seed = 123,
racing=F) #Set seed
ModelPerf <- mrIMLperformance(yhats=yhats_rf,
Model=model_rf,
Y=Y,
mode='classification')
ModelPerf[[1]] #Predictive performance for individual responses
ModelPerf[[2]]#Overall predictive performance. r2 for regression and MCC for classification
```
## Plotting
```{r message = FALSE, warning = FALSE}
bs_impVI <- mrvip(
mrBootstrap_obj = NULL,
yhats = yhats_rf,
X = X,
Y = Y,
mode = 'classification',
threshold = 0.8,
global_top_var = 10,
local_top_var = 5,
taxa = 'pol_132',
ModelPerf = ModelPerf)
bs_impVI[[3]] #importance
bs_impVI[[4]] #PCA
```
## Effect of a feature on genetic change
We also wrap some flashlight functionality to visualize the marginal (i.e. partial dependencies) or conditional (accumulated local effects) effect of a feature on genetic change. Partial dependencies take longer to calculate and are more sensitive to correlated features
```{r message = FALSE, warning = FALSE}
flashlightObj <- mrFlashlight(yhats_rf,
X=X,
Y=Y,
response = "single",
index=1,
mode='classification')
#plot prediction scatter for all responses. Gets busy with
plot(light_scatter(flashlightObj,
v = "Forest",
type = "predicted"))
#plots everything on one plot (partial dependency, ALE, scatter)
plot(light_effects(flashlightObj,
v = "Grassland"),
use = "all")
profileData_ale <- light_profile(flashlightObj,
v = "Grassland",
type = "ale") #accumulated local effects
mrProfileplot(profileData_ale,
sdthresh =0.01)
#the second plot is the cumulative turnover function
```
## Interacting predictors or features
Finally, we can assess how features interact overall to shape genetic change. Be warned this is memory intensive. Future updates to this package will enable users to visualize these interactions and explore them in more detail using 2D ALE plots for example.
```{r message = FALSE, warning = FALSE}
int_ <- mrInteractions(yhats=yhats_rf,
X,
Y,
num_bootstrap=10,
feature = 'Plas',
top.int=10)
#10 bootstraps to keep it short. top int focusses on the 10 top interactions (all of them in this case).
int_[[1]] # overall plot
#int_[[2]] # individual plot for the response of choice
#int_[[3]] # two way plot
```
## Recent mrIML publications
1. Fountain-Jones, N. M., Kozakiewicz, C. P., Forester, B. R., Landguth, E. L., Carver, S., Charleston, M., Gagne, R. B., Greenwell, B., Kraberger, S., Trumbo, D. R., Mayer, M., Clark, N. J., & Machado, G. (2021). MrIML: Multi-response interpretable machine learning to model genomic landscapes. Molecular Ecology Resources, 21, 2766– 2781. https://doi.org/10.1111/1755-0998.13495
2. Sykes, A. L., Silva, G. S., Holtkamp, D. J., Mauch, B. W., Osemeke, O., Linhares, D. C.L., & Machado, G. (2021). Interpretable machine learning applied to on-farm biosecurity and porcine reproductive and respiratory syndrome virus. Transboundary and Emerging Diseases, 00, 1– 15. https://doi.org/10.1111/tbed.14369
## References
Xing, L, Lesperance, ML and Zhang, X (2020). Simultaneous prediction of multiple outcomes using revised stacking algorithms. Bioinformatics, 36, 65-72. doi:10.1093/bioinformatics/btz531.
Fitzpatrick, M.C. & Keller, S.R. (2015) Ecological genomics meets community-level modelling of biodiversity: mapping the genomic landscape of current and future environmental adaptation. Ecology Letters 18, 1–16.doi.org/10.1111/ele.12376
Ellis, N., Smith, S.J. and Pitcher, C.R. (2012), Gradient forests: calculating importance gradients on physical predictors. Ecology, 93: 156-168. doi:10.1890/11-0252.1