{"id":96,"date":"2015-01-29T17:31:00","date_gmt":"2015-01-29T17:31:00","guid":{"rendered":"http:\/\/gallego.ca\/blog\/?p=96"},"modified":"2022-04-23T19:56:45","modified_gmt":"2022-04-23T19:56:45","slug":"getting-started-with-random-forests-in-r","status":"publish","type":"post","link":"http:\/\/gallego.ca\/myblog\/getting-started-with-random-forests-in-r\/","title":{"rendered":"Getting started with Random Forests in R"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This is a step-by-step intro to Random Forests using R, in particular using RStudio. RStudio is a powerful and open source integrated development environment (IDE) for R, available on Windows, Mac and Linux. It supports direct code excecution via a console, as well as an editor with code completion and other tools for plotting and managing your development workspace.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">RStudio supports installation of all current available R packages hosted by the CRAN package repository.<br>I will provide instructions on how to install some basic packages required to start training a classifier and doing common data visualization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Install RStudio<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To begin, Download an installer of RStudio for your OS, and follow the instructions. Installers for Supported Platforms can be found here:<br>* https:\/\/www.rstudio.com\/products\/rstudio\/download\/<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Gather some R packages<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">All R functions and datasets are stored in packages. In order to access a package functionality, it&#8217;s necessary to load it first. RStudio comes with a collection of packages pre-installed. To see this, start Rstudio and type on the console:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">library()\n\n# You can also view your R version by typing:\nR.version\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">##                _                            \n## platform       x86_64-w64-mingw32           \n## arch           x86_64                       \n## os             mingw32                      \n## system         x86_64, mingw32              \n## status                                      \n## major          2                            \n## minor          15.3                         \n## year           2013                         \n## month          03                           \n## day            01                           \n## svn rev        62090                        \n## language       R                            \n## version.string R version 2.15.3 (2013-03-01)\n## nickname       Security Blanket\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To install additional packages, all you need is access to the internet and use install.packages() and update.packages() functions.<br>I will demonstrate how to build a Random forest classifier with Anderson&#8217;s Iris Data. So we need to get the following packages:<br>* caret (short for Classification And REgression Training)<br>* ggplot<br>* randomForest<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">install.packages(\"caret\", libs_only = TRUE)\ninstall.packages(\"ggplot2\")\ninstall.packages(\"randomForest\")\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># then load the libraries we just install\nlibrary(caret)\nrequire(ggplot2)\nlibrary(randomForest)\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Format the data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Fisher\u0092s or Anderson\u0092s) iris data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.<br>The Iris data is available as part of the R Datasets Package, so no external data acquisition is needed.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># load the data\niris = data.frame(iris)\n\n# simply format categorical variables as such\niris$Species = as.factor(iris$Species)\nsummary(iris)\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">##   Sepal.Length   Sepal.Width    Petal.Length   Petal.Width \n##  Min.   :4.30   Min.   :2.00   Min.   :1.00   Min.   :0.1  \n##  1st Qu.:5.10   1st Qu.:2.80   1st Qu.:1.60   1st Qu.:0.3  \n##  Median :5.80   Median :3.00   Median :4.35   Median :1.3  \n##  Mean   :5.84   Mean   :3.06   Mean   :3.76   Mean   :1.2  \n##  3rd Qu.:6.40   3rd Qu.:3.30   3rd Qu.:5.10   3rd Qu.:1.8  \n##  Max.   :7.90   Max.   :4.40   Max.   :6.90   Max.   :2.5  \n##        Species  \n##  setosa    :50  \n##  versicolor:50  \n##  virginica :50  \n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recursive Feature Elimination (RFE) via caret<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The following will perform feature selection and random forest parameter tuning in a training set.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In caret, RFE consists on a resampling-based function. There are several arguments:<br>* x, a matrix or data frame of predictor variables<br>* y, a vector (numeric or factor) of outcomes<br>* sizes, a integer vector for the specific subset sizes that should be tested<br>rfeControl, a list of options that can be used to specify the model and the methods for prediction, ranking, resampling etc.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">set.seed(2)\nnvars = ncol(iris)-1\nx = iris[c(1,2,3,4)]\ny = iris$Species\nsubsets &lt;- c(1:nvars)\nctrl &lt;- rfeControl(functions = rfFuncs, # use Random Forest variable importance feature selection\n                   method = \"boot\", # use bootstrap sampling \n                   number = 50,\n                   verbose = FALSE)\n\nirisrfe &lt;- rfe(x, y,\n                 sizes = subsets,\n                 rfeControl = ctrl)\nprint(irisrfe)\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">## Recursive feature selection\n## \n## Outer resampling method: Bootstrapped (50 reps) \n## \n## Resampling performance over subset size:\n## \n##  Variables Accuracy Kappa AccuracySD KappaSD Selected\n##          1    0.939 0.907     0.0333  0.0502         \n##          2    0.959 0.938     0.0244  0.0367        *\n##          3    0.958 0.936     0.0247  0.0372         \n##          4    0.957 0.935     0.0236  0.0356         \n## \n## The top 2 variables (out of 2):\n##    Petal.Width, Petal.Length\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To plot:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">p &lt;- ggplot(irisrfe$results, aes(x=irisrfe$results$Variables, y=irisrfe$results$Accuracy))\np + geom_line() + xlab(\"Number of subset variables\") + ylab(\"Overall Accuracy (50 bootstraps)\")\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-4.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-4-300x300.png\" alt=\"\" class=\"wp-image-98\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-4-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-4-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-4.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The results indicate that the best subset of features consists of 2 variables: Petal.Width, Petal.Length<br>However, this is for discriminating among 3 species of flowers, i.e we&#8217;re dealing with a muti-classification problem.<br>TO illustrate the basics of ROC curves it&#8217;s better to use a binary classification dataset. The iris dataset has 2 well separated classes (setosa vs. versicolor) and 2 classes with some overlap (versicolor vs. virginica)<br>First, subset the datasets:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Iris binary classification, 4 features, 2 classes, n1=50\/100, n2=50\/100\n# C1 = iris setosa, C2 = iris versicolor dataset iris3, datasets is the\n# same as in iris but it's formatted differently 'Anderson's Iris Data --\n# 2 species well separated classes'\nirisdata1 = data.frame(rbind(iris3[, , 1], iris3[, , 2]), Species = rep(c(\"setosa\", \n    \"versicolor\"), rep(50, 2)))\npairs(irisdata1[1:4], main = \"Anderson's Iris Data -- 2 species well separated classes\", \n    pch = 21, bg = c(\"red\", \"blue\")[unclass(irisdata1$Species)])\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-1-300x300.png\" alt=\"\" class=\"wp-image-48\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-1-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-1-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-1.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"># 'Anderson's Iris Data -- 2 species some overlaps in classes'\nirisdata2 = data.frame(rbind(iris3[, , 2], iris3[, , 3]), Species = rep(c(\"versicolor\", \n    \"virginica\"), rep(50, 2)))\npairs(irisdata2[1:4], main = \"Anderson's Iris Data -- 2 species some overlaps in classes\", \n    pch = 21, bg = c(\"red\", \"green3\")[unclass(irisdata2$Species)])\n\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-3.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-3-300x300.png\" alt=\"\" class=\"wp-image-50\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-3-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-3-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2014\/11\/unnamed-chunk-2-3.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"># we can run feature selection again in the subsetted dataset2\nx = irisdata2[c(1:4)]\ny = irisdata2$Species\nirisrfe2 &lt;- rfe(x, y, sizes = subsets, rfeControl = ctrl)\nprint(irisrfe2)\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">## Recursive feature selection\n## \n## Outer resampling method: Bootstrapped (50 reps) \n## \n## Resampling performance over subset size:\n## \n##  Variables Accuracy Kappa AccuracySD KappaSD Selected\n##          1    0.903 0.805     0.0393  0.0791         \n##          2    0.925 0.849     0.0418  0.0830        *\n##          3    0.925 0.847     0.0403  0.0811         \n##          4    0.925 0.848     0.0407  0.0820         \n## \n## The top 2 variables (out of 2):\n##    Petal.L., Petal.W.\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># plot\np &lt;- ggplot(irisrfe2$results, aes(x = irisrfe2$results$Variables, y = irisrfe2$results$Accuracy))\np + geom_line() + xlab(\"Number of subset variables\") + ylab(\"Overall Accuracy (50 bootstraps)\")\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-53.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-53-300x300.png\" alt=\"\" class=\"wp-image-99\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-53-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-53-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-53.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The next step is to used this subset of selected features to train the classifier. To do this, we need to tune the parameters of the classifier, in our case; we want to tune to the number of trees in the forest (ntree) and the number of variables to use at each split node (mtry)<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># we start by leaving out independent test samples out of the data we are going to use to generate the model\n# subset based on selected features\nirisdata_sel = irisdata2[c(\"Petal.W.\",\"Petal.L.\",\"Species\")]\n\nset.seed(1)\ninTrain &lt;- createDataPartition(y = irisdata_sel$Species, ## the outcome data are needed\n                               p = .75, ## The percentage of data in the training set\n                               list = FALSE) ## The format of the results\n\n# createDataPartition does a stratified random split of the data. To partition the data:\ntraining &lt;- irisdata_sel[ inTrain,]\ntesting &lt;- irisdata_sel[-inTrain,]\n\n# we'll use bootstrap samples of the data\nbootControl &lt;- trainControl(method = \"boot\", \n                number = 50, # number of boostrap iterations\n                savePredictions = TRUE,\n                p = 0.75,   # % of data points of the training data sampled with replacement\n                classProbs = TRUE,\n                returnResamp = \"all\",\n                verbose = FALSE,\n                summaryFunction = twoClassSummary) # this allow us to obtain ROC metrics\n\n# the caret package allow us to train the number of mtry variables, as following:\nRFGrid &lt;- expand.grid(.mtry=c(2:ncol(training)-1) )\n\nRFfit &lt;- train(Species ~ ., data = training,\n                        method = \"rf\",\n                        trControl = bootControl,\n                        tuneGrid = RFGrid,\n                        returnData = TRUE,\n                        fitBest = TRUE,\n                        verbose=FALSE,\n                        metric=\"ROC\")\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">## Loading required package: pROC\n## Type 'citation(\"pROC\")' for a citation.\n## \n## Attaching package: 'pROC'\n## \n## The following object(s) are masked from 'package:stats':\n## \n##     cov, smooth, var\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">print(RFfit$finalModel)\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">## Call:\n##  randomForest(x = x, y = y, mtry = param$mtry, returnData = TRUE,      fitBest = TRUE, verbose = FALSE) \n##                Type of random forest: classification\n##                      Number of trees: 500\n## No. of variables tried at each split: 1\n## \n##         OOB estimate of  error rate: 5.26%\n## Confusion matrix:\n##            versicolor virginica class.error\n## versicolor         36         2     0.05263\n## virginica           2        36     0.05263\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The caret function train, has optimized our forest with ntree = 500 and mtry=2, and achieves a 6.58% out-of-bag (OOB) error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we can asses our generalization error on the held-out test cases:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">confusionMatrix(predict(RFfit, newdata = testing), testing$Species)\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">## Confusion Matrix and Statistics\n## \n##             Reference\n## Prediction   versicolor virginica\n##   versicolor         11         0\n##   virginica           1        12\n##                                         \n##                Accuracy : 0.958         \n##                  95% CI : (0.789, 0.999)\n##     No Information Rate : 0.5           \n##     P-Value [Acc &gt; NIR] : 1.49e-06      \n##                                         \n##                   Kappa : 0.917         \n##  Mcnemar's Test P-Value : 1             \n##                                         \n##             Sensitivity : 0.917         \n##             Specificity : 1.000         \n##          Pos Pred Value : 1.000         \n##          Neg Pred Value : 0.923         \n##              Prevalence : 0.500         \n##          Detection Rate : 0.458         \n##    Detection Prevalence : 0.458         \n##       Balanced Accuracy : 0.958         \n##                                         \n##        'Positive' Class : versicolor    \n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># To do an ROC, we need the output probabilities of the classifier\n# independent of the threshold used\noutprob_train = predict(RFfit, newdata = training, type = \"prob\")\noutprob_test = predict(RFfit, newdata = testing, type = \"prob\")\noutprob_train$obs = training$Species\noutprob_test$obs = testing$Species\n\nROCF_train &lt;- plot.roc(outprob_train$obs, outprob_train$versicolor, col = \"#000086\", \n    lty = 1)\npar(new = TRUE)\nROCF_test &lt;- plot.roc(outprob_test$obs, outprob_test$versicolor, col = \"#860000\", \n    lty = 2, main = \"ROC for mass max cvFolds\")\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-7.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-7-300x300.png\" alt=\"\" class=\"wp-image-100\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-7-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-7-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-7.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\">print(ROCF_train$auc)\n## Area under the curve: 1\n\nprint(ROCF_test$auc)\n## Area under the curve: 0.997\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Our trained Random forest, achieves 95.8% overall accuracy on independent datasets. The AUC is 100% in the training set and 99.6% in the testset. This is a really great performance!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To have more control over the tuning parameters, we can use the Random Forest package directly and do a grid search or even build individual tress. To use the Random Forest package directly, i&#8217;ve created a simple function:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">trainRF &lt;- function(mtry, ntree, training, testing) {\n    experiment.rf &lt;- randomForest(Species ~ ., data = training, importance = TRUE, \n        ntree = ntree, mtry = mtry, do.trace = FALSE, proximity = TRUE, keep.forest = TRUE)\n    \n    # get oobError\n    oobError = as.numeric(experiment.rf$err.rate[ntree, 1])\n    \n    # get missclassError\n    Trainresults = confusionMatrix(predict(experiment.rf, newdata = training), \n        training$Species)\n    Testresults = confusionMatrix(predict(experiment.rf, newdata = testing), \n        testing$Species)\n    TrainE = 1 - as.numeric(Trainresults$overall[1])\n    TestE = 1 - as.numeric(Testresults$overall[1])\n    \n    output &lt;- list(oobError = oobError, TrainE = TrainE, TestE = TestE)\n    return(output)\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">First test: look at varying Forest complexity (ntree) and (mtry)<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"># Design the grid search space\ntrainparam = expand.grid(mtry = c(1:2), ntree = c(10, seq(25, 250, 50), 500, 750, 1000))\ngridsearch = data.frame()\n\n# start the search\nfor (k in 1:nrow(trainparam)) {\n    aparam = trainparam[k, ]\n    RF_results = trainRF(aparam$mtry, aparam$ntree, training, testing)\n    gridsearch = rbind(gridsearch, c(aparam, RF_results))\n}\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># final results\nprint(gridsearch)\n\n##     mtry ntree oobError  TrainE   TestE\n## 2      1    10  0.05333 0.02632 0.04167\n## 21     2    10  0.06667 0.01316 0.04167\n## 3      3    10  0.06667 0.02632 0.04167\n## 4      4    10  0.05263 0.01316 0.04167\n## 5      1    25  0.06579 0.00000 0.04167\n## 6      2    25  0.06579 0.00000 0.04167\n## 7      3    25  0.06579 0.01316 0.04167\n## 8      4    25  0.05263 0.00000 0.04167\n## 9      1    75  0.06579 0.00000 0.04167\n## 10     2    75  0.06579 0.00000 0.04167\n## 11     3    75  0.06579 0.00000 0.04167\n## 12     4    75  0.06579 0.00000 0.04167\n## 13     1   125  0.06579 0.01316 0.04167\n## 14     2   125  0.06579 0.00000 0.04167\n## 15     3   125  0.06579 0.00000 0.04167\n## 16     4   125  0.06579 0.00000 0.04167\n## 17     1   175  0.05263 0.00000 0.04167\n## 18     2   175  0.06579 0.00000 0.04167\n## 19     3   175  0.06579 0.00000 0.04167\n## 20     4   175  0.05263 0.00000 0.04167\n## 211    1   225  0.06579 0.00000 0.04167\n## 22     2   225  0.05263 0.00000 0.04167\n## 23     3   225  0.06579 0.00000 0.04167\n## 24     4   225  0.06579 0.00000 0.04167\n## 25     1   500  0.05263 0.00000 0.04167\n## 26     2   500  0.05263 0.00000 0.04167\n## 27     3   500  0.06579 0.00000 0.04167\n## 28     4   500  0.06579 0.00000 0.04167\n## 29     1   750  0.05263 0.00000 0.04167\n## 30     2   750  0.06579 0.00000 0.04167\n## 31     3   750  0.06579 0.00000 0.04167\n## 32     4   750  0.06579 0.00000 0.04167\n## 33     1  1000  0.06579 0.00000 0.04167\n## 34     2  1000  0.06579 0.00000 0.04167\n## 35     3  1000  0.06579 0.00000 0.04167\n## 36     4  1000  0.06579 0.00000 0.04167\n<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># Do some plots plot with color\ntrellis.par.set(caretTheme())\ngridsearch$mtry &lt;- as.factor(gridsearch$mtry)\n# plot TrainError\np1 &lt;- ggplot(gridsearch, aes(x = ntree, y = TrainE)) + geom_line(aes(colour = mtry)) + \n    scale_y_continuous(breaks = seq(0, max(gridsearch$TrainE), 0.01))\np1 + theme_bw() + theme(panel.grid.minor = element_line(colour = \"grey\", linetype = \"dotted\"))\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-91.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-91-300x300.png\" alt=\"\" class=\"wp-image-101\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-91-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-91-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-91.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\"># plot TestError\np2 &lt;- ggplot(gridsearch, aes(x = ntree, y = TestE)) + geom_line(aes(colour = mtry)) + \n    scale_y_continuous(breaks = seq(0, max(gridsearch$TestE), 0.05))\np2 + theme_bw() + theme(panel.grid.minor = element_line(colour = \"grey\", linetype = \"dotted\"))\n<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-92.png\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-92-300x300.png\" alt=\"\" class=\"wp-image-102\" srcset=\"http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-92-300x300.png 300w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-92-150x150.png 150w, http:\/\/gallego.ca\/myblog\/wp-content\/uploads\/sites\/2\/2015\/07\/unnamed-chunk-92.png 504w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Final Remarks<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This was intended to be a short tutorial in getting started with Random Forest in R. There is more you can do at the control level of the trees in R, but it was not demonstrated in this tutorial. Below are some useful links to further reading on the topics reviewed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Some useful Links:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:1.125em\">* For a graphical guide to getting-started with RStudio: <a title=\"http:\/\/dss.princeton.edu\/training\/RStudio101.pdf\" href=\"http:\/\/dss.princeton.edu\/training\/RStudio101.pdf\" target=\"_blank\" rel=\"noopener\">http:\/\/dss.princeton.edu\/training\/RStudio101.pdf<\/a><br>* For a more detail tutorial on RFE and other topics visit <a title=\"http:\/\/topepo.github.io\/caret\/rfe.html\" href=\"http:\/\/topepo.github.io\/caret\/rfe.html\" target=\"_blank\" rel=\"noopener\">http:\/\/topepo.github.io\/caret\/rfe.html<\/a><br>* To access ggplot2 documentation: <a title=\"http:\/\/docs.ggplot2.org\/0.9.3\/index.html\" href=\"http:\/\/docs.ggplot2.org\/0.9.3\/index.htmlhttp:\/\/\" target=\"_blank\" rel=\"noopener\">http:\/\/docs.ggplot2.org\/0.9.3\/index.html<\/a><br>* Leo Breiman and Adele Cutler Random Forest website: <a title=\"http:\/\/www.stat.berkeley.edu\/~breiman\/RandomForests\/cc_papers.htm\" href=\"http:\/\/www.stat.berkeley.edu\/~breiman\/RandomForests\/cc_papers.htm\" target=\"_blank\" rel=\"noopener\">http:\/\/www.stat.berkeley.edu\/~breiman\/RandomForests\/cc_papers.htm<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a step-by-step intro to Random Forests using R, in particular using RStudio. RStudio is a powerful and open source integrated development environment (IDE) for R, available on Windows, Mac and Linux. It supports direct code excecution via a console, as well as an editor with code completion and other tools for plotting and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":25,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,4,8],"tags":[],"class_list":["post-96","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-visualization","category-machine-learning","category-r"],"_links":{"self":[{"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/posts\/96","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/comments?post=96"}],"version-history":[{"count":9,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/posts\/96\/revisions"}],"predecessor-version":[{"id":135,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/posts\/96\/revisions\/135"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/media\/25"}],"wp:attachment":[{"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/media?parent=96"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/categories?post=96"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/gallego.ca\/myblog\/wp-json\/wp\/v2\/tags?post=96"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}