forked from neurodata/SPORF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
executable file
·429 lines (315 loc) · 14.1 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
---
title: "Randomer Forest"
output:
github_document:
html_preview: false
toc: false
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, include=FALSE, eval = FALSE}
## run this to build the README.md file.
## takes less than 60 seconds to run.
require(rerf)
system.time({
rmarkdown::render('README.Rmd')
}
)
```
```{r, echo = FALSE, include = FALSE}
library(rerf)
knitr::opts_chunk$set(
cache = FALSE,
collapse = TRUE,
comment = "#>"
)
```
[![CRAN Status Badge](https://www.r-pkg.org/badges/version/rerf)](https://cran.r-project.org/package=rerf)
[![arXiv shield](https://img.shields.io/badge/arXiv-1506.03410-red.svg?style=flat)](https://arxiv.org/abs/1506.03410)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2558568.svg)](https://doi.org/10.5281/zenodo.2558568)
- [Randomer Forest](#randomer-forest)
- [Repo Contents](#repo-contents)
- [Description](#description)
- [Tested on](#tested-on)
- [Hardware Requirements](#hardware-requirements)
- [Software Dependencies](#software-dependencies)
- [Installation](#installation)
- [Usage](#usage)
- [Load the library :](#load-the-library)
- [Create a forest:](#create-a-forest)
- [Making predictions and determining error
rate:](#making-predictions-and-determining-error-rate)
- [Compute similarities:](#compute-similarities)
- [Compute tree strengths and
correlations:](#compute-tree-strengths-and-correlations)
- [Train Structured RerF (S-RerF) for image
classification:](#train-structured-rerf-s-rerf-for-image-classification)
- [Unsupervised classification
(U-RerF)](#unsupervised-classification-u-rerf)
- [Similarity Randomer Forest
(SmerF)](#similarity-randomer-forest-smerf)
- [Fast-RerF (fpRerF)](#forest-packing-with-fast-rerf)
## Repo Contents
- [**R**](R): `R` building blocks for user interface code. Internally called by user interface.
- [**man**](man): Package documentation
- [**src**](src): C++ functions called from within R
- [**tests**](tests): testthat tests
## Description
R-RerF (aka Randomer Forest (RerF), or Random Projection Forests) is a generalization of the Random Forest (RF) algorithm. RF partitions the input (feature) space via a series of recursive binary hyperplanes. Hyperplanes are constrained to be axis-aligned. In other words, each partition is a test of the form X<sub>i</sub> > t, where t is a threshold and X<sub>i</sub> is one of p inputs (features) {X<sub>1</sub>, ..., X<sub>p</sub>}. The best axis-aligned split is found by sampling a random subset of the p inputs and choosing the one that best partitions the observed data according to some specified split criterion. RerF relaxes the constraint that the splitting hyperplanes must be axis-aligned. That is, each partition in RerF is a test of the form w<sub>1</sub>X<sub>1</sub> + ... + w<sub>p</sub>X<sub>p</sub> > t. The orientations of hyperplanes are sampled randomly via a user-specified distribution on the coefficients w<sub>i</sub>, although an empirically validated default distribution is provided. Currently only classification is supported. Regression and unsupervised learning will be supported in the future.
## Tested on
- Mac OSX: 10.11 (El Capitan), 10.12 (Sierra), 10.13 (High Sierra)
- Linux: Ubuntu 16.04 and 17.10, CentOS 6
- Windows: 10
## Hardware Requirements
Any machine with >= 2 GB RAM
## Software Dependencies
- OpenMP (for `fpRerF`)
- `R (>= 3.3.0)`
- `R` packages:
- `dummies`
- `compiler`
- `RcppArmadillo`
- `RcppZiggurat`
- `parallel`
## Installation
- Installation normally takes ~5-10 minutes
- Non-Windows users install the GNU Scientific Library (libgsl0-dev).
- Windows users install Rtools (https://cran.r-project.org/bin/windows/Rtools/)
### Stable Release from CRAN:
From within R-
```r
install.packages("rerf")
```
### Development Version from Github:
From terminal:
```sh
git clone https://github.com/neurodata/RerF.git
## defaults to the staging branch
cd RerF
Rscript -e "install.packages('R-Project/', type = 'source', repos = NULL)"
```
#### Mac OS
- run `brew install libomp`.
- edit the user Makevars file ~/.R/Makevars:
```sh
omploc=$(brew --prefix libomp)
SHLIB_OPENMP_CFLAGS = -Xpreprocessor -fopenmp -I$(omploc)/include
SHLIB_OPENMP_CXXFLAGS = -Xpreprocessor -fopenmp -I$(omploc)/include
CFLAGS = -Wall -O3 -ffast-math
CXXFLAGS = -Wall -O3 -ffast-math
```
- then `Rscript -e "install.packages('R-Project/', type = 'source', repos = NULL)"` from the above instructions.
***
# Usage
Runtime for the following examples should be < 1 sec on any machine.
### Load the library :
```r
library(rerf)
```
## Create a forest:
To create a forest the minimum data needed is an n by d input matrix (X) and an n length vector of corresponding class labels (Y). Rows correspond to samples and columns correspond to features.
```{r create-a-forest}
X <- as.matrix(iris[,1:4])
Y <- iris[[5L]]
forest <- RerF(X, Y, seed = 1L, num.cores = 1L)
```
**Expected output**
```{r}
forest$trees[[1]]
```
`forest` is a trained forest which is needed for all other rerf functions. Additional parameters and more complex examples of training a forest can be found using the help function (`?RerF`)
## Making predictions and determining error rate:
In the example below, trainIdx is used to subset the iris dataset in order to make a training set and a testing set.
```{r making-predictions}
trainIdx <- c(1:40, 51:90, 101:140)
X <- as.matrix(iris[,1:4])
Y <- iris[[5L]]
forest <- RerF(X[trainIdx, ], Y[trainIdx], num.cores = 1L, rank.transform = TRUE, seed = 1)
# Using a set of samples with unknown classification
predictions <- Predict(X[-trainIdx, ], forest, num.cores = 1L, Xtrain = X[trainIdx, ])
error.rate <- mean(predictions != Y[-trainIdx])
```
**Expected output**
```{r}
predictions
error.rate
```
If a testing set is not available the error rate of a forest can be determined based on the samples held out-of-bag while training (out-of-bag samples are randomly chosen for each tree in the forest).
```{r oob}
X <- as.matrix(iris[,1:4])
Y <- iris[[5L]]
forest <- RerF(X, Y, store.oob=TRUE, num.cores = 1L, seed = 1L)
predictions <- OOBPredict(X, forest, num.cores = 1L)
oob.error <- mean(predictions != Y)
```
**Expected output**
```{r}
predictions
oob.error
```
## Compute similarities:
Computes pairwise similarities between observations. The similarity between two points is defined as the fraction of trees such that two points fall into the same leaf node (i.e. two samples are similar if they consistently show up in the same leaf node). This function produces an n by n symmetric similarity matrix.
```{r compute-similarities}
X <- as.matrix(iris[,1:4])
Y <- iris[[5L]]
forest <- RerF(X, Y, num.cores = 1L, seed = 1L)
sim.matrix <- ComputeSimilarity(X, forest, num.cores = 1L)
```
**Expected output**
```{r}
sim.matrix[1, ]
```
## Compute tree strengths and correlations:
Computes estimates of tree strength and correlation according to the definitions in Breiman's 2001 Random Forests paper.
```{r tree-strengths}
set.seed(24)
nsamp <- 30 ## number of training samples per species
trainIdx <- vapply(list(1:50, 51:100, 101:150), sample, outer(1,1:nsamp), size = nsamp)
X <- as.matrix(iris[,1:4])
Y <- iris[[5L]]
forest <- RerF(X[trainIdx, ], Y[trainIdx], num.cores = 1L, seed = 1L)
predictions <- Predict(X[-trainIdx, ], forest, num.cores = 1L, aggregate.output = FALSE)
scor <- StrCorr(predictions, Y[-trainIdx])
```
**Expected output**
```{r}
scor
```
### Compute feature (projection) importance (DEV version only):
Computes the Gini importance for all of the unique projections used to split the data. The returned value is a list with members imp and features. The member imp is a numeric vector of feature importances sorted in decreasing order. The member features is a list the same length as imp of vectors specifying the split projections corresponding to the values in imp. The projections are represented by the vector such that the odd numbered indices indicate the canonical feature indices and the even numbered indices indicate the linear coefficients. For example a vector (1,-1,4,1,5,-1) is the projection -X1 + X4 - X5. **Note**: it is highly advised to run this only when the splitting features (projections) have unweighted coefficients, such as for the default setting or for RF.
```{r compute-feature-importance}
X <- as.matrix(iris[, 1:4]) # feature matrix
Y <- iris$Species # class labels
p <- ncol(X) # number of features in the data
d <- ceiling(sqrt(p)) # number of features to sample at each split
# Here we specify that we want to run the standard random forest algorithm and we want to store the decrease in impurity at each split node. The latter option is required in order to compute Gini feature importance.
forest <- RerF(as.matrix(iris[, 1:4]), iris[[5L]], FUN = RandMatRF,
paramList = list(p = p, d = d), num.cores = 1L,
store.impurity = TRUE, seed = 1L)
feature.imp <- FeatureImportance(forest, num.cores = 1L, type = "R")
```
**Expected output**
```{r}
feature.imp
```
## Train Structured RerF (S-RerF) for image classification:
S-RerF samples and evaluates a set of random features at each split node, where each feature is defined as a random linear combination of intensities of pixels contained in a contiguous patch within an image. Thus, the generated features exploit local structure inherent in images.
To be able to run this example quickly we will consider training and testing on the digits `3` and `5`. You can try a differernt subset of digits by changing `numsub` in the code chunk below.
```{r mnist}
data(mnist)
## Get a random subsample, 100 each of 3's and 5's
set.seed(320)
threes <- sample(which(mnist$Ytrain %in% 3), 100)
fives <- sample(which(mnist$Ytrain %in% 5), 100)
numsub <- c(threes, fives)
Ytrain <- mnist$Ytrain[numsub]
Xtrain <- mnist$Xtrain[numsub,]
Ytest <- mnist$Ytest[mnist$Ytest %in% c(3,5)]
Xtest <- mnist$Xtest[mnist$Ytest %in% c(3,5),]
# p is number of dimensions, d is the number of random features to evaluate, iw is image width, ih is image height, patch.min is min width of square patch to sample pixels from, and patch.max is the max width of square patch
p <- ncol(Xtrain)
d <- ceiling(sqrt(p))
iw <- sqrt(p)
ih <- iw
patch.min <- 1L
patch.max <- 5L
forest <- RerF(Xtrain, Ytrain, num.cores = 1L, FUN = RandMatImagePatch,
paramList = list(p = p, d = d, iw = iw, ih = ih,
pwMin = patch.min, pwMax = patch.max),
seed = 1L)
predictions <- Predict(Xtest, forest, num.cores = 1L)
mnist.error.rate <- mean(predictions != Ytest)
```
**Expected output**
```{r}
mnist.error.rate
```
## Unsupervised classification (U-RerF)
Using the Iris dataset we will show how to use the unsupervised verison.
```{r u-rerf, results = 'hide'}
set.seed(54321)
X <- as.matrix(iris[, 1:4])
u1 <- Urerf(X, trees = 100, Progress = FALSE)
```
### The dissimilarity matrix
```{r dissimilarityMatrix}
m <- as.matrix(u1$sim)
#plot(as.raster(m))
```
### Running h-clust on the resulting dissimiliarity matrix
```{r hclust}
disSim <- hclust(as.dist(1 - u1$similarityMatrix), method = 'mcquitty')
clusters <- cutree(disSim, k = 3)
table(clusters, truth = as.numeric(iris[[5]]))
```
## Similarity Randomer Forest (SmerF)
### Create the similarity matrix for training
```{r load-dat01}
train <- sort(c(sample(1:50, 25), sample(51:100, 25), sample(101:150, 25)))
test <- setdiff(1:150, train)
X <- iris[, -5]
Y <- 1 - as.matrix(dist(X[train, ]))
Ytest <- 1 - as.matrix(dist(X[test, ]))
```
### Run SmerF
```{r}
iris.forest <- RerF(X[train, ], Y, task = 'similarity', num.cores = 4L)
Yhat <- Predict(X[test, ], iris.forest, num.cores = 4L)
```
### Frobenius norm of $Y - \hat{Y}$
```{r}
(f.iris <- norm(Ytest - Yhat, "F"))
max(abs(Ytest - Yhat))
```
## Forest Packing with fast-RerF
```{r fpRerF}
X <- mnist$Xtrain
Y <- mnist$Ytrain
## runs in under a minute on all of MNIST
system.time({
f <- fpRerF(X, Y, forestType = "binnedBaseRerF", numTreesInForest = 100, numCores = 4)
})
training.pred <- fpPredict(f, X)
testing.pred <- fpPredict(f, mnist$Xtest)
(training.error <- mean(training.pred != Y))
(testing.error <- mean(testing.pred != mnist$Ytest))
```
<!-- calcium-spike data are not properly documented at this time, waiting on @jasonkyuyim TBD by 20180813 -->
<!--
### Train Structured RerF (S-RerF) for spike train inference:
Similar to S-RerF for image classification except now in the Spike Train setting. 500 samples were stimulated from the following AR(2) model:
$$c_t = \sum_{i}{\gamma_i c_{t-i} + s_t},\quad s_t \sim \text{Poisson}(0.01)$$
$$y_t = a \ c_t + \epsilon_t, \ \ \ \ \epsilon_t \sim \mathcal{N}(0, 1)$$
where $\gamma_1 = 1.7, \gamma_2 = -0.712$, $a = 1$. We sampled such that the were an equal number of spikes and non-spikes in the datasets. S-RerF was trained on these samples by computing local feature patches across the time series windows.
```{r spike-train, eval = FALSE, include = FALSE}
data(calcium_spike)
ts.train <- calcium_spike$train[, -ncol(calcium_spike$train)]
ts.test <- calcium_spike$test[, -ncol(calcium_spike$test)]
ts.train.Y <- ts.train[,ncol(ts.train)]
ts.test.Y <- ts.test[,ncol(ts.test)]
ts.train <- calcium_spike$train
ts.test <- calcium_spike$test
ts.train.X <- ts.train[,1:(ncol(ts.train)-1)]
ts.train.Y <- ts.train[,ncol(ts.train)]
ts.test.X <- ts.test[,1:(ncol(ts.test)-1)]
ts.test.Y <- ts.test[,ncol(ts.test)]
# p is number of dimensions, d is the number of random features to evaluate, patch.min is min width of a time series patch to sample, and patch.max is the max width of the patch.
p <- ncol(ts.train.X)
d <- ceiling(sqrt(p))
patch.min <- 1L
patch.max <- 5L
forest <- RerF(ts.train.X, ts.train.Y, num.cores = 1L,
mat.options = list(p = p,
d = d,
random.matrix = "ts-patch",
patch.min = patch.min,
patch.max = patch.max),
seed = 1L)
predictions <- Predict(ts.test.X, forest, num.cores = 1L)
ts.error.rate <- mean(predictions != ts.test.Y)
```
**Expected output**
```{r, eval = FALSE, include = FALSE}
ts.error.rate
```
-->
---